Python PIL.Image.frombuffer() Examples
The following are 30
code examples of PIL.Image.frombuffer().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
PIL.Image
, or try the search function
.
Example #1
Source File: polapizero_09.py From polapi-zero with MIT License | 6 votes |
def displayImage(image): global grey_palette l_height = SCREEN_HEIGHT l_width = SCREEN_WIDTH pgImage = pygame.image.frombuffer(image.tobytes(), image.size, 'P' ) pgImage.set_palette(grey_palette) i_width = pgImage.get_width() i_height = pgImage.get_height() pgImage = pygame.transform.scale( pgImage, (int(i_width*(1.0*l_height/i_height)), l_height) ) screen.fill(backgroundColor) screen.blit(pgImage, ((l_width - pgImage.get_width())/2, (l_height-pgImage.get_height())/2)) pygame.display.flip()
Example #2
Source File: EditMeta.py From DrapsTV_Materials with MIT License | 6 votes |
def writeMetaData(imgname, tag, replace): try: metaData = {} imgFile = Image.open(imgname) imgData = imgFile.getdata() print "Getting meta data..." info = imgFile._getexif() if info: print "found meta data!" i = 0 for (tag, value) in info.items(): i = i + 1 tagname = TAGS.get(tag, tag) #if tagname == tagToReplace: #info.items()[i][1] = replace print "Saving Change" outImg = Image.frombuffer("RGBX",len(imgData)+len(info),imgData+info) outImg.save(img) except: print "Failed"
Example #3
Source File: testWrite.py From DrapsTV_Materials with MIT License | 6 votes |
def writeMetaData(imgname, tag, replace): try: metaData = {} imgFile = Image.open(imgname) imgData = imgFile.getdata() print "Getting meta data..." info = imgFile._getexif() if info: print "found meta data!" i = 0 for (tag, value) in info.items(): i = i + 1 tagname = TAGS.get(tag, tag) #if tagname == tagToReplace: #info.items()[i][1] = replace print "Saving Change" outImg = Image.frombuffer("RGBX",len(imgData)+len(info),imgData+info) outImg.save(img) except: print "Failed"
Example #4
Source File: webcamsnap.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def pil_save(filename, pixels, width, height): from PIL import Image, ImageFile buffer_len = (width * 3 + 3) & -4 img = Image.frombuffer('RGB', (width, height), pixels, 'raw', 'BGR', buffer_len, 1) ImageFile.MAXBLOCK = width * height img=img.transpose(Image.FLIP_TOP_BOTTOM) img.save(filename, quality=95, optimize=True, progressive=True) logging.info('webcam snap saved to %s'%filename)
Example #5
Source File: backend_agg.py From twitter-stock-recommendation with MIT License | 5 votes |
def print_tif(self, filename_or_obj, *args, **kwargs): buf, size = self.print_to_buffer() if kwargs.pop("dryrun", False): return image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) dpi = (self.figure.dpi, self.figure.dpi) return image.save(filename_or_obj, format='tiff', dpi=dpi)
Example #6
Source File: backend_agg.py From twitter-stock-recommendation with MIT License | 5 votes |
def print_jpg(self, filename_or_obj, *args, **kwargs): """ Other Parameters ---------------- quality : int The image quality, on a scale from 1 (worst) to 95 (best). The default is 95, if not given in the matplotlibrc file in the savefig.jpeg_quality parameter. Values above 95 should be avoided; 100 completely disables the JPEG quantization stage. optimize : bool If present, indicates that the encoder should make an extra pass over the image in order to select optimal encoder settings. progressive : bool If present, indicates that this image should be stored as a progressive JPEG file. """ buf, size = self.print_to_buffer() if kwargs.pop("dryrun", False): return # The image is "pasted" onto a white background image to safely # handle any transparency image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) rgba = mcolors.to_rgba(rcParams['savefig.facecolor']) color = tuple([int(x * 255.0) for x in rgba[:3]]) background = Image.new('RGB', size, color) background.paste(image, image) options = {k: kwargs[k] for k in ['quality', 'optimize', 'progressive', 'dpi'] if k in kwargs} options.setdefault('quality', rcParams['savefig.jpeg_quality']) if 'dpi' in options: # Set the same dpi in both x and y directions options['dpi'] = (options['dpi'], options['dpi']) return background.save(filename_or_obj, format='jpeg', **options)
Example #7
Source File: screenshot.py From self-driving-truck with MIT License | 5 votes |
def make_screenshot(x1, y1, x2, y2): #w, h = x1+x2, y1+y2 w = x2 - x1 h = y2 - y1 size = w * h objlength = size * 3 SCREENSHOT_LIB.getScreen.argtypes = [] result = (ctypes.c_ubyte * objlength)() SCREENSHOT_LIB.getScreen(x1, y1, w, h, result) #return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1) img_flat = np.frombuffer(result, dtype=np.uint8) return img_flat.reshape((h, w, 3))
Example #8
Source File: screenshot.py From backdoorme with MIT License | 5 votes |
def pil_save(filename, pixels, width, height): from PIL import Image, ImageFile buffer_len = (width * 3 + 3) & -4 img = Image.frombuffer('RGB', (width, height), pixels, 'raw', 'BGR', buffer_len, 1) ImageFile.MAXBLOCK = width * height img=img.transpose(Image.FLIP_TOP_BOTTOM) img.save(filename, quality=95, optimize=True, progressive=True) logging.info('Screenshot saved to %s'%filename)
Example #9
Source File: mouselogger.py From backdoorme with MIT License | 5 votes |
def pil_save(filename, pixels, width, height): from PIL import Image, ImageFile buffer_len = (width * 3 + 3) & -4 img = Image.frombuffer('RGB', (width, height), pixels, 'raw', 'BGR', buffer_len, 1) ImageFile.MAXBLOCK = width * height img=img.transpose(Image.FLIP_TOP_BOTTOM) img.save(filename, quality=95, optimize=True, progressive=True)
Example #10
Source File: webcamsnap.py From backdoorme with MIT License | 5 votes |
def pil_save(filename, pixels, width, height): from PIL import Image, ImageFile buffer_len = (width * 3 + 3) & -4 img = Image.frombuffer('RGB', (width, height), pixels, 'raw', 'BGR', buffer_len, 1) ImageFile.MAXBLOCK = width * height img=img.transpose(Image.FLIP_TOP_BOTTOM) img.save(filename, quality=95, optimize=True, progressive=True) logging.info('webcam snap saved to %s'%filename)
Example #11
Source File: IcnsImagePlugin.py From lambda-text-extractor with Apache License 2.0 | 5 votes |
def read_mk(fobj, start_length, size): # Alpha masks seem to be uncompressed start = start_length[0] fobj.seek(start) pixel_size = (size[0] * size[2], size[1] * size[2]) sizesq = pixel_size[0] * pixel_size[1] band = Image.frombuffer( "L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1 ) return {"A": band}
Example #12
Source File: image.py From CogAlg with MIT License | 5 votes |
def pil_to_array(pilImage): """Load a `PIL image`_ and return it as a numpy array. .. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html Returns ------- numpy.array The array shape depends on the image type: - (M, N) for grayscale images. - (M, N, 3) for RGB images. - (M, N, 4) for RGBA images. """ if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']: # return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array return np.asarray(pilImage) elif pilImage.mode.startswith('I;16'): # return MxN luminance array of uint16 raw = pilImage.tobytes('raw', pilImage.mode) if pilImage.mode.endswith('B'): x = np.frombuffer(raw, '>u2') else: x = np.frombuffer(raw, '<u2') return x.reshape(pilImage.size[::-1]).astype('=u2') else: # try to convert to an rgba image try: pilImage = pilImage.convert('RGBA') except ValueError: raise RuntimeError('Unknown image mode') return np.asarray(pilImage) # return MxNx4 RGBA array
Example #13
Source File: windows.py From ATX with Apache License 2.0 | 5 votes |
def screen(self): """PIL Image of current window screen. reference: https://msdn.microsoft.com/en-us/library/dd183402(v=vs.85).aspx""" hwnd = win32gui.GetDesktopWindow() left, top, right, bottom = self.rect width, height = right-left, bottom-top # copy bits to temporary dc win32gui.BitBlt(self._hdcmem, 0, 0, width, height, self._hdcwin, left, top, win32con.SRCCOPY) # read bits into buffer windll.gdi32.GetDIBits(self._hdcmem, self._hbmp.handle, 0, height, self._buf, ctypes.byref(self._bi), win32con.DIB_RGB_COLORS) # make a PIL Image img = Image.frombuffer('RGB', (width, height), self._buf, 'raw', 'BGRX', 0, 1) img = img.transpose(Image.FLIP_TOP_BOTTOM) return img
Example #14
Source File: IcnsImagePlugin.py From FODI with GNU General Public License v3.0 | 5 votes |
def read_mk(fobj, start_length, size): # Alpha masks seem to be uncompressed start = start_length[0] fobj.seek(start) pixel_size = (size[0] * size[2], size[1] * size[2]) sizesq = pixel_size[0] * pixel_size[1] band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1) return {"A": band}
Example #15
Source File: backend_agg.py From coffeegrindsize with MIT License | 5 votes |
def print_tif(self, filename_or_obj, *args, dryrun=False, **kwargs): buf, size = self.print_to_buffer() if dryrun: return image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) dpi = (self.figure.dpi, self.figure.dpi) return image.save(filename_or_obj, format='tiff', dpi=dpi)
Example #16
Source File: extract_edof.py From dual-camera-edof with GNU General Public License v2.0 | 5 votes |
def extract_edof(data, idx, fname): if data[idx + 4:idx + 8] != b'edof': print("ERROR: Frame is not EDOF") return False idx += 8 columns = int.from_bytes(data[idx + 16: idx + 18], byteorder='little') rows = int.from_bytes(data[idx + 18: idx + 20], byteorder='little') print("\t* found EDOF at %d with geometry=%dx%d" % (idx, columns, rows)) orientation = data[idx + 7] idx += 68 img = Image.frombuffer('L', (columns, rows), data[idx:], 'raw', 'L', 0, 0) if orientation == 0x10: img = img.transpose(Image.FLIP_TOP_BOTTOM) elif orientation == 0x12: img = img.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 0x13: img = img.transpose(Image.TRANSPOSE) if show_edof: img.show() if save_edof: outfname = (''.join(fname.split('.')[:-1])) + '-EDOF.png' print("\t * saving to %s" % outfname) img.save(outfname) return True
Example #17
Source File: backend_agg.py From CogAlg with MIT License | 5 votes |
def stop_filter(self, post_processing): """ Save the plot in the current canvas as a image and apply the *post_processing* function. def post_processing(image, dpi): # ny, nx, depth = image.shape # image (numpy array) has RGBA channels and has a depth of 4. ... # create a new_image (numpy array of 4 channels, size can be # different). The resulting image may have offsets from # lower-left corner of the original image return new_image, offset_x, offset_y The saved renderer is restored and the returned image from post_processing is plotted (using draw_image) on it. """ width, height = int(self.width), int(self.height) buffer, (l, b, w, h) = self.tostring_rgba_minimized() self._renderer = self._filter_renderers.pop() self._update_methods() if w > 0 and h > 0: img = np.frombuffer(buffer, np.uint8) img, ox, oy = post_processing(img.reshape((h, w, 4)) / 255., self.dpi) gc = self.new_gc() if img.dtype.kind == 'f': img = np.asarray(img * 255., np.uint8) img = img[::-1] self._renderer.draw_image(gc, l + ox, height - b - h + oy, img)
Example #18
Source File: IcnsImagePlugin.py From lambda-text-extractor with Apache License 2.0 | 5 votes |
def read_mk(fobj, start_length, size): # Alpha masks seem to be uncompressed start = start_length[0] fobj.seek(start) pixel_size = (size[0] * size[2], size[1] * size[2]) sizesq = pixel_size[0] * pixel_size[1] band = Image.frombuffer( "L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1 ) return {"A": band}
Example #19
Source File: IcnsImagePlugin.py From FODI with GNU General Public License v3.0 | 5 votes |
def read_32(fobj, start_length, size): """ Read a 32bit RGB icon resource. Seems to be either uncompressed or an RLE packbits-like scheme. """ (start, length) = start_length fobj.seek(start) pixel_size = (size[0] * size[2], size[1] * size[2]) sizesq = pixel_size[0] * pixel_size[1] if length == sizesq * 3: # uncompressed ("RGBRGBGB") indata = fobj.read(length) im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1) else: # decode image im = Image.new("RGB", pixel_size, None) for band_ix in range(3): data = [] bytesleft = sizesq while bytesleft > 0: byte = fobj.read(1) if not byte: break byte = i8(byte) if byte & 0x80: blocksize = byte - 125 byte = fobj.read(1) for i in range(blocksize): data.append(byte) else: blocksize = byte + 1 data.append(fobj.read(blocksize)) bytesleft -= blocksize if bytesleft <= 0: break if bytesleft != 0: raise SyntaxError("Error reading channel [%r left]" % bytesleft) band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1) im.im.putband(band.im, band_ix) return {"RGB": im}
Example #20
Source File: QuoteWriter.py From variety with GNU General Public License v3.0 | 5 votes |
def save_cairo_surface(surface, filename): try: # attempt faster method first # the get_data() call will fail with Cairo version < 1.15.4-1 (e.g. on 16.04) # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=809479 data = surface.get_data() size = surface.get_width(), surface.get_height() image = Image.frombuffer("RGBA", size, data.tobytes(), "raw", "BGRA", 0, 1).convert( "RGB" ) image.save(filename, quality=100) except: # fallback to slower method, but which works on 16.04 surface.write_to_png(filename)
Example #21
Source File: backend_agg.py From ImageFusion with MIT License | 5 votes |
def print_tif(self, filename_or_obj, *args, **kwargs): buf, size = self.print_to_buffer() if kwargs.pop("dryrun", False): return image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) dpi = (self.figure.dpi, self.figure.dpi) return image.save(filename_or_obj, format='tiff', dpi=dpi)
Example #22
Source File: backend_agg.py From ImageFusion with MIT License | 5 votes |
def print_jpg(self, filename_or_obj, *args, **kwargs): """ Supported kwargs: *quality*: The image quality, on a scale from 1 (worst) to 95 (best). The default is 95, if not given in the matplotlibrc file in the savefig.jpeg_quality parameter. Values above 95 should be avoided; 100 completely disables the JPEG quantization stage. *optimize*: If present, indicates that the encoder should make an extra pass over the image in order to select optimal encoder settings. *progressive*: If present, indicates that this image should be stored as a progressive JPEG file. """ buf, size = self.print_to_buffer() if kwargs.pop("dryrun", False): return image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) options = restrict_dict(kwargs, ['quality', 'optimize', 'progressive']) if 'quality' not in options: options['quality'] = rcParams['savefig.jpeg_quality'] return image.save(filename_or_obj, format='jpeg', **options)
Example #23
Source File: generalelements.py From Snu-Photo-Manager with GNU Lesser General Public License v3.0 | 5 votes |
def get_converted_frame(self): if self.first_frame: frame = self.first_frame self.first_frame = None else: self.player.set_pause(False) frame = None while not frame: frame, value = self.player.get_frame(force_refresh=False) if value == 'eof': return None self.player.set_pause(True) self.frame_number = self.frame_number + 1 if self.max_frames: if self.frame_number > self.max_frames: return None frame_image = frame[0] frame_size = frame_image.get_size() frame_converter = SWScale(frame_size[0], frame_size[1], frame_image.get_pixel_format(), ofmt='rgb24') new_frame = frame_converter.scale(frame_image) image_data = bytes(new_frame.to_bytearray()[0]) image = Image.frombuffer(mode='RGB', size=(frame_size[0], frame_size[1]), data=image_data, decoder_name='raw') #for some reason, video frames are read upside-down? fix it here... image = image.transpose(PIL.Image.FLIP_TOP_BOTTOM) if image.mode != 'RGB': image = image.convert('RGB') image = self.adjust_image(image, preview=False) return [image, frame[1]]
Example #24
Source File: linegen.py From kraken with Apache License 2.0 | 5 votes |
def render_line(self, text): """ Draws a line onto a Cairo surface which will be converted to an pillow Image. Args: text (unicode): A string which will be rendered as a single line. Returns: PIL.Image of mode 'L'. Raises: KrakenCairoSurfaceException if the Cairo surface couldn't be created (usually caused by invalid dimensions. """ logger.info('Rendering line \'{}\''.format(text)) logger.debug('Creating temporary cairo surface') temp_surface = cairo.cairo_image_surface_create(0, 0, 0) width, height = _draw_on_surface(temp_surface, self.font, self.language, text) cairo.cairo_surface_destroy(temp_surface) if width == 0 or height == 0: logger.error('Surface for \'{}\' zero pixels in at least one dimension'.format(text)) raise KrakenCairoSurfaceException('Surface zero pixels in at least one dimension', width, height) logger.debug('Creating sized cairo surface') real_surface = cairo.cairo_image_surface_create(0, width, height) _draw_on_surface(real_surface, self.font, self.language, text) logger.debug('Extracing data from real surface') data = cairo.cairo_image_surface_get_data(real_surface) size = int(4 * width * height) buffer = ctypes.create_string_buffer(size) ctypes.memmove(buffer, data, size) logger.debug('Loading data into PIL image') im = Image.frombuffer("RGBA", (width, height), buffer, "raw", "BGRA", 0, 1) cairo.cairo_surface_destroy(real_surface) logger.debug('Expand and grayscale image') im = im.convert('L') im = ImageOps.expand(im, 5, 255) return im
Example #25
Source File: qrcode.py From platypush with MIT License | 5 votes |
def _convert_frame(self, frame): import numpy as np assert isinstance(frame, np.ndarray), \ 'Image conversion only works with numpy arrays for now (got {})'.format(type(frame)) mode = 'RGB' if len(frame.shape) > 2 and frame.shape[2] == 4: mode = 'RGBA' return Image.frombuffer(mode, (frame.shape[1], frame.shape[0]), frame, 'raw', mode, 0, 1)
Example #26
Source File: mouselogger.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def pil_save(filename, pixels, width, height): from PIL import Image, ImageFile buffer_len = (width * 3 + 3) & -4 img = Image.frombuffer('RGB', (width, height), pixels, 'raw', 'BGR', buffer_len, 1) ImageFile.MAXBLOCK = width * height img=img.transpose(Image.FLIP_TOP_BOTTOM) img.save(filename, quality=95, optimize=True, progressive=True)
Example #27
Source File: screenshot.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def pil_save(filename, pixels, width, height): from PIL import Image, ImageFile buffer_len = (width * 3 + 3) & -4 img = Image.frombuffer('RGB', (width, height), pixels, 'raw', 'BGR', buffer_len, 1) ImageFile.MAXBLOCK = width * height img=img.transpose(Image.FLIP_TOP_BOTTOM) img.save(filename, quality=95, optimize=True, progressive=True) logging.info('Screenshot saved to %s'%filename)
Example #28
Source File: mouselogger.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def pil_save(filename, pixels, width, height): from PIL import Image, ImageFile buffer_len = (width * 3 + 3) & -4 img = Image.frombuffer('RGB', (width, height), pixels, 'raw', 'BGR', buffer_len, 1) ImageFile.MAXBLOCK = width * height img=img.transpose(Image.FLIP_TOP_BOTTOM) img.save(filename, quality=95, optimize=True, progressive=True)
Example #29
Source File: webcamsnap.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def pil_save(filename, pixels, width, height): from PIL import Image, ImageFile buffer_len = (width * 3 + 3) & -4 img = Image.frombuffer('RGB', (width, height), pixels, 'raw', 'BGR', buffer_len, 1) ImageFile.MAXBLOCK = width * height img=img.transpose(Image.FLIP_TOP_BOTTOM) img.save(filename, quality=95, optimize=True, progressive=True) logging.info('webcam snap saved to %s'%filename)
Example #30
Source File: backend_agg.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def print_tif(self, filename_or_obj, *args, dryrun=False, **kwargs): buf, size = self.print_to_buffer() if dryrun: return image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) dpi = (self.figure.dpi, self.figure.dpi) return image.save(filename_or_obj, format='tiff', dpi=dpi)