def diffPhaseContrast(dpc_path, dpc_phase, dpc_amp): # do something here phase = np.zeros((256, 256)) amp = np.zeros((256, 256)) cx = 128 cy = 128 cx1 = 100 cy1 = 100 cx2 = 140 cy2 = 140 radius = 60 ** 2 radius1 = 10 ** 2 radius2 = 15 ** 2 for i in np.arange(256): for j in np.arange(256): if ((cx - i) * (cx - i) + (cy - j) * (cy - j)) <= radius: phase[i][j] = 128 amp[255 - i][255 - j] = 128 if ((cx1 - i) * (cx1 - i) + (cy1 - j) * (cy1 - j)) <= radius1: phase[i][j] = 255 amp[255 - i][255 - j] = 255 if ((cx2 - i) * (cx2 - i) + (cy2 - j) * (cy2 - j)) <= radius2: phase[i][j] = 64 amp[255 - i][255 - j] = 64 # save to files im.fromarray(np.uint8(phase)).save(dpc_phase) im.fromarray(np.uint8(amp)).save(dpc_amp)
def onSave(self): file_opt = options = {} options['filetypes'] = [('Image Files', '*.tif *.jpg *.png')] options['initialfile'] = 'myImage.jpg' options['parent'] = self.parent fname = tkFileDialog.asksaveasfilename(**file_opt) Image.fromarray(np.uint8(self.Ilast)).save(fname)
def render(x): assert(x.ndim == 2) x = x[:(len(x)/25)*25] # make the number of rows a multiple of 25 for visualization purposes s = 12 x = x.reshape([x.shape[0],s,s,3]) # normalize (and map nonlinearly to make images look nice on the screen) x = x - x.mean() x = x / x.std() x = numpy.tanh(0.5*x)*0.5+0.5 # create the mosaic h,w = x.shape[0]/25,25 x = x.reshape([h,w,s,s,x.shape[3]]) z = numpy.ones([h,w,s+2,s+2,x.shape[4]]) z[:,:,1:-1,1:-1,:] = x z = z.transpose([0,2,1,3,4]).reshape([h*(s+2),w*(s+2),3]) # display the mosaic b = io.BytesIO() Image.fromarray((z*255).astype('byte'),'RGB').save(b,format='png') return lambda: IPython.core.display.Image(data=b.getvalue(),format='png', embed=True)
def from_data_with_min_max(cls, slug, data, extent, min_value, max_value, cdict=None): """ Create GeoImage from slug and data. """ tmp_base = tempfile.mktemp() #print('tmp_base: %s' % tmp_base) #print('step 1') # Step 1: save png + pgw in RD if cdict is None: cdict = { 'red': ((0.0, 51./256, 51./256), (0.5, 237./256, 237./256), (1.0, 83./256, 83./256)), 'green': ((0.0, 114./256, 114./256), (0.5, 245./256, 245./256), (1.0, 83./256, 83./256)), 'blue': ((0.0, 54./256, 54./256), (0.5, 170./256, 170./256), (1.0, 83./256, 83./256)), } colormap = mpl.colors.LinearSegmentedColormap('something', cdict, N=1024) normalize = mpl.colors.Normalize(vmin=min_value, vmax=max_value) rgba = colormap(normalize(data), bytes=True) #rgba[:,:,3] = np.where(rgba[:,:,0], 153 , 0) if 'depth' in slug: # Make transparent where depth is zero or less rgba[:,:,3] = np.where(np.greater(data, 0), 255, 0) Image.fromarray(rgba).save(tmp_base + '.png', 'PNG') write_pgw(tmp_base + '.pgw', extent) return cls.from_rd_png(tmp_base, slug, extent)
def write_image(img, fname, apply_gamma=False): """Save a float-3 numpy array image to a file. Supported formats: PNG, JPEG, and others; see PIL docs for more. Image can be 3-channel, which is interpreted as RGB, or can be 1-channel, which is greyscale. Can optionally specify that the image should be gamma-encoded prior to writing it out; this should be done if the image contains linear pixel values, to make the image look "normal". Args: img: Numpy image array data. fname: Path of file to save to; the extension specifies the format. apply_gamma: (Optional) apply gamma to the image prior to writing it. """ if apply_gamma: img = apply_lut_to_image(img, DEFAULT_GAMMA_LUT) (h, w, chans) = img.shape if chans == 3: Image.fromarray((img * 255.0).astype(numpy.uint8), "RGB").save(fname) elif chans == 1: img3 = (img * 255.0).astype(numpy.uint8).repeat(3).reshape(h,w,3) Image.fromarray(img3, "RGB").save(fname) else: raise its.error.Error('Unsupported image type')
def convolve_png(filename, kernel, **kwargs): '''convolve_png(str filename, ndarray kernel, **kwargs) -> int32 ndarray A convenience function: reads data from the PNG, convolves, colors, and then returns the PIL Image object. Options: prefilter: a function ndarray -> ndarray to apply before the convolution postfilter: for after the convolution colormap: a function ndarray -> (ndarray data, str mode) which does its own normalizing and also returns the necessary mode flag to construct an Image. saveas: a filename to write the image into, in addition to returning the ndarray max: an int, normalize to this maximum ''' options = Options(colormap = lambda data: (igreyscale(data), 'I'), prefilter = lambda data: data, postfilter = lambda data: data, saveas = None) options.update(kwargs) conv = options.postfilter(convolve_f1d(options.prefilter(png_to_ndarray(filename)), kernel)) colored, mode = options.colormap(conv.astype('int32')) if options.saveas is not None: Image.fromarray(colored, mode=mode).save(options.saveas) return conv
def deconvolve_dir(src_dir, dest_dir, OD_vector): if (src_dir == dest_dir): print "src_dir and dest_dir must be different ! ABORTING" return for c in os.listdir(src_dir): if (not os.path.exists(os.path.join(dest_dir, c))): os.mkdir(os.path.join(dest_dir, c)) for _file in os.listdir(os.path.join(src_dir, c)): try: im_src = Image.open(os.path.join(src_dir, c, _file)) im_src.verify() except IOError: print "warning filename %s is not an image" % os.path.join(src_dir, c, _file) im_src = Image.open(os.path.join(src_dir, c, _file)) #TODO check image type im_src = np.array(im_src, dtype = np.float) print im_src.shape im_dest = deconvolve_im_array(im_src, OD_vector) if (im_dest.shape[2] == 4): im_dest = Image.fromarray(im_dest, 'RGBA') else: im_dest = Image.fromarray(im_dest, 'RGB') im_dest.save(os.path.join(dest_dir, c, _file), "PNG") test = Image.open(os.path.join(dest_dir, c, _file)) print test.mode
def Export(self, data, outFile, xslice, yslice, zslice, metadata=None, events = None, origName=None): #nframes = (zslice.stop - zslice.start)/zslice.step outDir = os.path.splitext(outFile)[0] os.mkdir(outDir) i = 0 for frameN in range(zslice.start,zslice.stop, zslice.step): im = data[xslice, yslice, frameN].squeeze()[None, :,:] for fN in range(frameN+1, frameN+zslice.step): im += data[xslice, yslice, fN].squeeze()[None, :,:] Image.fromarray(im.squeeze().astype('uint16'), 'I;16').save(os.path.join(outDir, 'frame_%03d.tif'%i)) i += 1 if not metadata == None: xmd = MetaDataHandler.XMLMDHandler(mdToCopy=metadata) if not origName == None: xmd.setEntry('cropping.originalFile', origName) xmd.setEntry('cropping.xslice', xslice.indices(data.shape[0])) xmd.setEntry('cropping.yslice', yslice.indices(data.shape[1])) xmd.setEntry('cropping.zslice', zslice.indices(data.shape[2])) xmlFile = os.path.splitext(outFile)[0] + '.xml' xmd.writeXML(xmlFile)
def show_plot(data, synth): a_v = data.cumsum() #print "Amount of white pixels: ", a_v[len(a_v) - 1] # debug - to see the spongious structure num_imgs = len(os.listdir('/home/rodrigo/result/')) if(show_figure): fig = plt.figure() a=fig.add_subplot(2,2,1) plt.imshow((data[num_imgs/2]), cmap=plt.gray()) plt.title('Real') a=fig.add_subplot(2,2,2) plt.imshow(Image.fromarray(synth[num_imgs/2])) plt.title('Synthetic') a=fig.add_subplot(2,2,3) plt.imshow((data[:, num_imgs/4, :]), cmap=plt.gray()) plt.title('Real') a=fig.add_subplot(2,2,4) plt.imshow(Image.fromarray(synth[:, num_imgs/4, :])) plt.title('Synthetic') plt.show() np.save('synth.npy', synth)
def conn_tests(solver, save_format): print '>>>', datetime.now(), 'Begin conn tests' solver.net.set_phase_test() solver.test_nets[0].share_with(solver.net) net = solver.test_nets[0] save_dir = save_format.format(solver.iter) os.mkdir(save_dir) hist = np.zeros((2, 2)) for fname in fnames_val: net.forward() im = Image.fromarray(net.blobs['left-conn'].data[0].argmax(0) .astype(np.uint8), mode='P') im.save(os.path.join(save_dir, fname + '-L.png')) im = Image.fromarray(net.blobs['top-conn'].data[0].argmax(0) .astype(np.uint8), mode='P') im.save(os.path.join(save_dir, fname + '-T.png')) h, _ , _ = np.histogram2d(net.blobs['left-gt'].data[0, 0].flatten(), net.blobs['left-conn'].data[0].argmax(0).flatten(), bins = 2, range=[[0, 2], [0, 2]]) hist += h h, _ , _ = np.histogram2d(net.blobs['top-gt'].data[0, 0].flatten(), net.blobs['top-conn'].data[0].argmax(0).flatten(), bins = 2, range=[[0, 2], [0, 2]]) hist += h print '>>>', datetime.now(), 'Iteration', solver.iter, 'overall accuracy', \ np.diag(hist).sum() / hist.sum() print '>>>', datetime.now(), 'Iteration', solver.iter, 'total IU', \ hist[1, 1] / (hist[0, 1] + hist[1, 0] + hist[1, 1]) solver.net.set_phase_train()
def overlay(self, frame, alpha): im0 = Image.fromarray(self.source_frame) im1 = Image.fromarray(frame) self.overlays = (im0, im1) self.alpha = alpha self.refresh = True
def ptychography(pty_path, pty_out1, pty_out2): """ Ptychography reconstruction routine """ #do something here pty1 = np.zeros((256, 256)) pty2 = np.zeros((256, 256)) cx = 128 cy = 128 cx1 = 100 cy1 = 100 cx2 = 140 cy2 = 140 radius = 60**2 radius1 = 10**2 radius2 = 15**2 for i in np.arange(256): for j in np.arange(256): if ((cx - i)*(cx - i) + (cy - j)*(cy - j)) <= radius: pty1[i][j] = 128 pty2[255-i][255-j] = 128 if ((cx1 - i)*(cx1 - i) + (cy1 - j)*(cy1 - j)) <= radius1: pty1[i][j] = 255 pty2[255-i][255-j] = 255 if ((cx2 - i)*(cx2 - i) + (cy2 - j)*(cy2 - j)) <= radius2: pty1[i][j] = 64 pty2[255-i][255-j] = 64 #save to files im.fromarray(np.uint8(pty1)).save(pty_out1) im.fromarray(np.uint8(pty2)).save(pty_out2)
def test_process(self): """ Rotate an actual batch. """ self.testee.setup(None, 'seq_one') batch_sz = 1 batchin = create_mbatch(batch_sz, 128, 128) img = numpy.cast['uint8'](batchin[0, :, :, 0:3]) img = Image.fromarray(img) #img.show(title="TestRotationAdj.original") batch = self.testee.process(batchin) self.assertEqual(batch.shape, (batch_sz, 128, 128, 4)) for i in range(batch_sz): im_rgb = batch[i, :, :, 0:3] im_rgb = numpy.cast['uint8'](im_rgb) if i < 10: img = Image.fromarray(im_rgb) if show_im: img.show( title="TestRotationAdj.test_vertical %d" % i) batchin = create_mbatch(batch_sz, 128, 128) batch = self.testee.accumulate(batchin) self.assertEqual(batch.shape, (batch_sz*self.testee.transf_count(), 128, 128, 4)) for i in range(batch.shape[0]): im_rgb = batch[i, :, :, 0:3] im_rgb = numpy.cast['uint8'](im_rgb) if i < 16: img = Image.fromarray(im_rgb) if show_im: img.show( title="TestRotationAdj.test_vertical %d" % i)
def save(self, data): if _im is None: raise NotImplementedError d = data[0] if isinstance(d, _RGB): s = list(d.shape) s.append(3) # c = _core.ndarray(s, buffer=d.data, dtype=_core._uint8) c = _core.zeros(s, dtype=_core._uint8) # print d.red c[...,0] = d.get_red(dtype=_core._uint8) c[...,1] = d.get_green(dtype=_core._uint8) c[...,2] = d.get_blue(dtype=_core._uint8) d = c try: if d.dtype == _core.int64: im = _im.fromarray(d, mode='I') else: im = _im.fromarray(d) except: if d.dtype == _core._uint16: # trap a known PIL 1.1.7 TIFF bug im = _im.frombuffer("I;16", tuple(reversed(d.shape)), d.data, 'raw', "I;16", 0, 1) else: raise im.save(self.name)
def test_both(self): """ Flip batches both vertically and horizontally. """ self.testee.horizontal = True self.testee.vertical = True self.testee.setup(None, 'seq_one') batch_sz = 5 batchin = create_mbatch(batch_sz, 128, 128) im_rgb = batchin[0, :, :, 0:3] im_rgb = numpy.cast['uint8'](im_rgb) img = Image.fromarray(im_rgb) #img.show() batch = self.testee.process(batchin) self.assertEqual(batch.shape, (batch_sz, 128, 128, 4)) for i in range(batch_sz): im_rgb = batch[i, :, :, 0:3] im_rgb = numpy.cast['uint8'](im_rgb) if i == 0: img = Image.fromarray(im_rgb) if show_im: img.show(title="TestFlipAdj.test_vertical %d" % i) batch = self.testee.accumulate(batchin) self.assertEqual(batch.shape, (batch_sz*4, 128, 128, 4)) self.assertTrue(numpy.any(batch[0] != batch[batch_sz/2+1])) for i in range(batch.shape[0]): im_rgb = batch[i, :, :, 0:3] im_rgb = numpy.cast['uint8'](im_rgb) if i >= 0: img = Image.fromarray(im_rgb) if show_im: img.show(title="TestFlipAdj.test_vertical %d" % i)
def writeImage(time, data, width, height, rowSizeBytes, bitDepth, components, field): # FIXME this assumes 8bit RGB image. Check bitDepth, components, field flatarray = numpy.fromstring(data, numpy.uint8, rowSizeBytes*height) outImage = numpy.array(numpy.flipud(numpy.reshape(flatarray, (height, width, 3)))) filepath = NamedTemporaryFile( prefix="outputBufferCallbackTest-", suffix=".jpg" ) Image.fromarray(outImage).save( filepath.name )
def npy2tif(path): data = _np.load(path) filebase = _os.path.splitext(path)[0] print 'File base name:', filebase if data.dtype is not _np.float32: data = _np.array(data, dtype=_np.float32) if data.ndim == 2: saveto = filebase + '.tif' print 'Creating file', saveto image = Image.fromarray(data, mode='F') image.save(saveto) else: try: _os.mkdir(filebase) except WindowsError as e: if e.errno != 17: raise except: raise n_digits = len(str(data.shape[0])) min = data.min() max = data.max() for i in xrange(data.shape[0]): formatstr = '0' + str(n_digits) + 'd' filename = '{0:' + formatstr + '}.tif' filepath = _os.path.join(filebase, filename.format(i)) image = Image.fromarray(data[i], mode='F') image.save(filepath)
def getTargets(screen):#TODO '''Get the words from the screen. (This will be the hard part.)''' (width,height)=screen.size #screen.save('screen'+str(cnt)+'.png') blobs=screen.convert('L') blobs=np.array(blobs) #blobs=screen. leftmost=0 targets=[] for y in range(width): for x in range(height): if(blobs[x,y]<20): print(x,y) if(y+200<=width): targets.append(np.copy(blobs[x-20:x+20,y:y+200])) blobs[x-30:x+30,y:y+200]=255 #Image.fromarray(blobs).show() #raw_input('') if leftmost==0: leftmost=y cnt=0 for target in targets: Image.fromarray(target).save('target'+str(cnt)+'.png') cnt=cnt+1 return targets '''words=[]
def get_objectome64alpha_images(): dirname = OBJ64ALPHA_PATH dset = objectome64_alpha(internal_canonical=True) meta = dset.meta if not os.path.isdir(dirname): print 'Creating directory : ' + dirname os.makedirs(dirname) with open (os.path.join(dirname, 'metadata.pkl'), 'w') as _f: pk.dump(meta, _f) img_res, img_size = 1024, 256 dataset_obj = objectome64_fg(internal_canonical=True) dataset_bg = objectome64_bg(internal_canonical=True) obj_imgs = dataset_obj.get_images({'dtype':'uint8', 'size': (img_res, img_res,4), 'normalize':False, 'mode':'RGBA'}, get_models=True) bg_imgs = dataset_bg.get_images({'dtype':'uint8', 'size': (img_res, img_res), 'normalize':False, 'mode':'L'}, get_models=True) IMGS = [] for i,m in enumerate(meta): background = Image.fromarray(bg_imgs[i]) foreground = obj_imgs[i] foreground[:,:,-1] = foreground[:,:,-1] * m['objalpha'][0] foreground = Image.fromarray(foreground) background.paste(foreground, (0, 0), foreground) IMGS.append(np.asarray(background)) save_images(dirname, IMGS, meta) return
def siftflow_segment(dataDir): fileList = np.sort(os.listdir(dataDir)) for item in fileList: if item.startswith('data_batch_'): batchPath = os.path.join(dataDir, item) dic = unpickle(batchPath) dic['segmentations'] = [] for im in dic['data']: tf1, tf2 = './temp-in.ppm', './temp-out.ppm' Image.fromarray(im).save(tf1) os.system('./segment 0.5 500 20 %s %s > /dev/null' % (tf1, tf2)) imSeg = np.array(Image.open(tf2)) pixelList = list(imSeg.T.swapaxes(1,2).reshape((3,-1))) pixelList = zip(pixelList[0],pixelList[1],pixelList[2]) pixelDic = {} for i,pixel in enumerate(pixelList): if pixelDic.has_key(pixel): pixelDic[pixel].append(i) else: pixelDic[pixel] = [i] seg = np.zeros(im.shape[:2], np.int32).flatten() for i,p in enumerate(pixelDic.keys()): seg[np.array(pixelDic[p])] = i + 1 dic['segmentations'].append(seg.reshape(im.shape[:2])) pickle(batchPath, dic)
def inverse_filtering(img, width, height): """Инверсная фильтрация""" k = 0.002 eps = 1E-5 pic_a = numpy.asarray(img) F = numpy.fft.fftshift(numpy.fft.fft2(pic_a)) N = 5 + 3 * numpy.random.randn(len(F), len(F[0])) H_values = [[H(k, i, j) for j in xrange(len(F[0]))] for i in xrange(len(F))] N = numpy.fft.fftshift(numpy.fft.fft2(N)) G = [[hij * fij + nij for hij, fij, nij in zip(hi, fi, ni)] for hi, fi, ni in zip(H_values,F, N)] degraded_image = abs(numpy.fft.ifft2(numpy.fft.ifftshift(G))) H_reversed = [[1 / Hij if Hij > eps else 0 for Hij in Hi] for Hi in H_values] # H_reversed = [] # for i in xrange(len(H_values)): # H_reversed.append([]) # for j in xrange(len(H_values[0])): # if H_values[i][j] > eps: # H_reversed[i].append(1 / H_values[i][j]) # else: # print 'zero!' # H_reversed[i].append(0) # print H_reversed[0] # print G[0] restored_image = [[gij * hrij for gij, hrij in zip(gi, hri)] for gi, hri in zip(G, H_reversed)] restored_image = abs(numpy.fft.ifft2(numpy.fft.ifftshift(restored_image))) bad_pic = Image.fromarray(degraded_image.astype(numpy.uint8)) bad_pic.save('images/bmstu_inv_noised.png') good_pic = Image.fromarray(numpy.asarray(restored_image).astype(numpy.uint8)) good_pic.save('images/bmstu_inv_restored.png')
def get_alpha_images(): dataset_obj = objectome64s100alpha(internal_canonical=True) dataset_bg = objectome64s100bg(internal_canonical=True) img_res, img_size = 1024, 256 obj_imgs = dataset_obj.get_images({'dtype':'uint8', 'size': (img_res, img_res,4), 'normalize':False, 'mode':'RGBA'}, get_models=True) bg_imgs = dataset_bg.get_images({'dtype':'uint8', 'size': (img_res, img_res), 'normalize':False, 'mode':'L'}, get_models=True) IMGS = [] alphaval = [] for i in xrange(obj_imgs.shape[0]): background = Image.fromarray(bg_imgs[i]) foreground = obj_imgs[i] tmp_alpha = np.random.uniform(0.25,1) foreground[:,:,-1] = foreground[:,:,-1] * tmp_alpha alphaval.append(tmp_alpha) foreground = Image.fromarray(foreground) background.paste(foreground, (0, 0), foreground) IMGS.append(np.asarray(background)) meta = dataset_obj.meta names = meta.dtype.names + ('obj_alpha',) formats = zip(*meta.dtype.descr)[1] + ('float',) META = tb.tabarray(records=[tuple(meta[i]) + (alphaval[i],) for i in range(len(meta))], names=names, formats=formats) return IMGS, META
def load_data(): print 'loading...' #image_size, train_x, train_y, test_x, test_y = cPickle.load(open('../../Data/lfw/data.dat','rb')) image_size, train_x, train_y, test_x, test_y = cPickle.load(open('../../Data/mnist/lfw_liked_data.dat','rb')) l = train_x.shape[0] ind = numpy.random.permutation(l) print train_x.shape train_x = train_x[ind] train_y = train_y[ind] train_y_0 = (train_y+1)/2 test_y_0 = (test_y+1)/2 import Image Image.fromarray(256*train_x[0].reshape(-1, image_size)).show() def get_shared(data_x, data_y, data_y_0, borrow = True): shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX), borrow=borrow) shared_y = theano.shared(numpy.asarray(data_y.flatten(), dtype=theano.config.floatX), borrow=borrow) shared_y_0 = theano.shared(numpy.asarray(data_y_0.flatten(), dtype=theano.config.floatX), borrow=borrow) return shared_x, T.cast(shared_y, 'int32'), T.cast(shared_y_0, 'int32') print 'loading done' datasets = [get_shared(train_x, train_y, train_y_0), get_shared(test_x, test_y, test_y_0)] return image_size, datasets
def getVideoFrames(path,step=1,preprocess=None) : # NOTE: Online preprocessing of each frame is advised. This should be implemented in order to deal with big video files. ''' Extracts a list of frames (PIL Images) from a video file. Params: path - of the input video file (OPTIONAL) step - takes one frame every 'step' frames preprocess - tuple of parameters (n.cols,n.rows,inverse,normalize) for the greyscaleProcess function. Online preprocessing of each frame. ''' vc = cv2.VideoCapture(path) c=0 frames = [] if preprocess != None : cols,rows,inv,norm = preprocess if vc.isOpened(): rval , frame = vc.read() frame = Image.fromarray(frame) if preprocess == None else ASCII_Image.greyscaleProcess(Image.fromarray(frame),cols,rows,inverse=inv,normalize=norm) frames.append(frame) else: rval = False while rval: rval, frame = vc.read() if c % step == 0 and rval : frame = Image.fromarray(frame) if preprocess == None else ASCII_Image.greyscaleProcess(Image.fromarray(frame),cols,rows,inverse=inv,normalize=norm) frames.append(frame) c = c + 1 vc.release() return frames
def reconstruct_from_labels(image_id): im = np.zeros((imgwidth, imgheight), dtype=np.uint8) f = open(label_file) lines = f.readlines() image_id_str = '%.3d_' % image_id for i in range(1, len(lines)): line = lines[i] if not image_id_str in line: continue tokens = line.split(' ') id = tokens[0] prediction = int(tokens[1]) tokens = id.split('_') i = int(tokens[1]) j = int(tokens[2]) je = min(j+w, imgwidth) ie = min(i+h, imgheight) if prediction == 0: adata = np.zeros((w,h)) else: adata = np.ones((w,h)) im[j:je, i:ie] = binary_to_uint8(adata) Image.fromarray(im).save('prediction_' + '%.3d' % image_id + '.png')
def createCumulativeManaImages(self, cards): global actualManas cumManaImages = {} manaThreshold = 245 for i in range(11) + [12, 20]: cumManaImages[i] = np.zeros((40, 30), dtype=np.uint8) for i in range(len(cards)): card = cards[i] mana = actualManas[i] if card.golden: manaImage = imgToBW( card.cardImage.crop(self.screenshotParser.gManaLocation[card.cardType]), self.screenshotParser.manaThreshold, ) else: manaImage = imgToBW( card.cardImage.crop(self.screenshotParser.manaLocation), self.screenshotParser.manaThreshold ) cumManaImage = cumManaImages[mana] for row in range(len(manaImage)): for col in range(len(manaImage[row])): if manaImage[row, col] == 0xFF: cumManaImage[row, col] += 1 cumManaImages = self.normaliseManaImages(cumManaImages) for i in range(11) + [12, 20]: Image.fromarray(cumManaImages[i]).save("./compImages/mana-" + str(i) + ".bmp", "BMP")
def tomography(tomo_path, tomo_vol_path): """ Tomography reconstruction routine """ #do something here tomo = np.zeros((256, 256)) cx = 128 cy = 128 cx1 = 100 cy1 = 100 cx2 = 140 cy2 = 140 radius = 60**2 radius1 = 10**2 radius2 = 15**2 for k in np.arange(4): for i in np.arange(256): for j in np.arange(256): if ((cx - i)*(cx - i) + (cy - j)*(cy - j)) <= radius: tomo[i][j] = 128 - k*10 if ((cx1 - i)*(cx1 - i) + (cy1 - j)*(cy1 - j)) <= radius1: tomo[i][j] = 255 - k*10 if ((cx2 - i)*(cx2 - i) + (cy2 - j)*(cy2 - j)) <= radius2: tomo[i][j] = 64 + k*10 #save to files filename = tomo_vol_path + str(k) + '.tif' im.fromarray(np.uint8(tomo)).save(filename)
def test_process(self): """ Adjust a batch. """ self.testee.setup(None, 'seq_one') batch_sz = 5 batch = create_mbatch(batch_sz, 128, 128) batch = self.testee.process(batch) for i in range(batch_sz): im_rgb = batch[i, :, :, 0:3] im_rgb = numpy.cast['uint8'](im_rgb) if i < 1: img = Image.fromarray(im_rgb) if show_im: img.show(title="TestGcaAdj.test_vertical %d" % i) batch = create_mbatch(batch_sz, 128, 128) batch = self.testee.accumulate(batch) self.assertEqual(batch.shape, (batch_sz*self.testee.transf_count(), 128, 128, 4)) for i in range(batch.shape[0]): im_rgb = batch[i, :, :, 0:3] im_rgb = numpy.cast['uint8'](im_rgb) if i < 10: img = Image.fromarray(im_rgb) if show_im: img.show(title="TestGcaAdj.test_vertical %d" % i)
def flip_patches(patches): """ Flip patches (either 90 degrees left right, or 180 degrees). Assume that patches come in pairs. """ import theano n, d = patches.shape dx = int(np.sqrt(d)) tmp = patches.reshape((n, dx, dx)) result = np.zeros((n, d), dtype=theano.config.floatX) for j in xrange(n/2): flips = np.random.rand() if flips < 0.5: # no flipping result[2*j, :] = patches[2*j] result[2*j + 1, :] = patches[2*j + 1] else: p1 = img.fromarray(tmp[2*j]) p2 = img.fromarray(tmp[2*j + 1]) # determine random flip rnd1 = np.random.rand() if rnd1 < 0.33: flip = img.ROTATE_90 elif rnd1 < 0.66: flip = img.ROTATE_180 else: flip = img.ROTATE_270 p1 = p1.transpose(flip) p2 = p2.transpose(flip) result[2*j, :] = np.asarray(p1).ravel() result[2*j+1,:] = np.asarray(p2).ravel() return result
def show(arr, shape=None): """show - Create new temp figure and show array contents as image. Usage: show(arr, shape=None) Input: arr - Either numpy nd-array or PIL image. shape - (optional) if arr is a flat array, shape is a tuple with the desired shape, in (rows, cols) format. Output: -NONE- but a figure is created. """ import Image import numpy as np if shape: arr = arr.reshape(shape) if type(arr) is np.ndarray: Image.fromarray( (arr.astype(float) * 255 / arr.max()).astype(np.uint8) ).show() else: try: arr.show() except AttributeError: print "Unknown array type"
def dm3ToTiff(filename, newpath=getcwd()): dm3f = dm3.DM3(filename+".dm3", debug=0) A = dm3f.imagedata # get some useful tag data and print print "datatype:", dm3f.tags["root.ImageList.1.ImageData.DataType"] # A = rescale(A) # im = Image.fromarray(A, mode="I;16") # "I;16" is PIL's 16 bit unsigned int mode - do we need this for dm3 files? im = Image.fromarray(A) im.save(newpath+"/"+filename+".tif", format="TIFF") return
def showTwoRowsOfDigits(digits): assert len(digits) > 1, "Need at least two digits..." assert (len(digits) % 2) == 0, "Need an even number of digits..." width = len(digits) / 2 digits[0].shape = (28, 28) digits[width].shape = (28, 28) topRow = digits[0] botRow = digits[width] for i in range(1, width): digits[i].shape = (28, 28) digits[width + i].shape = (28, 28) topRow = np.hstack((topRow, digits[i])) botRow = np.hstack((botRow, digits[width + i])) bothRows = np.vstack((topRow, botRow)) im = Image.fromarray(bothRows, 'L') im.show()
def hsv(self, image, url_args): args = { "hue": url_args.get("hue", 0.0) / 360.0, "saturation": url_args.get("saturation", 0.0) / 255.0, "value": url_args.get("value", 0.0) / 255.0 } print "HSV" arr = numpy.array(image) rgb = arr[...,0:3] / 255.0 hsv = rgb2hsv(rgb) hsv[...,0] += float(args["hue"]) hsv[...,0] = hsv[...,0] % 1.0 hsv[...,1] = numpy.clip(hsv[...,1] + float(args["saturation"]), 0.0, 1.0) hsv[...,2] = numpy.clip(hsv[...,2] + float(args["value"]), 0.0, 1.0) arr[...,0:3] = hsv2rgb(hsv) * 255.0 return Image.fromarray(arr)
def PCA(paths): imgs = [] for name in paths: imgs.append(np.array(Image.open(name), 'f')) imgsize = imgs[0].size # print(imgsize) allImg = np.concatenate((imgs[0].reshape(1, imgsize), imgs[1].reshape(1, imgsize)), axis=0) covImage = np.cov(allImg) D, V = np.linalg.eig(covImage) if D[0] > D[1]: a = V[:, 0] / V[:, 0].sum() else: a = V[:, 1] / V[:, 1].sum() res = imgs[0]*a[0]+imgs[1]*a[1] result = Image.fromarray(np.uint8(res)) return result
def make_image_slices(imgfilename, num_rows=300): imgslices = make_slices(data, num_rows) outfilename_list = [] outfilename_fmt = "{0}_s{1}.png" for idx, n in enumerate(imgslices): print n.shape outfilename = outfilename_fmt.format(basename, idx) outimg = Image.fromarray(n, "L") outimg.save(outfilename) print "wrote", outfilename outfilename_list.append(outfilename) return outfilename_list
def playvideo(root, imagelabel, queue, var): global im p = Process(target=image_capture, args=(task,)) p.start() update_all(root, imagelabel, queue, p, var) root.mainloop() p.terminate() if var.get()==False: try: cv2.imwrite("capturedFrame.jpg",im[:, :, ::-1]) a = Image.fromarray(im) imagelabel.configure(image=a) imagelabel._image_cache = im except Exception,e: print e
def main( ): if len(sys.argv) != 2: print("You should really read the source...\n\nUsage: rotate.py <Imagename>\n") sys.exit(-1) # Open, convert to grayscale, convert to numpy array img = Image.open(sys.argv[1]).convert("L") i = numpy.fromstring(img.tostring(),dtype="uint8").reshape(img.size[1],img.size[0]) # Rotate & convert back to PIL Image irot = rotate_image(i) rotimg = Image.fromarray(irot,mode="L") # Save and display rotimg.save("rotated.png") rotimg.show()
def Make_cinema_source(self): for elem in range(130): viewer_trans(-transX, -transY, -self.z_ - transZ) viewer_rotate(360 / 130.0, 0, 10, 0) viewer_trans(transX, transY, self.z_ + transZ) data_pkg = self.func_name(*self.args) viewer_data, viewer_dtype = collect_result(data_pkg) self.widget.setData(viewer_data, viewer_data.shape[1], viewer_data.shape[0]) a = Image.fromarray(self.widget.data) a.save("./resultsss/result-" + str('%03d' % (self.ret_image_cnt)) + ".tif") self.ret_image_cnt = self.ret_image_cnt + 1
def screenshot(self, fn=None, A=False): if A: channels = "RGBA" glc = GL_RGBA else: channels = "RGB" glc = GL_RGB img = glReadPixels(0, 0, self.width, self.height, glc, GL_UNSIGNED_BYTE) #print len(img), self.width, self.height, len(channels) img = frombuffer(img, dtype='u1').reshape((self.height, self.width, len(channels))) img = Image.fromarray(img[::-1]) #img = Image.frombuffer(channels, (self.width, self.height), img, "raw", channels, 0, 0) if fn: img.save(fn) return img
def numpyToImage(numpyfile, imagefile): dt = np.dtype([('quadkey', 'S15'), ('x', np.int16), ('y', np.int16), ('z', np.int16), ('objid', np.int32), ('typeid', np.int16)]) data = np.loadtxt( numpyfile, delimiter=",", dtype=dt ) #load the numpy data (this will be in a single array of quadkey,x,y,z,objid,typeid arcpy.AddMessage(data['x']) minx = min(data['x']) #get the minx value maxx = max(data['x']) #get the maxx value miny = min(data['y']) #get the miny value maxy = max(data['y']) #get the maxy value arcpy.AddMessage("minx:" + str(minx) + " maxx:" + str(maxx) + " miny:" + str(miny) + " maxy:" + str(maxy)) width = maxx - minx + 1 #get the width of the resulting image height = maxy - miny + 1 #get the height of the resulting image arcpy.AddMessage("width:" + str(width) + " height:" + str(height)) data['x'].__isub__( minx ) #change the x values to be zero based by subtracting the minx value data['y'].__imul__( -1) #do the same with the y values using a different calculation data['y'].__iadd__(maxy) arcpy.AddMessage(data['x']) arcpy.AddMessage(data['y']) arcpy.AddMessage(data['z']) pixels = coo_matrix( (data['z'], (data['y'], data['x'])), shape=(height, width) ).todense( ) #convert the sparse array into a dense matrix, i.e. by adding in all of the zero values arcpy.AddMessage(pixels) image = Image.fromarray( pixels) #create the output tif from the pixel values image.save(imagefile) #save the image to a file f = open( imagefile[:-3] + "tfw", 'w') #open the tfw file to write the georeferencing coordinates in f.write( str(CELLSIZE) + "\n0.0000000000\n0.0000000000\n-" + str(CELLSIZE) + "\n" ) #you need to set the y cell size as a minus number otherwise the image is upside down topleftx = (minx * CELLSIZE) - OFFSET + (CELLSIZE / 2 ) #get the top left x coordinate toplefty = (maxy * CELLSIZE) - OFFSET + (CELLSIZE / 2 ) #get the top left y coordinate f.write(str(topleftx) + "\n") #top left x coordinate f.write(str(toplefty) + "\n") #top left y coordinate f.close() #close the file
def GPU(): im = Image.open(sys.argv[1]) print sys.argv[1], ": ", im.format, im.size, im.mode, '\n' pixels = np.array(im.getdata()).reshape(im.size[0], im.size[1], 3) print pixels print pixels.size #pixels = np.array(im) #gpu = cuda.mem_alloc(pixels.nbytes) #cuda.memcpy_htod(gpu, pixels) kernel = SourceModule(""" #define MAX_PIXEL_VALUE 255 #define THRESHOLD 50 __global__ void process_pixel(int *pixels, int N) { // int id = blockDim.x*blockIdx.x + threadIdx.x; int idx = threadIdx.x; if (id < N) { if ( pixels[id] > THRESHOLD ) { pixels[id] = MAX_PIXEL_VALUE; } } /* if ((r[id] > THRESHOLD) && (g[id] > THRESHOLD) && (b[id] > THRESHOLD)) { r[id] = MAX_PIXEL_VALUE; g[id] = MAX_PIXEL_VALUE; b[id] = MAX_PIXEL_VALUE; } */ } """) func = kernel.get_function("process_pixel") func(cuda.InOut(pixels), np.int32(pixels.size), block=(128, 1, 1), grid=(1, 1)) #newpixels = np.zeros_like(pixels) #cuda.memcpy_dtoh(newpixels, gpu) print pixels im2 = Image.fromarray(np.uint8(pixels)) im2.save("post.png")
def dem2img(self, path, file): # Source LIDAR DEM file source = path + file # Load the ASCII DEM into a numpy array arr = np.loadtxt(source, skiprows=6) # Convert the numpy array to a PIL image im = Image.fromarray(arr).convert('L') # Enhance the image im = ImageOps.equalize(im) im = ImageOps.autocontrast(im) # Begin building our color ramp palette = [] # Hue, Saturaction, Value # color space h = .67 s = 1 v = 1 step = h / 256.0 for i in range(256): rp, gp, bp = colorsys.hsv_to_rgb(h, s, v) r = int(rp * 255) g = int(gp * 255) b = int(bp * 255) palette.extend([r, g, b]) h -= step # Apply the palette to the image im.putpalette(palette) im = im.convert('RGB') # Output image file img_path = os.path.dirname(os.getcwd( )) + '/webGIS/static/showLidar/images/' + file.split('.')[0] + '.jpg' # Save the image im.save(img_path) image = '/static/showLidar/images/' + file.split('.')[0] + '.jpg' return image
def real_time_classification(): cam = cv2.VideoCapture(0) while True: ret_val, frame = cam.read() cv2.imshow("webcam", frame) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) pil_img = Image.fromarray(frame) input_img = data_transforms(pil_img).reshape([1, 3, 224, 224]).to(device) #input_img = input_img.reshape([1,3,224,224]) #input_img = input_img.to(device) out = model_ft(input_img) softmax_result = F.softmax(out) top1_prob, top1_label = torch.topk(softmax_result, 1) print(top1_prob, labels.get(int(top1_label))) cv2.waitKey(1) cv2.destroyAllWindows()
def createImages(list_of_ims): for im in list_of_ims: nii = nibabel.load(im) data = nii.get_data() x = data.shape[1] data_slice = data[x / 2, :, :] new_name = im.strip().split('/')[-1][:-3] + 'png' ## we have to normalize the slice to be in the range 0-255 max_val = float(np.max(data_slice[:])) data_slice /= max_val data_slice *= 255 data_slice = np.array(data_slice, dtype='uint8') image = Image.fromarray(data_slice, 'L') image.save(new_name)
def process_image(self, rgb_image): object_description = [] bytes = rgb_image.tobytes() im = mig.fromarray(rgb_image) imgByteArr = io.BytesIO() im.save(imgByteArr, format='PNG') imgByteArr = imgByteArr.getvalue() image = client.image(content=imgByteArr) features = [ Feature(FeatureTypes.LABEL_DETECTION, 1), Feature(FeatureTypes.FACE_DETECTION, 1) ] annotations = image.detect(features) for label in annotations.labels: object_description.append([label.description, label.score]) return object_description
def save_image(tensor, filename, nrow=4, padding=2, mean=None, std=None): """ Saves a given Tensor into an image file. If given a mini-batch tensor, will save the tensor as a grid of images. """ from PIL import Image tensor = tensor.cpu() grid = make_grid(tensor, nrow=nrow, padding=10, pad_value=1) if not mean is None: ndarr = grid.mul(std).add(mean).mul(255).byte().transpose( 0, 2).transpose(0, 1).numpy() else: ndarr = grid.mul(0.5).add(0.5).mul(255).byte().transpose( 0, 2).transpose(0, 1).numpy() im = Image.fromarray(ndarr) im.save(filename)
def quantize_without_scipy(self, image): """" This function can be used if no scipy is availabe. It's 7 times slower though. """ w,h = image.size px = np.asarray(image).copy() memo = {} for j in range(w): for i in range(h): key = (px[i,j,0],px[i,j,1],px[i,j,2]) try: val = memo[key] except KeyError: val = self.convert(*key) memo[key] = val px[i,j,0],px[i,j,1],px[i,j,2] = val return Image.fromarray(px).convert("RGB").quantize(palette=self.paletteImage())
def compute_hist(net, save_dir, dataset): n_cl = net.blobs['upscore'].channels os.mkdir(save_dir) hist = np.zeros((n_cl, n_cl)) for fname in fnames_val[dataset]: net.forward() h, _, _ = np.histogram2d( net.blobs['gt'].data[0, 0].flatten(), net.blobs['upscore'].data[0].argmax(0).flatten(), bins=n_cl, range=[[0, n_cl], [0, n_cl]]) hist += h im = Image.fromarray(net.blobs['upscore'].data[0].argmax(0).astype( np.uint8), mode='P') im.save(os.path.join(save_dir, fname + '.png')) return hist
def crop_img(filename, image): flag = 0 pic_name = filename[:filename.find("_")] print pic_name text_name = filename[:filename.find(".")] + ".txt" src = "C:\\3d-Model\\bin\\segmentation_files\\" + text_name f = open("C:\\3d-Model\\bin\\curr_proj.txt", "r") #Read whole file into data proj_name = f.read() main_directory = proj_name + "\\input" print main_directory image_data = np.asarray(image) image_data_bw = image_data.max(axis=2) non_empty_columns = np.where(image_data_bw.max(axis=0) > 0)[0] non_empty_rows = np.where(image_data_bw.max(axis=1) > 0)[0] cropBox = (min(non_empty_rows), max(non_empty_rows), min(non_empty_columns), max(non_empty_columns)) directory = "C:\segmentation_data\\" + filename print directory image1 = Image.open("C:\\3d-Model\\bin\\segmentation_files\\pic.jpg") image.load() image_data1 = np.asarray(image1) image_data_new = image_data1[cropBox[0]:cropBox[1] + 1, cropBox[2]:cropBox[3] + 1, :] new_image = Image.fromarray(image_data_new) folders = os.listdir(main_directory) print folders for files in folders: print files if files == pic_name: print main_directory + "\\" + pic_name dst = main_directory + "\\" + pic_name new_image.save(main_directory + "\\" + pic_name + "\\" + filename) shutil.copy(src, dst) os.remove(src) flag = 1 print "save" break if flag == 0: os.mkdir(main_directory + "\\" + pic_name) dst = main_directory + "\\" + pic_name new_image.save(main_directory + "\\" + pic_name + "\\" + filename) shutil.copy(src, dst) os.remove(src) print "made"
def saveDepthmapImage(self, depthMap, saved_file): im = depthMap["depthMap"] # print(im) im[np.where(im == max(im))[0]] = 0 # if min(im) < 0: # im[np.where(im < 0)[0]] = 0 im = im.reshape( (depthMap["height"], depthMap["width"])) # .astype(int) # display image img = Image.fromarray(im) # img.save(saved_file.replace(".tif", 'noflip.tif')) # img = img.transpose(Image.FLIP_LEFT_RIGHT) # img.save(saved_file, compression="tiff_deflate") # has bug, cannot read the results correctly img.save(saved_file) return img
def update_img(self, arg=None): # get image from pong system class img = self.pong_system.img if img is not None: # convert image to be friendly with tkinter # rearrange color channel # print arg # self.root.after(4000, self.update_img) b, g, r = cv2.split(img) img = cv2.merge((r, g, b)) im = PilImage.fromarray(img) self.imgtk = ImageTk.PhotoImage(image=im) self.img_panel.configure(image=self.imgtk)
def set_image(self, vals): dim = self.dimensions[0] * self.dimensions[1] nImg = np.sqrt(vals[0, ].size / dim) if nImg > 1 and nImg.is_integer(): # Show a mosaic of images nImg = np.int(nImg) self.vals = np.zeros( (self.dimensions[0] * nImg, self.dimensions[1] * nImg)) for iR in range(nImg): for iC in range(nImg): currImgId = iR * nImg + iC currImg = np.reshape(vals[0, dim * currImgId + np.array(range(dim))], self.dimensions, order='F') firstRow = iR * self.dimensions[0] lastRow = (iR + 1) * self.dimensions[0] firstCol = iC * self.dimensions[1] lastCol = (iC + 1) * self.dimensions[1] self.vals[firstRow:lastRow, firstCol:lastCol] = currImg else: self.vals = np.reshape(vals[0, dim * self.selectImage + np.array(range(dim))], self.dimensions, order='F') if self.transpose: self.vals = self.vals.T # if not self.scale: # self.vals = self.vals if self.invert: self.vals = -self.vals # un-normalizing, for visualisation purposes: if self.presetSTD >= 0: # The Mean is assumed to be in the range (0,255) self.vals = self.vals * self.presetSTD + self.presetMean # Clipping the values: self.vals[self.vals < 0] = 0 self.vals[self.vals > 255] = 255 else: self.vals = 255 * (self.vals - self.vals.min()) / ( self.vals.max() - self.vals.min()) if not self.palette == []: # applying using an image palette (e.g. if the image has been quantized) self.vals = Image.fromarray(self.vals.astype('uint8')) self.vals.putpalette( self.palette ) # palette is a list, must be loaded before calling this function
def showImage(dictionary, outpath, imSize): images = dictionary.get('data') singleImage = images[:, 1] recon = np.zeros((imSize, imSize, 3), dtype=np.uint8) singleImage = singleImage.reshape((imSize * 3, imSize)) red = singleImage[0:imSize, :] blue = singleImage[imSize:2 * imSize, :] green = singleImage[2 * imSize:3 * imSize, :] recon[:, :, 0] = red recon[:, :, 1] = blue recon[:, :, 2] = green img = Image.fromarray(recon) img.save(outpath)
def createNevImg(): STAA = time.time() iW_size = W_num * W_size iH_size = H_num * H_size print root I = numpy.array(transfer(root+"lyf.jpg", iW_size, iH_size)) * 1.0 for i in range(W_num): for j in range(H_num): s = random.choice(aval) res = I[ j*H_size:(j+1)*H_size, i*W_size:(i+1)*W_size] * numpy.array(transfer(s, W_size, H_size))/255 I[ j*H_size:(j+1)*H_size, i*W_size:(i+1)*W_size] = res img = Image.fromarray(I.astype(numpy.uint8)) img = img.point(lambda i : i * 1.5) img.save("createNevImg_past.jpg") print "createNevImg Func time %s"%(time.time()-STAA)
def vis_db(db_dir, output_dir, image_dims, is_gray, img_num, save_flag): if os.path.exists(output_dir): print 'The folder already exists, would clean the folder' shutil.rmtree(output_dir) count = 0 h = leveldb.LevelDB(db_dir) datum = caffe_pb2.Datum() for key_val, ser_str in h.RangeIter(): count = count + 1 datum.ParseFromString(ser_str) rows = datum.height cols = datum.width channel = datum.channels label = datum.label print rows, cols, channel, label img_pre = np.fromstring(datum.data, dtype=np.uint8) img = img_pre.reshape(channel, rows, cols) img = img.transpose((1, 2, 0)) print img.shape # Change to BGR if not is_gray: img = img[:, :, (2, 1, 0)] else: img = img[:, :, 0] im = Image.fromarray(img) # Do resize here if image_dims is not None: im = im.resize((image_dims[1], image_dims[0]), Image.BILINEAR) if (count <= img_num): if save_flag: real_out_dir = os.path.join(output_dir, str(label)) mkdir_p(real_out_dir) im.save(os.path.join(real_out_dir, str(count) + '.jpg'), quality=100) else: im.show() else: break
def build_pil(im, height, mode=img.ANTIALIAS): """ """ pyr = [] for h in xrange(height - 1): pimg = img.fromarray(im) dx, dy = pimg.size low = pimg.resize((dx / 2, dy / 2), resample=mode) high = low.resize((dx, dy), resample=mode) diff = np.asarray(pimg, dtype=np.float) - np.asarray(high, dtype=np.float) pyr.append(diff) im = np.asarray(low, dtype=np.float) pyr.append(im) return pyr
def create_ns(tmp_imgpath, cnt_ns): global pyramids tmp_img = Image.open("%s/%s" % (coco_path, tmp_imgpath), 'r') pyramids = list(pyramid_gaussian(tmp_img, downscale=math.sqrt(2))) for i in range(len(pyramids)): if min(pyramids[i].shape[0], pyramids[i].shape[1]) < MinFace: del pyramids[i:] break # for j in range(4) : for j in range(36): # creating random index img_index = random.randint(0, len(pyramids) - 1) tmp_patch_num = (pyramids[img_index].shape[0] - 12 + 1) * (pyramids[img_index].shape[1] - 12 + 1) rand_index = random.randint(0, tmp_patch_num) # x, y position decoding row_max = pyramids[img_index].shape[0] col_max = pyramids[img_index].shape[1] row = 0 col = rand_index while (col >= col_max - 12 + 1): row = row + 1 col = col - (col_max - 12 + 1) flag = 0 # Rejecting Black and White image tmp_ns = pyramids[img_index][row:row + 12, col:col + 12] if not len(tmp_ns.shape) == 3: print " Gray Image. Skip " return 0 # Rejecting Positive Samples scale_factor = math.sqrt(2)**img_index tmp_ns = pyramids[img_index][row:row + 12, col:col + 12] tmp_ns = Image.fromarray((tmp_ns * 255.0).astype(np.uint8)) # tmp_ns = tmp_ns.resize( (12,12), Image.BICUBIC ) tmp_ns = tmp_ns.resize((12, 12), Image.BILINEAR) tmp_ns.save("%s/ns-%s.jpg" % (ns_path, cnt_ns + j)) return 1
def __writePNG(A, outname): """ Write PNG image using the Python Image Library (PIL). UNDER CONSTRUCTION Would be faster and more flexible than using I{Matplotlib}. @param A: Input array containing the values to be plotted. @param outname: Name of the output image file. """ import Image, ImageColor im = Image.new('RGBA', (1195, 1550), ImageColor.colormap['firebrick']) print A.shape Am = Image.fromarray(A, 'RGBA') im.paste(Am) im.save(outname + '.png', 'PNG')
def prepareImg(img, info, name, idx): data = np.zeros([len(info), 227, 227, 3]) if img.ndim == 2: img = np.tile(img[:, :, np.newaxis], (1, 1, 3)) elif img.shape[2] == 4: img = img[:, :, :3] j = 0 for b in info: idx.write(b[4]) window = getWindow(img, b) bIm = Image.fromarray(np.uint8(window)) data[j, :, :, :] = np.asarray(bIm.resize( (227, 227), Image.BICUBIC))[:, :, ::-1] # Resize and convert to BGR j += 1 data -= imagenet.IMAGENET_MEAN[14:241, 14:241, :] return data.swapaxes(2, 3).swapaxes(1, 2)
def read_raw_olshausen10_white(show=True): data=loadmat('original/olshausen/IMAGES.mat') IMAGES=data['IMAGES'] im_list=[] for i in range(10): im=IMAGES[:,:,i].copy() if show: imm=Image.fromarray(im) imm.show(command='display') im_list.append(im) var={'im':im_list,'im_scale_shift':[1.0,0.0]} return var