def generate(filename, w, h): print filename data = open(filename).read() thin_file = open(filename + 'SHADOWTHIN', 'w') thick_file = open(filename + 'SHADOWTHICK', 'w') bloat_file = open(filename + 'BLOAT', 'w') linesize = int(math.ceil(w/8.0)) charsize = linesize * h chars = [ data[i*charsize:(i+1)*charsize] for i in xrange(len(data)/charsize) ] for char in chars: charimg = PIL.fromstring('1', (w, h), char) paste = PIL.new('1', (w+4, h+4)) paste.paste(charimg, (2, 2)) bloat_file.write(paste.tostring()) img = Image(paste) img = img.convolve([ [0, 1, 0], [1, 1, 1], [0, 1, 0], ]) thin = PIL.fromstring('RGB', (w+4, h+4), img.toString()).convert('1').tostring() thin_file.write(thin) img = img.dilate() thick = PIL.fromstring('RGB', (w+4, h+4), img.toString()).convert('1').tostring() thick_file.write(thick)
def main(exrFilePath): exrFile = OpenEXR.InputFile(exrFilePath) dw = exrFile.header()['dataWindow'] pt = Imath.PixelType(Imath.PixelType.FLOAT) size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1) width, height = size[0], size[1] print size rstr = exrFile.channel("R", pt) gstr = exrFile.channel("G", pt) bstr = exrFile.channel("B", pt) rgbf = [Image.fromstring("F", size, exrFile.channel(c, pt)) for c in "RGB"] for im in rgbf: print im.getextrema() return red, green, blue = array.array("f", rstr), array.array("f", gstr), array.array("f", bstr) floats = array.array("f") for i in range(0, len(red)): floats.append(red[i]) floats.append(green[i]) floats.append(blue[i]) outFile = open(exrFilePath + "_" + str(width) + "x" + str(height) + ".float", "wb") floats.tofile(outFile) outFile.close() return rgbf = [Image.fromstring("F", size, exrFile.channel(c, pt)) for c in "RGB"] extrema = [im.getextrema() for im in rgbf] darkest = min([lo for (lo,hi) in extrema]) lighest = max([hi for (lo,hi) in extrema]) scale = 255 / (lighest - darkest) def normalize_0_255(v): return (v * scale) + darkest rgb8 = [im.point(normalize_0_255).convert("L") for im in rgbf] Image.merge("RGB", rgb8).save(exrFilePath + "_" + str(width) + "x" + str(height) + ".jpg")
def screen_capture(background = 0): global piece_name print piece_name filename = screen_capture_path + piece_name + screen_capture_type #expose() x0, y0, width, height = glGetIntegerv(GL_VIEWPORT) glReadBuffer(GL_FRONT) glPixelStorei(GL_PACK_ALIGNMENT, 1) if background: data = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE) im = Image.fromstring('RGB', (width, height), data) else: data = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE) im = Image.fromstring('RGBA', (width, height), data) #print im.getbbox() #im = im.crop(im.getbbox()) # Shrink as much as possible # fast but no outline im = im.crop(instructions.bbox(im)) #if scale != 1.0: # xsize, ysize = im.size # im = im.resize((xsize*scale, ysize*scale)) # Shrink if too big limit = 100.0 xsize, ysize = im.size max_extent = float(max(xsize, ysize)) if max_extent > limit: #scale = (1.0/0.853)*(0.6*limit/max_extent + 0.4) scale = (0.5*limit/max_extent + 0.5) print 'scale', scale im = im.resize((int(round(scale*xsize)), int(round(scale*ysize)))) im = instructions.outline(im, 4, (0, 0, 0)) im.transpose(Image.FLIP_TOP_BOTTOM).save(filename)
def SaveImage(filepath, image): if image.IsEmpty(): return logger.debug('Saving image as : {0}'.format(filepath)) ext = os.path.splitext(filepath)[-1] if ext == '.ktx': SaveKTXImage(filepath, image) elif ext == '.astc': SaveASTCImage(filepath, image) else: # use Image module format_dict = { OGLEnum.GL_RGB8 : 'RGB', OGLEnum.GL_RGBA8 : 'RGBA', } if image.internalformat not in format_dict: logger.error('Unexpected internal format when saving image as {1} : {0}'.format(OGLEnum.names[image.internalformat], filepath)) return try: Image.fromstring( format_dict[image.internalformat], (image.width, image.height), image.data).save(filepath) except IOError: logger.error('Failed to save image as {0}'.format(filepath)) return
def unpack_rle_565(rlefile, rawfile, function): if rawfile is None: if rlefile[-4] == ".": rawfile = rlefile[:-4] + ".raw" else: rawfile = rlefile + ".raw" if rawfile[-4] == ".": pngfile = rawfile[:-4] + ".png" else: pngfile = rawfile + ".png" sys.stderr.write("output: %s [%s]\n" % (rawfile, pngfile)) rle = open(rlefile, "rb") raw = open(rawfile, "wb") total = function(rle, raw) try: import Image except ImportError: return size = SIZE.get(total) if size is None: return data = open(rawfile, "rb") Image.fromstring("RGB", size, data.read(), "raw").save(pngfile) data.close()
def np2pil( im ): """ for grayscale - all values must be between 0 and 255. not sure about color yet. np2pil(im) """ #TODO: print 'util.np2cv: works for texseg.py' #TODO: print 'util.np2cv: more extensive tests would be useful' if len(im.shape) == 3: shp = im.shape channels = shp[2] height, width = shp[0], shp[1] elif len(im.shape) == 2: height, width = im.shape channels = 1 else: raise AssertionError("unrecognized shape for the input image. should be 3 or 2, but was %d." % len(im.shape)) if channels == 3: image = Image.fromstring( "RGB", (width, height), im.tostring() ) if channels == 1: im = np.array(im, dtype=np.uint8) #image = Image.fromarray(im) image = Image.fromstring( "L", (width, height), im.tostring() ) return image
def derivatives(self): # make array of numbers depthString = self.getDepthString() self.depth = Numeric.array(depthString, 'c')[2::4].astype(Numeric.Int8) self.dsq = Numeric.reshape(self.depth, (self.w, self.h)) self.fstD = Numeric.zeros((self.w, self.h), Numeric.Int8) self.sndD = Numeric.zeros((self.w, self.h), Numeric.Int8) self.deriv = Numeric.zeros((self.w, self.h), Numeric.Int8) for i in range(1, self.w-1): for j in range(1, self.h-1): a, b = self._derivatives(i,j) self.fstD[i][j] = a self.sndD[i][j] = b self.deriv[i][j] = max(a, b) # self.deriv = Numeric.choose( Numeric.greater(self.fstD,self.sndD), # (self.fstD,self.sndD) ) self.fstDim = Image.fromstring('P', (self.w,self.h), self.fstD.tostring()) self.sndDim = Image.fromstring('P', (self.w,self.h), self.sndD.tostring()) self.derivim = Image.fromstring('P', (self.w,self.h), self.deriv.tostring() )
def unpack_rle_565(rlefile, rawfile, function): if rawfile is None: if rlefile[-4] == '.': rawfile = rlefile[:-4] + '.raw' else: rawfile = rlefile + '.raw' if rawfile[-4] == '.': pngfile = rawfile[:-4] + '.png' else: pngfile = rawfile + '.png' sys.stderr.write('output: %s [%s]\n' % (rawfile, pngfile)) rle = open(rlefile, 'rb') raw = open(rawfile, 'wb') total = function(rle, raw) try: import Image except ImportError: return size = SIZE.get(total) if size is None: return data = open(rawfile, 'rb') Image.fromstring('RGB', size, data.read(), 'raw').save(pngfile) data.close()
def ConvertEXRToJPG(exrfile, jpgfile): File = OpenEXR.InputFile(exrfile) PixType = Imath.PixelType(Imath.PixelType.FLOAT) DW = File.header()['dataWindow'] Size = (DW.max.x - DW.min.x + 1, DW.max.y - DW.min.y + 1) RedStr = File.channel('R', PixType) GreenStr = File.channel('G', PixType) BlueStr = File.channel('B', PixType) Red = array.array('f', RedStr) Green = array.array('f', GreenStr) Blue = array.array('f', BlueStr) for I in range(len(Red)): Red[I] = EncodeToSRGB(Red[I]) for I in range(len(Green)): Green[I] = EncodeToSRGB(Green[I]) for I in range(len(Blue)): Blue[I] = EncodeToSRGB(Blue[I]) rgbf = [Image.fromstring("F", Size, Red.tostring())] rgbf.append(Image.fromstring("F", Size, Green.tostring())) rgbf.append(Image.fromstring("F", Size, Blue.tostring())) rgb8 = [im.convert("L") for im in rgbf] Image.merge("RGB", rgb8).save(jpgfile, "JPEG", quality=95)
def main(input_dir): output_dir = '/user/hadoop-trainer/output-ex1-0/%f' % (time.time()) hadoopy.run_hadoop(input_dir, output_dir, 'mean_image.py') print('Output Dir:[%s]' % (output_dir)) for key, val in hadoopy.hdfs_cat_tb(output_dir): fn = 'output-ex1-0-mean-%s.png' % ('-'.join(map(str, key))) print('Saving %s' % (fn)) Image.fromstring('L', key, val).save(fn)
def fmf2images(filename, imgformat='png', startframe=0,endframe=-1,interval=1, prefix=None,outdir=None,progress=False): base,ext = os.path.splitext(filename) if ext != '.fmf': print 'fmf_filename does not end in .fmf' sys.exit() path,base = os.path.split(base) if prefix is not None: base = prefix if outdir is None: outdir = path fly_movie = FlyMovieFormat.FlyMovie(filename) fmf_format = fly_movie.get_format() n_frames = fly_movie.get_n_frames() if endframe < 0 or endframe >= n_frames: endframe = n_frames - 1 fly_movie.seek(startframe) frames = range(startframe,endframe+1,interval) n_frames = len(frames) if progress: import progressbar widgets=['fmf2bmps', progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.ETA()] pbar=progressbar.ProgressBar(widgets=widgets, maxval=n_frames).start() else: pbar = None for count,frame_number in enumerate(frames): if pbar is not None: pbar.update(count) frame,timestamp = fly_movie.get_frame(frame_number) mono=False if (fmf_format in ['RGB8','RGB32f','ARGB8','YUV411','YUV422'] or fmf_format.startswith('MONO8:') or fmf_format.startswith('MONO32f:')): save_frame = imops.to_rgb8(fmf_format,frame) else: if fmf_format not in ['MONO8','MONO16']: warnings.warn('converting unknown fmf format %s to mono'%( fmf_format,)) save_frame = imops.to_mono8(fmf_format,frame) mono=True h,w=save_frame.shape[:2] if mono: im = Image.fromstring('L',(w,h),save_frame.tostring()) else: im = Image.fromstring('RGB',(w,h),save_frame.tostring()) f='%s_%08d.%s'%(os.path.join(outdir,base),frame_number,imgformat) im.save(f) if pbar is not None: pbar.finish()
def tBMP(r): if r.truecolor: im = Image.fromstring('RGB', (r.width, r.height), r.data) else: im = Image.fromstring('P', (r.width, r.height), r.indexed_data) im.putpalette(r.palette) buf = StringIO.StringIO() im.save(buf, 'png') return buf.getvalue()
def doLV(): for i in range(10): t = time.time() frame = ptpSession.GetLiveData() tRetrieved = time.time() viewport = Image.fromstring("RGB",(frame.header.bitmap.logical_width,frame.header.bitmap.logical_height),frame.viewportRGB,'raw','RGB') bitmap = Image.fromstring("RGBA",(frame.header.bitmap.logical_width,frame.header.bitmap.logical_height),frame.bitmapRGBA,'raw','RGBA') viewport.save(r'd:\temp\test-vp.jpg') bitmap.save(r'd:\temp\test-bm.jpg') print 'live data retrieved in %.2fs'%(tRetrieved-t)
def main(): try: filename = sys.argv[1] except: print 'Usage: %s fmf_filename' % sys.argv[0] sys.exit() path,ext = os.path.splitext(filename) if ext != '.fmf': print 'fmf_filename does not end in .fmf' sys.exit() fly_movie = FlyMovieFormat.FlyMovie(filename) n_frames = fly_movie.get_n_frames() fmf_format = fly_movie.get_format() fmf = fly_movie delays = numpy.array([]) for frame_number in range(n_frames): frame,timestamp = fmf.get_frame(frame_number) mono=False if (fmf_format in ['RGB8','ARGB8','YUV411','YUV422'] or fmf_format.startswith('MONO8:') or fmf_format.startswith('MONO32f:')): save_frame = imops.to_rgb8(fmf_format, frame) else: if fmf_format not in ['MONO8','MONO16']: warnings.warn('converting unknown fmf format %s to mono'%( fmf_format,)) save_frame = imops.to_mono8(fmf_format,frame) mono=True h, w = save_frame.shape[:2] if mono: im = Image.fromstring('L',(w,h),save_frame.tostring()) else: im = Image.fromstring('RGB',(w,h),save_frame.tostring()) f = '%s_%08d.%s'%(os.path.join("./", "zbartmp"), frame_number, 'bmp') im.save(f) try: TS = subprocess.check_output(['zbarimg', '-q', f]) ts = float(TS[8:].strip()) except OSError: raise except: ts = float('nan') delay = timestamp-ts delays = numpy.append(delays,[delay]) print "ds: % 14.6f cam: % 14.6f delay: % 8.6f" % (ts, timestamp, delay) os.unlink(f) print "delay mean: % 8.6f std: % 8.6f" % (delays[~numpy.isnan(delays)].mean(),delays[~numpy.isnan(delays)].std()) print "delay max: % 8.6f min: % 8.6f" % (delays[~numpy.isnan(delays)].max(),delays[~numpy.isnan(delays)].min()) print "%i of %i frames used" % (len(delays[numpy.isnan(delays)]),len(delays[~numpy.isnan(delays)]))
def toImage(arr): if arr.type().bytes == 1: # need to swap coordinates btw array and image (with [::-1]) im = Image.fromstring('L', arr.shape[::-1], arr.tostring()) else: arr_c = arr - arr.min() arr_c *= (255./arr_c.max()) arr = arr_c.astype(UInt8) # need to swap coordinates btw array and image (with [::-1]) im = Image.fromstring('L', arr.shape[::-1], arr.tostring()) return im
def show_legend(self, steps=20, horizontal=True): delta = (self.maxi-self.mini)/(steps-1) vals = self.vals= [] for i in range(steps-1): vals.append(self.mini+i*delta) self.vals.append(self.maxi) values = self.cmap.Map(vals) if horizontal: self.legend = Image.fromstring('RGBA', (steps, 1), (values*255).astype('B').tostring()) else: self.legend = Image.fromstring('RGBA', (1,steps), (values*255).astype('B').tostring()) self.legend.show()
def preview(np, fmt, size, data): def chan(x): return Image.fromstring("L", size, (255 * x).astype(np.uint8)) if fmt == gd2.L1: r = Image.fromstring("1", size, data) elif fmt == gd2.L8: r = Image.fromstring("L", size, data) else: d8 = np.array(data) a = np.ones(size[0] * size[1]) (r, g, b) = (a, a, a) if fmt == gd2.ARGB4: d16 = np.array(array.array('H', data.tostring())) a = (15 & (d16 >> 12)) / 15. r = (15 & (d16 >> 8)) / 15. g = (15 & (d16 >> 4)) / 15. b = (15 & (d16 >> 0)) / 15. elif fmt == gd2.RGB565: d16 = np.array(array.array('H', data.tostring())) r = (31 & (d16 >> 11)) / 31. g = (63 & (d16 >> 5)) / 63. b = (31 & (d16 >> 0)) / 31. elif fmt == gd2.ARGB1555: d16 = np.array(array.array('H', data.tostring())) a = (1 & (d16 >> 15)) r = (31 & (d16 >> 10)) / 31. g = (31 & (d16 >> 5)) / 31. b = (31 & (d16 >> 0)) / 31. elif fmt == gd2.ARGB2: a = (3 & (d8 >> 6)) / 3. r = (3 & (d8 >> 4)) / 3. g = (3 & (d8 >> 2)) / 3. b = (3 & (d8 >> 0)) / 3. elif fmt == gd2.RGB332: r = (7 & (d8 >> 5)) / 7. g = (7 & (d8 >> 2)) / 7. b = (3 & (d8 >> 0)) / 3. elif fmt == gd2.L4: hi = d8 >> 4 lo = d8 & 15 d4 = np.column_stack((hi, lo)).flatten() r = d4 / 15. g = r b = r o = Image.merge("RGB", [chan(c) for c in (r, g, b)]) bg = Image.new("RGB", size, (128, 128, 128)) r = Image.composite(o, bg, chan(a)) r = r.resize((r.size[0] * 5, r.size[1] * 5), Image.NEAREST) return r
def mat2gray(inmat, alpha=True): """ Normalize inmat to 0..255, apply grayscale colormap, use inverse of input as alpha channel (ie white is transparent), return as PIL Image """ mat1 = cv.CreateMat(inmat.rows, inmat.cols, cv.CV_8UC1) cv.Normalize(inmat, mat1, 0, 255, cv.CV_MINMAX) im = Image.fromstring('L', cv.GetSize(mat1), mat1.tostring()) if alpha: cv.Not(mat1, mat1) al = Image.fromstring('L', cv.GetSize(mat1), mat1.tostring()) im.putalpha(al) return im
def test_mapreduce(self): test_in = pickle.load(gzip.open(DATA_FN)) out = self.call_reduce(Reducer, self.shuffle_kv(self.call_map(Mapper, test_in))) try: os.mkdir('output') except OSError: pass for image_id, image in out: image_fn = 'output/%s-%.10d.png' % image_id print(image_fn) image = image.replace('\x01', '\xff') Image.fromstring('L', SZ, image).save(image_fn)
def find_loop(pixels_per_mm_horizontal, show_point=True): #img_array = numpy.fromstring(camera.getChannelObject("image").getValue(), numpy.uint8) rgbImgChan = camera.addChannel({ 'type': 'tango', 'name': 'rgbimage', "read_as_str": 1 }, "RgbImage") raw_data = rgbImgChan.getValue() snapshot_filename = os.path.join(tempfile.gettempdir(), "mxcube_sample_snapshot.png") Image.fromstring("RGB", (imgWidth, imgHeight), raw_data).save(snapshot_filename) info, x, y = lucid.find_loop(snapshot_filename, pixels_per_mm_horizontal=pixels_per_mm_horizontal) self.emitProgressMessage("Loop found: %s (%d, %d)" % (info, x, y)) logging.debug("Loop found: %s (%d, %d)" % (info, x, y)) if show_point: self.emit("newAutomaticCentringPoint", (x,y)) return x,y
def get_last_environment_map(self): if self.last_environment_map is None: faceh = self.cubemap_face_yres facew = self.cubemap_face_xres nchan = self.last_optical_images['posy'].shape[2] imnx = numpy.empty( (faceh*3,facew*4,nchan), dtype = numpy.uint8) if nchan == 4: # make background transparent (alpha channel = 0) initvalue = 0 else: # make background white initvalue = 255 imnx.fill(initvalue) yi0 = faceh yi1 = 2*faceh xi0 = 0 xi1 = facew imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['posy'] xi0 = 2*facew xi1 = 3*facew imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['negy'] xi0 = 3*facew xi1 = 4*facew imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['negx'] xi0 = facew xi1 = 2*facew imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['posx'] yi0 = 0 yi1 = faceh imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['negz'] yi0 = 2*faceh yi1 = 3*faceh imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['posz'] if nchan == 3: im = Image.fromstring('RGB',(imnx.shape[1],imnx.shape[0]),imnx.tostring()) elif nchan == 4: im = Image.fromstring('RGBA',(imnx.shape[1],imnx.shape[0]),imnx.tostring()) im = im.transpose( Image.FLIP_TOP_BOTTOM ) self.last_environment_map = im return self.last_environment_map
def BuildThumbnail(city,colors,waterLevel): """Build the region view images (normal&alpha)""" n = os.path.splitext( city.fileName )[0] minx,miny,maxx,maxy,r = tools3D.generateImage( waterLevel,city.heightMap.shape, city.heightMap.tostring(), colors ) print city.heightMap.shape, len( colors ) print minx,miny,maxx,maxy maxx += 2 offset = len(r)/2 im = Image.fromstring( "RGB", ( 514,428 ), r[:offset]) im = im.crop( [minx,miny,maxx,maxy] ) im.save( n+".PNG" ) im = Image.fromstring( "RGB", ( 514,428 ), r[offset:]) im = im.crop( [minx,miny,maxx,maxy] ) im.save( n+"_alpha.PNG" ) return
def showImageNao(): camProxy = ALProxy('ALVideoDevice', '192.168.2.21', 9559) resolution = 2 colorSpace = 11 videoClient = camProxy.subscribe('python_client', resolution, colorSpace, 5) t0 = time.time() #Get Image naoImage = camProxy.getImageRemote(videoClient) t1 = time.time() #time for transfert diff = t1 - t0 print(('Acquisition delay' + str(diff))) camProxy.unsubscribe(videoClient) #Show imageWidth = naoImage[0] imageHeight = naoImage[1] array = naoImage[6] im = Image.fromstring('RGB', (imageWidth, imageHeight), array) im.show()
def _screenshot(self, path_prefix='.', format='PNG'): """Saves a screenshot of the current frame buffer. The save path is <path_prefix>/.screenshots/shot<num>.png The path is automatically created if it does not exist. Shots are automatically numerated based on how many files are already in the directory.""" if self.counter == self.frameT: self.counter = 1 dir = os.path.join(path_prefix, 'screenshots') if not os.path.exists(dir): os.makedirs(dir) num_present = len(os.listdir(dir)) num_digits = len(str(num_present)) index = '0' * (5 - num_digits) + str(num_present) path = os.path.join(dir, 'shot' + index + '.' + format.lower()) glPixelStorei(GL_PACK_ALIGNMENT, 1) data = glReadPixels(0, 0, self.width, self.height, GL_RGB, GL_UNSIGNED_BYTE) image = Image.fromstring("RGB", (self.width, self.height), data) image = image.transpose(Image.FLIP_TOP_BOTTOM) image.save(path, format) print 'Image saved to %s' % (os.path.basename(path)) else: self.counter += 1 return
def _getBounds(size, glDispID, filename, scale, rotation, partRotation): # Clear the drawing buffer with white glClearColor(1.0, 1.0, 1.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Draw the piece in black glColor3f(0, 0, 0) adjustGLViewport(0, 0, size, size) rotateToView(rotation, scale) rotateView(*partRotation) glCallList(glDispID) # Use PIL to find the image's bounding box (sweet) pixels = glReadPixels(0, 0, size, size, GL_RGB, GL_UNSIGNED_BYTE) img = Image.fromstring("RGB", (size, size), pixels) bg = bgCache.setdefault(size, Image.new("RGB", img.size, (255, 255, 255))) box = ImageChops.difference(img, bg).getbbox() if box is None: return (0, 0, 0, 0, 0, 0) # Rendered entirely out of frame # if filename: # import os # rawFilename = os.path.splitext(os.path.basename(filename))[0] # img.save("C:\\lic\\tmp\\%s_%dx%d.png" % (rawFilename, box[2] - box[0], box[3] - box[1])) # print filename + "box: " + str(box if box else "No box = shit") # Find the bottom left corner inset, used for placing PLIItem quantity labels data = img.load() leftInset = _getLeftInset(data, size, box[1]) bottomInset = _getBottomInset(data, size, box[0]) return box + (leftInset - box[0], bottomInset - box[1])
def loadSurface(self, surface, monochrome = False, alphaChannel = False): """Load the texture from a pygame surface""" # make it a power of two self.pixelSize = w, h = surface.get_size() w2, h2 = [self.nextPowerOfTwo(x) for x in [w, h]] if w != w2 or h != h2: s = pygame.Surface((w2, h2), pygame.SRCALPHA, 32) s.blit(surface, (0, h2 - h)) surface = s if monochrome: # pygame doesn't support monochrome, so the fastest way # appears to be using PIL to do the conversion. string = pygame.image.tostring(surface, "RGB") image = Image.fromstring("RGB", surface.get_size(), string).convert("L") string = image.tostring('raw', 'L', 0, -1) self.loadRaw(surface.get_size(), string, GL_LUMINANCE, GL_INTENSITY8) else: if alphaChannel: string = pygame.image.tostring(surface, "RGBA", True) self.loadRaw(surface.get_size(), string, GL_RGBA, 4) else: string = pygame.image.tostring(surface, "RGB", True) self.loadRaw(surface.get_size(), string, GL_RGB, 3) self.size = (w / w2, h / h2)
def test_r(self): """ Line of circles (varying r) across image each produces a strong response """ im = Image.new("L", (1000, 200), (0)) npoints = 18 xs = [ (100 + 50 * t) for t in range(npoints) ] for t in range(npoints): r = (2.0+0.5*t) circle(im, xs[t], 100, r, 248) # Add noise into the image. If the image does not contain noise, # then the non maximum suppression can - like Buridan's ass - be # presented with two adjacent responses that are equal, and reject # both because neither is a maximum. The chance of this happening # with real-world images is very remote indeed. noise = Image.fromstring("L", (1000,200), "".join([ chr(random.randrange(0, 8)) for i in range(1000 * 200)])) im = ImageChops.add(im, noise) result = sorted([(x,y,s,response) for (x,y,s,response) in simple(im, 7, 1.0, 999999.0, 999999.0)][-npoints:]) # Must have npoints self.assertEqual(len(result), npoints) # X coordinates must be within 1 point of expected for i,(x,y,s,r) in enumerate(result): self.assert_(abs(x - xs[i]) <= 1) # Already ordered by x, so scale should be increasing ss = [s for (x,y,s,r) in result] self.assertEqual(ss, sorted(ss))
def fromstring(string, width, height): """Create a new tile from a `string` of raw pixels, with the given dimensions. fromstring(string, int, int) -> Tile """ return Tile(Image.fromstring('RGB', (width, height), string))
def getThumbnail(self, asDict=False): '''Returns thumbnail as Image or dict.''' # get thumbnail tn_size = int( self.tags['root.ImageList.0.ImageData.Data.Size'] ) tn_offset = int( self.tags['root.ImageList.0.ImageData.Data.Offset'] ) tn_width = int( self.tags['root.ImageList.0.ImageData.Dimensions.0'] ) tn_height = int( self.tags['root.ImageList.0.ImageData.Dimensions.1'] ) if self.debug > 0: print "Notice: tn data in %s starts at %s"%(os.path.split(self.__filename)[1], hex(tn_offset)) print "Notice: tn size: %sx%s px"%(tn_width,tn_height) sizeError = False if (tn_width*tn_height*4) != tn_size: raise Exception, "Cannot extract thumbnail from %s"%os.path.split(self.__filename)[1] else: self.__f.seek( tn_offset ) rawdata = self.__f.read(tn_size) # - read as 16-bit LE unsigned integer tn = Image.fromstring( 'F', (tn_width,tn_height), rawdata, 'raw', 'F;32' ) # - rescale and convert px data tn = tn.point(lambda x: x * (1./65536) + 0) tn = tn.convert('L') if asDict: # - fill tnDict tnDict = {} tnDict['size'] = tn.size tnDict['mode'] = tn.mode tnDict['rawdata'] = tn.tostring() return tnDict else: return tn
def printViewer(self): """Save current buffer to filename in format""" from global_vars import CAIDViewerWildcard # Create a save file dialog dialog = wx.FileDialog ( None, style = wx.SAVE | wx.OVERWRITE_PROMPT , wildcard=CAIDViewerWildcard) # Show the dialog and get user input if dialog.ShowModal() == wx.ID_OK: filename="test.jpeg" try: filename = dialog.GetPath() except: pass ext = filename.split('.')[-1] if ext == "jpeg": fmt="JPEG" if ext == "png": fmt="PNG" import Image # get PIL's functionality... import os x,y,width,height = glGetDoublev(GL_VIEWPORT) width = int(width) height = int(height) glPixelStorei(GL_PACK_ALIGNMENT, 1) data = glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE) image = Image.fromstring( "RGB", (width, height), data ) image = image.transpose( Image.FLIP_TOP_BOTTOM) image.save( filename, fmt ) self.statusbar.SetStatusText("Image has been saved in " + filename) # Destroy the dialog dialog.Destroy()
def toImage(self): """Return the contents of this PixMap as a PIL Image object.""" import Image data = self.tostring()[1:] + chr(0) bounds = self.bounds return Image.fromstring('RGBA', (bounds[2] - bounds[0], bounds[3] - bounds[1]), data)
def array2image(a): """Convert numpy array to image""" if a.dtype.type == numpy.uint16: mode = "I;16" return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring()) else: return Image.fromarray(a)
def ConvertWXToPIL(bmp): """ Convert wx.Image Into PIL Image. """ width = bmp.GetWidth() height = bmp.GetHeight() img = Image.fromstring("RGBA", (width, height), bmp.GetData()) return img
def toImage(self): """Return the contents of this PixMap as a PIL Image object.""" import Image # our tostring() method returns data in ARGB format, # whereas Image uses RGBA; a bit of slicing fixes this... data = self.tostring()[1:] + chr(0) bounds = self.bounds return Image.fromstring('RGBA',(bounds[2]-bounds[0],bounds[3]-bounds[1]),data)
def handle_image(self, msg): rospy.loginfo("Snapper image") if msg.encoding=="mono": image_mode="gray" elif msg.encoding=="rgb": image_mode="RGB"; else: rospy.logerror("Image encoding is not supported %s",msg.encoding); return ma = msg.uint8_data # MultiArray dim = dict([ (d.label,d.size) for d in ma.layout.dim ]) (w,h) = (dim['width'], dim['height']) print dim image = msg.uint8_data.data image_sz = (w,h); if image_mode=="gray": i = Image.fromstring("L", image_sz, image) elif image_mode=="RGB": i = Image.fromstring("RGB", image_sz, image) else: rospy.logerror("Unknown image mode"); return ref_time = "%d.%09d" % (msg.header.stamp.secs, msg.header.stamp.nsecs) fn = "foo-%d.%09d.jpg" % (msg.header.stamp.secs, msg.header.stamp.nsecs) full_fn=os.path.join(self.img_dir,fn); i.save(full_fn) if self.submission_mode=="submit": ext_id = self.mech.submit(full_fn,{'image_size':"%d,%d" % (w,h), 'topic_in':rospy.resolve_name('image'), 'topic_out':rospy.resolve_name('annotation'), 'ref_time':ref_time, 'frame_id':self.frame_id, }) rospy.loginfo("Submitted %s %s"% ( full_fn, ext_id)) print "Submitted %s %s"% ( full_fn, ext_id) else: rospy.loginfo("Submission to session %s@%s blocked by parameter ~submission_mode <> 'submit'", self.target_session,self.server_name) print "Submission blocked to session %s@%s by parameter ~submission_mode <> 'submit'" % (self.target_session,self.server_name) ext_id="n/a"
def arrayToImage(a): """Fcli Converts a gdalnumeric array to a Python Imaging Library Image. """ i = Image.fromstring('L', (a.shape[1], a.shape[0]), (a.astype('b')).tostring()) return i
def capture_image(): image_info = _photos.capture_image() if image_info is None: return None image_data, w, h = image_info import Image img = Image.fromstring('RGBA', (w, h), image_data) return img
def img_img(f0, f1, RT): (ok, f1p, f1i0, f1i) = img_err(f0, f1, RT) c_r = 255 * vop.where(ok, f1i, 0) c_g = 255 * vop.where(ok, f1i0, 0) c_b = 0 * c_g # 255 * vop.where(ok & (abs(f1d0 - f0d) < 1.5), 1.0, 0.0) return Image.merge("RGB", [ Image.fromstring("L", chipsize, c.tostring()) for c in [c_r, c_g, c_b] ])
def array2image(a): if a.typecode() == UnsignedInt8: mode = "L" elif a.typecode() == Float32: mode = "F" else: raise ValueError, "unsupported image mode" return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring())
def rgb24image(self, img_data, width, height, rowstride): assert has_PIL if rowstride > 0: assert len(img_data) == rowstride * height else: assert len(img_data) == width * 3 * height return Image.fromstring("RGB", (width, height), img_data, 'raw', 'RGB', rowstride, 1)
def getImages_pil(self): if not self.images_pil: imageDimensions = self.width, self.height self.images_pil = [ Image.fromstring(modeByType[x[0]], imageDimensions, x[1]) for x in self.packs ] return self.images_pil
def create_bitmapfont(font, basename, chars=None, padleft=0, padright=0, padtop=0, padbottom=0, antialias=True): """Create a bitmap font template font - a pygame Font object or a (name,size) tuple chars - a string of characters that will be rendered (defaults to characters with ascii code 32-128) padleft, padright, padtop, padbottom - add padding to the characters if you intend to add borders/shadows """ if isinstance(font, tuple): fontname, size = font try: f = pygame.font.Font(fontname, size) except IOError: f = pygame.font.SysFont(fontname, size) font = f import Image if chars is None: chars = map(chr, range(32,128)) else: while 1: i = chars.find("..") if i == -1: break c1 = chars[i-1] c2 = chars[i+2] chars = chars[:i-1] + "".join(map(chr, range(ord(c1),ord(c2)))) + chars[i+2:] datfile = basename+".o2f" pngfile = basename+".png" surfs = [] maxheight = 0 width = 0 for c in chars: surf = font.render(c, antialias, (255,255,255,255)) w,h = surf.get_size() maxheight = max(maxheight, h) width += w + padright + padleft surfs.append(surf) height = maxheight + padtop + padbottom surf = pygame.Surface((width,height),pygame.SRCALPHA,32) surf.fill((0,0,0,0)) x = 0 rects = {} for c,s in zip(chars,surfs): w,h = s.get_size() w += padleft + padright h += padtop + padbottom surf.blit(s, (x+padleft,padtop)) rects[c] = (x,0,w,h) x += w dat = pygame.image.tostring(surf,"RGBA") img = Image.fromstring("RGBA", surf.get_size(), dat) img.save(pngfile, optimize=True) dat = BitmapFontData() dat.char_rects = rects dat.linesize = font.get_linesize() + padtop + padbottom dat.padding = (padleft,padright,padtop,padbottom) f = open(datfile, "wb") pickle.dump(dat, f, 2) f.close()
def array2image(array, k, name=''): """ computes t time steps and writes the resulting configurations into an image or video """ if (array.ndim == 1): img = Image.fromstring('P', (1, array.shape[0]), array.tostring()) if (array.ndim == 2): img = Image.fromstring('P', (array.shape[1], array.shape[0]), array.tostring()) else: print "Error: unsupported array size, from a 3D array a 2D video should be created, not yet implemented" if (k == 2): img.putpalette([0, 0, 0, 255, 255, 255]) else: print "Error: images with more than two colors not yet implemented" if (name != ''): img.save(name + ".png", "PNG") return img
def save(self, args): filename = args[0] try: imagestring = pygame.image.tostring(self.surface,"RGB") pilImage = Image.fromstring("RGB", self.surface.get_size(), imagestring) pilImage.save(filename) except NameError: pygame.image.save(self.surface, filename) self.clean = True
def save(self, filename): self.retrieve() if self.spec.type == self.gl_byte: source = string_at(self.buffer, sizeof(self.buffer)) image = Image.fromstring(self.spec.pil, (self.width, self.height), source) image.save(filename) else: raise Exception('cannot save non byte images')
def ImageCaptured(self): self.__imgLock.acquire() _, img = self.__cam.read() cv2.cvtColor(img, cv2.cv.CV_RGB2BGR, img) self.img_cv = img self.__img = Image.fromstring("RGB", (self.CaptureWidth, self.CaptureHeight), img.tostring()) self.__imgLock.release()
def refreshCam(self): try: self.image_data = self.video.read_and_queue() self.image_raw = Image.fromstring("RGB", (self.size_x, self.size_y), self.image_data) self.image = ImageQt.ImageQt(self.image_raw).mirrored(True, False) self.ui.camGoruntu.setPixmap(QtGui.QPixmap.fromImage(self.image)) self.updateCropMask() except: pass
def convertPixbufToImage(pixbuf): assert (pixbuf.get_colorspace() == gtk.gdk.COLORSPACE_RGB) dimensions = pixbuf.get_width(), pixbuf.get_height() stride = pixbuf.get_rowstride() pixels = pixbuf.get_pixels() mode = pixbuf.get_has_alpha() and "RGBA" or "RGB" return Image.frombuffer(mode, dimensions, pixels, "raw", mode, stride, 1) width, height = pixbuf.get_width(), pixbuf.get_height() return Image.fromstring("RGBA", (width, height), pixbuf.get_pixels())
def spr2pngfile(infile_name, outfile_name): infile = open(infile_name, "r") header = infile.read(14) print len(header) (w, h) = struct.unpack("xxxx H H xx xx xx", header) print infile_name, "is a %dx%d image" % (w, h) im = Image.fromstring("RGBA", (w, h), infile.read(4 * w * h), "raw", "RGBA", 4 * w) im.save(outfile_name)
def get_image(self, color=0xFF): if self.pixels is None: self.load_pixels() val_true = chr(color) val_false = chr(0) data = "".join([x and val_true or val_false for x in self.pixels]) return Image.fromstring("L", (self.width, self.height), data, "raw", "L", 16, 1)
def asImage(self): # findBlocks is going to modify the pic in place #if hasattr(self, 'pilImage'): # return self.pilImage self.pilImage = Image.fromstring("RGB", (self.w, self.h), self.string) b, g, r = self.pilImage.split() self.pilImage = Image.merge("RGB", (r, g, b)) return self.pilImage
def main(args): lst = [] spp = [] nl = [] count = [] frame = [] logFile = args[0] lfh = open(logFile, "r") i = 1 j = 1 for line in lfh.readlines(): if line.find('DEBUG') != 0: continue if line.find('ls -t') != -1 and line.find('skipping') == -1: fields = line.split() lst.append(int(fields[6])) count.append(j) j = j + 1 continue if line.find('_parse.pl') != -1: fields = line.split() spp.append(int(fields[5])) continue if line.find('nextlog') != -1: fields = line.split() nl.append(int(fields[5])) frame.append(i) i = i + 1 continue lfh.close() print len(frame) print len(spp) fig = Figure(figsize=(5, 5), dpi=100) ax = fig.add_subplot(111) canvas = FigureCanvasAgg(fig) ax.plot(count, lst) ax.set_xlabel('Frame Number') ax.set_ylabel('nextlog Time') canvas.draw() s = canvas.tostring_rgb() l, b, w, h = fig.bbox.bounds w, h = int(w), int(h) im = Image.fromstring("RGB", (w, h), s) im.show()
def plot_contour_lines(plot_data, xy_data=None, show_regression=False, \ show_equation=False, smooth_steps=0, num_contour_lines=10, \ label_contours=False, line_cmap=cm.hot, fill_cmap=cm.gray,dark=True, graph_shape='rect', prob_axes=False, **kwargs): """helper plots one or more series of contour line data calls the initializing functions, doesn't output figure takes: plot_data, xy_data, show_regression, show_equation, smooth, num_contour_lines, label_contours, line_cmap, fill_cmap, graph_shape, and **kwargs passed on to init_graph_display. plot_data = (x_bin, y_bin, data_matrix dot_colors) """ if prob_axes: extent = (0, 1, 0, 1) else: a = gca() extent = a.get_xlim() + a.get_ylim() #init graph display, rectangular due to needed colorbar space init_graph_display(graph_shape=graph_shape, dark=dark, **kwargs) #plots the contour data for x_bin, y_bin, data in plot_data: orig_max = max(ravel(data)) scaled_data = (data / orig_max * 255).astype('b') if smooth_steps and (Image is not None): orig_shape = data.shape im = Image.fromstring('L', data.shape, scaled_data) for i in range(smooth_steps): im = im.filter(ImageFilter.BLUR) new_data = fromstring(im.tostring(), 'b') data = reshape(new_data.astype('i') / 255.0 * orig_max, orig_shape) if fill_cmap is not None: im = imshow(data, interpolation='bicubic', extent=extent, \ origin='lower', cmap=fill_cmap) result = contour(x_bin, y_bin, data, num_contour_lines, origin='lower', linewidth=2, extent=extent, cmap=line_cmap) if label_contours: clabel(result, fmt='%1.1g') #add the colorbar legend to the side cb = colorbar() cb.ax.axisbg = 'black' if show_regression: equation = plot_regression_line(xy_data[0], xy_data[1], prob_axes=prob_axes) if show_equation: add_regression_equations([equation])
def saveTo(self, filename, format="JPEG"): import Image # get PIL's functionality... @UnresolvedImport width, height = 800, 600 glPixelStorei(GL_PACK_ALIGNMENT, 1) data = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE) image = Image.fromstring("RGB", (width, height), data) image = image.transpose(Image.FLIP_TOP_BOTTOM) image.save(filename, format) print('Saved image to ', filename) return image
def collect_screenshot(dest, ser): import Image t0 = time.time() match = "!screenshot" have = "X" * len(match) while have != match: have = (have + ser.read(1))[-len(match):] (w, h) = struct.unpack("II", ser.read(8)) print '%dx%d image' % (w, h), sys.stdout.flush() if 0: imd = ser.read(4 * w * h) im = Image.fromstring("RGBA", (w, h), imd) else: # print [ord(c) for c in ser.read(20)] def getn(): b = ord(ser.read(1)) n = b while b == 255: b = ord(ser.read(1)) n += b # print ' length', n return n imd = "" for y in range(h): # print 'line', y prev = 4 * chr(0) d = "" while len(d) < 4 * w: # print ' have', len(d) / 4 d += prev * getn() d += ser.read(4 * getn()) prev = d[-4:] assert len(d) == 4 * w, 'corrupted screen dump stream' imd += d im = Image.fromstring("RGBA", (w, h), imd) (b,g,r,a) = im.split() im = Image.merge("RGBA", (r, g, b, a)) im.convert("RGB").save(dest) took = time.time() - t0 print 'took %.1fs. Wrote RGB image to %s' % (took, dest) ser.write('k')
def dump_to_file(self, fullfilename): import Image width, height = self.GetSize() pstring = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE) snapshot = Image.fromstring("RGBA", (width, height), pstring).transpose(Image.FLIP_TOP_BOTTOM) from Utilities import assureCorrectFileEnding fullfilename = assureCorrectFileEnding(fullfilename, 'png') snapshot.save(fullfilename) return
def array2image(a): import numpy as np import Image if a.dtype == np.uint8: mode = "L" elif a.dtype == np.float32: mode = "F" else: raise ValueError, "unsupported image mode" return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring())
def fig2img(fig): """ @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it @param fig a matplotlib figure @return a Python Imaging Library ( PIL ) image """ # put the figure pixmap into a numpy array buf = fig2data(fig) w, h, d = buf.shape return Image.fromstring("RGBA", (w, h), buf.tostring())
def grab(bbox=None): size, data = grabber() im = Image.fromstring( "RGB", size, data, # RGB, 32-bit line padding, origo in lower left corner "raw", "BGR", (size[0]*3 + 3) & -4, -1 ) if bbox: im = im.crop(bbox) return im
def collect(self, frame): frame.descriptors = [] im = Image.fromstring("L", frame.size, frame.rawdata) frame.matcher = calonder.BruteForceMatcher() for (x, y, d) in frame.kp: patch = im.crop((x - 16, y - 16, x + 16, y + 16)) sig = self.cl.getSparseSignature(patch.tostring(), patch.size[0], patch.size[1]) frame.descriptors.append(sig) frame.matcher.addSignature(sig)