我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PIL.Image.FLIP_TOP_BOTTOM。
def create(format='png'): """ Create a screenshot :param format: formats supported by PIL (png, jpeg etc) """ dest = "" if not settings.SCREENSHOT_PATH: print("SCREENSHOT_PATH not defined in settings. Using cwd as fallback.") if settings.SCREENSHOT_PATH: if os.path.exists(settings.SCREENSHOT_PATH): dest = settings.SCREENSHOT_PATH else: print("SCREENSHOT_PATH {} does not exist. Using cwd as fallback".format(settings.SCREENSHOT_PATH)) x, y, width, height = GL.glGetIntegerv(GL.GL_VIEWPORT) print("Screenshot viewport:", x, y, width, height) GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1) data = GL.glReadPixels(x, y, width, height, GL.GL_RGB, GL.GL_UNSIGNED_BYTE) image = Image.frombytes("RGB", (width, height), data) image = image.transpose(Image.FLIP_TOP_BOTTOM) name = "{}.{}".format(datetime.now().strftime("%Y-%m-%d-%H-%M-%S"), format) image.save(os.path.join(dest, name), format=format)
def font_variant(self, font=None, size=None, index=None, encoding=None): """ Create a copy of this FreeTypeFont object, using any specified arguments to override the settings. Parameters are identical to the parameters used to initialize this object. :return: A FreeTypeFont object. """ return FreeTypeFont(font=self.path if font is None else font, size=self.size if size is None else size, index=self.index if index is None else index, encoding=self.encoding if encoding is None else encoding) ## # Wrapper that creates a transposed font from any existing font # object. # # @param font A font object. # @param orientation An optional orientation. If given, this should # be one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM, # Image.ROTATE_90, Image.ROTATE_180, or Image.ROTATE_270.
def initializeGL(self): self.ctx = ModernGL.create_context() self.dragon_obj = Obj.open(res('dragon.obj')) self.dragon_img = Image.open(res('dragon_texture_color.png')) self.dragon_img = self.dragon_img.convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) self.prog = self.ctx.program([ self.ctx.vertex_shader(open(res('vertex_shader.glsl')).read()), self.ctx.fragment_shader(open(res('fragment_shader.glsl')).read()), ]) self.mvp = self.prog.uniforms['Mvp'] self.light = self.prog.uniforms['Light'] self.vbo = self.ctx.buffer(self.dragon_obj.pack('vx vz vy nx nz ny tx ty')) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, ['in_vert', 'in_norm', 'in_text']) self.tex = self.ctx.texture(self.dragon_img.size, 3, self.dragon_img.tobytes()) self.tex.use() self.h, self.v, self.r = 0.5, 0.5, 10
def __init__(self, width=800, height=600): # Create a window self.win = window.Window(width, height, "App") # Load mesh mesh = pyassimp.load("data/african_head/african_head.obj") self.indices = mesh.meshes[0].faces self.vertices = mesh.meshes[0].vertices self.normals = mesh.meshes[0].normals self.uvs = mesh.meshes[0].texturecoords[0, :, 1::-1] # Load texture image = Image.open("data/african_head/african_head_diffuse.tga") image = image.transpose(Image.FLIP_TOP_BOTTOM) self.texture = np.array(image, dtype=np.float32) # Create renderer self.rend = renderer.Renderer(width, height) self.rend.init() self.clear = self.rend.clear_fn() self.draw = self.rend.draw_fn(shaders.TexturedLitShader()) self.start_time = self.last_time = time.time() self.win.loop(self)
def _execute_saving(self): if self.flag < 3: self.flag += 1 return size_x, size_y = self._plot._window.get_size() size = size_x*size_y*4*sizeof(c_ubyte) image = create_string_buffer(size) glReadPixels(0, 0, size_x, size_y, GL_RGBA, GL_UNSIGNED_BYTE, image) from PIL import Image im = Image.frombuffer('RGBA', (size_x, size_y), image.raw, 'raw', 'RGBA', 0, 1) im.transpose(Image.FLIP_TOP_BOTTOM).save(self.outfile, self.format) self.flag = 0 self.screenshot_requested = False if self.invisibleMode: self._plot._window.close()
def __init__(self, path): #load an image img = Image.open(path).transpose(Image.FLIP_TOP_BOTTOM) width, height = img.size imgData = numpy.array(img.convert("RGBA"), numpy.uint8) #load texture into buffer self.texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.texture) #texture wrapping params glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, (0.0, 0.0, 0.0, 0.0)); #texture filtering params, for scaling up or down glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imgData) #will be used to bind the texture to opengl so that it uses it. Opengl can bind many textures at once.
def image_transpose_exif(im): exif_orientation_tag = 0x0112 # contains an integer, 1 through 8 exif_transpose_sequences = [ # corresponding to the following [], [Image.FLIP_LEFT_RIGHT], [Image.ROTATE_180], [Image.FLIP_TOP_BOTTOM], [Image.FLIP_LEFT_RIGHT, Image.ROTATE_90], [Image.ROTATE_270], [Image.FLIP_TOP_BOTTOM, Image.ROTATE_90], [Image.ROTATE_90], ] try: if im._getexif() is not None: seq = exif_transpose_sequences[im._getexif()[exif_orientation_tag] - 1] return functools.reduce(lambda im, op: im.transpose(op), seq, im) else: return im except KeyError: return im
def load_image(fd): d = Asset(fd) tex = [i for i in d.objs if "image data" in i] assert len(tex) == 1 tex = tex[0] data = tex["image data"] width, height, fmt = tex["m_Width"], tex["m_Height"], tex["m_TextureFormat"] if fmt == 7: # BGR565 im = Image.frombytes("RGB", (width, height), data, "raw", "BGR;16") elif fmt == 13: # ABGR4444 im = Image.frombytes("RGBA", (width, height), data, "raw", "RGBA;4B") r, g, b, a = im.split() im = Image.merge("RGBA", (a, b, g, r)) else: raise Exception("Unsupported format %d" % fmt) im = im.transpose(Image.FLIP_TOP_BOTTOM) return im
def flip(image): """ Flip the image vertically (top to bottom). :param image: The image to flip. :return: An image. """ return image.transpose(Image.FLIP_TOP_BOTTOM)
def __getitem__(self, index): Cpath, Spath = self.imgs[index][0], self.imgs[index][1] Cimg, Simg = color_loader(Cpath), grey_loader(Spath) Cimg, Simg = RandomCrop(511)(Cimg, Simg) if random.random() < 0.5: Cimg, Simg = Cimg.transpose(Image.FLIP_LEFT_RIGHT), Simg.transpose(Image.FLIP_LEFT_RIGHT) if random.random() < 0.5: Cimg, Simg = Cimg.transpose(Image.FLIP_TOP_BOTTOM), Simg.transpose(Image.FLIP_TOP_BOTTOM) if random.random() < 0.5: Cimg, Simg = Cimg.transpose(Image.ROTATE_90), Simg.transpose(Image.ROTATE_90) Cimg, Vimg, Simg = self.transform(Cimg), self.vtransform(Cimg), self.stransform(Simg) return Cimg, Vimg, Simg
def __getitem__(self, index): Cpath, Spath = self.imgs[index] Cimg, Simg = color_loader(Cpath), sketch_loader(Spath) Cimg, Simg = RandomCrop(511)(Cimg, Simg) if random.random() < 0.5: Cimg, Simg = Cimg.transpose(Image.FLIP_LEFT_RIGHT), Simg.transpose(Image.FLIP_LEFT_RIGHT) if random.random() < 0.5: Cimg, Simg = Cimg.transpose(Image.FLIP_TOP_BOTTOM), Simg.transpose(Image.FLIP_TOP_BOTTOM) # if random.random() < 0.5: # Vimg = Vimg.transpose(Image.ROTATE_90) Cimg, Vimg, Simg = self.transform(Cimg), self.vtransform(Cimg), self.stransform(Simg) return Cimg, Vimg, Simg
def __getitem__(self, index): Cpath, Spath = self.imgs[index][0], self.imgs[index][random.randint(1, 3)] Cimg, Simg = color_loader(Cpath), sketch_loader(Spath) Cimg, Simg = RandomCrop(511)(Cimg, Simg) if random.random() < 0.5: Cimg, Simg = Cimg.transpose(Image.FLIP_LEFT_RIGHT), Simg.transpose(Image.FLIP_LEFT_RIGHT) if random.random() < 0.5: Cimg, Simg = Cimg.transpose(Image.FLIP_TOP_BOTTOM), Simg.transpose(Image.FLIP_TOP_BOTTOM) if random.random() < 0.5: Cimg, Simg = Cimg.transpose(Image.ROTATE_90), Simg.transpose(Image.ROTATE_90) Cimg, Vimg, Simg = self.transform(Cimg), self.vtransform(Cimg), self.stransform(Simg) return Cimg, Vimg, Simg
def __init__(self, *commands, prefixes=None, strict=False): """Answers with image containing stylish quote.""" super().__init__(*commands, prefixes=prefixes, strict=strict) self.q = Image.open(self.get_path("q.png")).resize((40, 40), Image.LANCZOS) self.qf = self.q.copy().transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.FLIP_TOP_BOTTOM) self.f = ImageFont.truetype(self.get_path("font.ttf"), 20) self.fs = ImageFont.truetype(self.get_path("font.ttf"), 14) example = self.command_example() self.description = [f"????????? ?????", f"{example} [?????] - ????????? ????????? ? ??????? ????? (?? ???????) ? " "???????? ??????!"]
def __call__(self, img): if random.random() < 0.5: return img.transpose(Image.FLIP_TOP_BOTTOM) return img
def __init__(self, font, orientation=None): """ Wrapper that creates a transposed font from any existing font object. :param font: A font object. :param orientation: An optional orientation. If given, this should be one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM, Image.ROTATE_90, Image.ROTATE_180, or Image.ROTATE_270. """ self.font = font self.orientation = orientation # any 'transpose' argument, or None
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)
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)
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)
def flip_image(input_file, input_box): prefix = os.path.splitext(input_file)[0] x1 = input_box[0]["x1"] y1 = input_box[0]["y1"] x2 = input_box[0]["x2"] y2 = input_box[0]["y2"] im = Image.open(input_file) im1 = im.transpose(Image.FLIP_LEFT_RIGHT) im2 = im.transpose(Image.FLIP_TOP_BOTTOM) output_file = [ prefix + "_flip_1.bmp", prefix + "_flip_2.bmp"] output_box = [ { "x1": SIZE - 1 - x1, "x2": SIZE - 1 - x2, "y1": y1, "y2": y2, }, { "x1": x1, "x2": x2, "y1": SIZE - 1 - y1, "y2": SIZE - 1 - y2, }, ] im1.save(output_file[0]) im2.save(output_file[1]) # draw_box(im1, output_box[0]).save(output_file[0]) # draw_box(im2, output_box[1]).save(output_file[1]) return output_file, output_box
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
def flip(message: discord.Message, image_arg: image, extension: str.lower=None): """ Flip an image in the y-axis. """ if extension: image_arg.set_extension(extension) # Flip the image image_arg.modify(Image.Image.transpose, Image.FLIP_TOP_BOTTOM) try: await send_image(message, image_arg) except IOError: await client.say(message, "**The image format is not supported (must be L or RGB)**")
def flip_horizontal(img): """ Flip image over the horizontal axis :param img: PIL image object :return: PIL image object """ return img.transpose(Image.FLIP_TOP_BOTTOM)
def flip_diagonal(img): """ Flip image over both axis :param img: PIL image object :return: PIL image object """ imgcpy = img.transpose(Image.FLIP_TOP_BOTTOM) return imgcpy.transpose(Image.FLIP_LEFT_RIGHT)
def __init__(self, width=0, height=0, filename=None): if filename != None: # opengl expect images data starting from bottom self.image = Image.open(filename).transpose(Image.FLIP_TOP_BOTTOM) else: self.image = Image.new(mode='RGBA', size=(width, height)) # flatten the image data self.pixels = numpy.array([component for pixel in self.image.getdata() for component in pixel], dtype=numpy.uint8)
def mask(cls, size, round=0): """Rectangular mask with optional rounded corners.""" m = Image.new("L", size, 255) if round > 0: w, h = int(round * size[0] / 2), int(round * size[1] / 2) m.place(Quadrant.mask((w,h)), align=(0,0), copy=False) m.place(Quadrant.mask((w,h)).transpose(Image.FLIP_LEFT_RIGHT), align=(1,0), copy=False) m.place(Quadrant.mask((w,h)).transpose(Image.FLIP_TOP_BOTTOM), align=(0,1), copy=False) m.place(Quadrant.mask((w,h)).transpose(Image.ROTATE_180), align=(1,1), copy=False) return m
def __init__(self,file): self.pixels = np.asarray(Image.open(file).convert("L").transpose(Image.FLIP_TOP_BOTTOM))
def __call__(self, old_image): xtranslation, ytranslation = np.random.randint(-self.max_translation, self.max_translation + 1, size=2) xpad, ypad = abs(xtranslation), abs(ytranslation) xsize, ysize = old_image.size flipped_lr = old_image.transpose(Image.FLIP_LEFT_RIGHT) flipped_tb = old_image.transpose(Image.FLIP_TOP_BOTTOM) flipped_both = old_image.transpose(Image.ROTATE_180) new_image = Image.new("RGB", (xsize + 2 * xpad, ysize + 2 * ypad)) new_image.paste(old_image, (xpad, ypad)) new_image.paste(flipped_lr, (xpad + xsize - 1, ypad)) new_image.paste(flipped_lr, (xpad - xsize + 1, ypad)) new_image.paste(flipped_tb, (xpad, ypad + ysize - 1)) new_image.paste(flipped_tb, (xpad, ypad - ysize + 1)) new_image.paste(flipped_both, (xpad - xsize + 1, ypad - ysize + 1)) new_image.paste(flipped_both, (xpad + xsize - 1, ypad - ysize + 1)) new_image.paste(flipped_both, (xpad - xsize + 1, ypad + ysize - 1)) new_image.paste(flipped_both, (xpad + xsize - 1, ypad + ysize - 1)) new_image = new_image.crop((xpad - xtranslation, ypad - ytranslation, xpad + xsize - xtranslation, ypad + ysize - ytranslation)) return new_image
def flip_up_down(func_config): def f(image_config): if random.random() < 0.5: image_config.image = image_config.image.transpose(Image.FLIP_TOP_BOTTOM) return f
def decode(self, file, filename): try: image = Image.open(file) except Exception as e: raise ImageDecodeException( 'PIL cannot read %r: %s' % (filename or file, e)) try: image = image.transpose(Image.FLIP_TOP_BOTTOM) except Exception as e: raise ImageDecodeException( 'PIL failed to transpose %r: %s' % (filename or file, e)) # Convert bitmap and palette images to component if image.mode in ('1', 'P'): image = image.convert() if image.mode not in ('L', 'LA', 'RGB', 'RGBA'): raise ImageDecodeException('Unsupported mode "%s"' % image.mode) type = GL_UNSIGNED_BYTE width, height = image.size # tostring is deprecated, replaced by tobytes in Pillow (PIL fork) # (1.1.7) PIL still uses it image_data_fn = getattr(image, "tobytes", getattr(image, "tostring")) return ImageData(width, height, image.mode, image_data_fn())
def transpose(self, opts): ############################################### self.logger.debug("Transposing image %s: %s" % (self.file_path, str(opts))) # Parse possible arguments num_args = 0 if "flipvert" in opts: method = Image.FLIP_LEFT_RIGHT num_args += 1 if "fliphorz" in opts: method = Image.FLIP_TOP_BOTTOM num_args += 1 if "rotate90" in opts: method = Image.ROTATE_90 num_args += 1 if "rotate180" in opts: method = Image.ROTATE_180 num_args += 1 if "rotate270" in opts: method = Image.ROTATE_270 num_args += 1 if num_args != 1: raise DirpyUserError( "Transpose requires exactly one option: %s" % str(opts)) # Now rotate try: self.im_in = self.im_in.transpose(method) self.out_x, self.out_y = self.im_in.size self.modified = True except Exception as e: raise DirpyFatalError( "Error transposing image %s: %s" % (self.file_path,e)) # Write an image to a BytesIO output buffer
def __call__(self, img): """ Args: img (PIL.Image): Image to be flipped. Returns: PIL.Image: Randomly flipped image. """ if np.random.random() < 0.5: return img.transpose(Image.FLIP_TOP_BOTTOM) return img
def __init__(self, file_path): try: im = Image.open(file_path) except FileNotFoundError as e: click.secho('{}: {}'.format(e.strerror, e.filename), fg='red') exit() else: im = im.resize((512, 512), Image.NEAREST) im = im.convert('1').transpose(Image.FLIP_TOP_BOTTOM) self.image = im _bytes = io.BytesIO() im.save(_bytes, format='BMP') self.data = _bytes.getvalue()
def exif_orientation(im): """ Rotate and/or flip an image to respect the image's EXIF orientation data. """ try: exif = im._getexif() except Exception: # There are many ways that _getexif fails, we're just going to blanket # cover them all. exif = None if exif: orientation = exif.get(0x0112) if orientation == 2: im = im.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 3: im = im.rotate(180) elif orientation == 4: im = im.transpose(Image.FLIP_TOP_BOTTOM) elif orientation == 5: im = im.rotate(-90).transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 6: im = im.rotate(-90) elif orientation == 7: im = im.rotate(90).transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 8: im = im.rotate(90) return im
def _CorrectOrientation(self, image, orientation): """Use PIL to correct the image orientation based on its EXIF. See JEITA CP-3451 at http://www.exif.org/specifications.html, Exif 2.2, page 18. Args: image: source PIL.Image.Image object. orientation: integer in range (1,8) inclusive, corresponding the image orientation from EXIF. Returns: PIL.Image.Image with transforms performed on it. If no correction was done, it returns the input image. """ if orientation == 2: image = image.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 3: image = image.rotate(180) elif orientation == 4: image = image.transpose(Image.FLIP_TOP_BOTTOM) elif orientation == 5: image = image.transpose(Image.FLIP_TOP_BOTTOM) image = image.rotate(270) elif orientation == 6: image = image.rotate(270) elif orientation == 7: image = image.transpose(Image.FLIP_LEFT_RIGHT) image = image.rotate(270) elif orientation == 8: image = image.rotate(90) return image