我们从Python开源项目中,提取了以下44个代码示例,用于说明如何使用PIL.ImageOps.invert()。
def displayImageFileOnLCD(filename): print 'displays ', filename title = 'Review Mode' # resize/dither to screen resolution and send to LCD image = Image.open(filename) im_width, im_height = image.size if im_width < im_height: image = image.rotate(90) image.thumbnail(S_SIZE, Image.ANTIALIAS) image_sized = Image.new('RGB', S_SIZE, (0, 0, 0)) image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2)) # draw filename draw = ImageDraw.Draw(image_sized) font = ImageFont.truetype('arial.ttf', 18) draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0)) draw.text((2, 2), title, fill='black', font=font) draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0)) draw.text((290, 218), filename, fill='black', font=font) # display on LCD image_sized = ImageOps.invert(image_sized) image_sized = image_sized.convert('1') # convert image to black and white lcd.write(image_sized.tobytes())
def run(self): global lcd for foo in camera.capture_continuous(self.stream2, format='jpeg', use_video_port=True, resize=(S_WIDTH, S_HEIGHT), splitter_port=0): self.stream2.seek(0) # "Rewind" the stream to the beginning so we can read its content print('live-view thread') # create image and invert it image_source = Image.open(self.stream2) imageInverted = ImageOps.invert(image_source) # convert image to black or white and send to LCD lcd.write(imageInverted.convert('1').tobytes()) self.stream2.seek(0) if self.exit: break # Variables
def crop_resize(img, dimension): inv_img = ImageOps.invert(img.convert("RGB")) # returns left, upper, right, lower left, upper, right, lower = inv_img.getbbox() width = right - left height = lower - upper if width > height: # we want to add half the difference between width and height # to the upper and lower dimension padding = int(math.floor((width - height) / 2)) upper -= padding lower += padding else: padding = int(math.floor((height - width) / 2)) left -= padding right += padding img = img.crop((left, upper, right, lower)) # Image.LANCZOS # Image.BICUBIC return img.resize((dimension, dimension), Image.LANCZOS) # pulls together all the methods to distort and finalise the image
def __call__(self, img_group): if self.scale_worker is not None: img_group = self.scale_worker(img_group) image_w, image_h = img_group[0].size crop_w, crop_h = self.crop_size offsets = GroupMultiScaleCrop.fill_fix_offset(False, image_w, image_h, crop_w, crop_h) oversample_group = list() for o_w, o_h in offsets: normal_group = list() flip_group = list() for i, img in enumerate(img_group): crop = img.crop((o_w, o_h, o_w + crop_w, o_h + crop_h)) normal_group.append(crop) flip_crop = crop.copy().transpose(Image.FLIP_LEFT_RIGHT) if img.mode == 'L' and i % 2 == 0: flip_group.append(ImageOps.invert(flip_crop)) else: flip_group.append(flip_crop) oversample_group.extend(normal_group) oversample_group.extend(flip_group) return oversample_group
def __new__(cls, size, fg="black", bg=None, antialias=4, invert=False, **kwargs): """Generate an image of the appropriate shape. See mask method for additional shape-specific parameters. - size (int/(int,int)): image size - fg (color/pattern): image foreground [black] - bg (color/pattern): image background [None] - antialias (x>0): level of antialiasing (if supported), where 1.0 is none [4.0] - invert (boolean): whether to invert the shape mask [False] """ if isinstance(size, Integral): size = (size, size) if bg is None: bg = ImageColor.getrgba(fg)._replace(alpha=0) if cls.antialiasing: orig_size, size = size, [round(s * antialias) for s in size] if isinstance(bg, Image.Image): bg = bg.resize([round(s * antialias) for s in bg.size], Image.NEAREST) if isinstance(fg, Image.Image): fg = fg.resize([round(s * antialias) for s in fg.size], Image.NEAREST) mask = cls.mask(size, **kwargs) if invert: mask = mask.invert_mask() base = Image.from_pattern(bg, mask.size) if isinstance(bg, Image.Image) else Image.new("RGBA", mask.size, bg) fore = Image.from_pattern(fg, mask.size) if isinstance(fg, Image.Image) else Image.new("RGBA", mask.size, fg) img = base.overlay(fore, mask=mask) if cls.antialiasing: img = img.resize(orig_size, resample=Image.LANCZOS if antialias > 1 else Image.NEAREST) return img
def main(): if not os.path.exists('emoji'): os.mkdir('emoji') for font, glyphs in fonts.items(): font = ImageFont.truetype(font, 128) for name, glyph in glyphs.items(): im = Image.new("RGBA", (300, 300), (255, 255, 255, 0)) draw = ImageDraw.Draw(im) draw.text((50, 50), glyph, font=font, fill=(0, 0, 0)) # remove unneccessory whitespaces if needed im = im.crop(ImageOps.invert(im.convert('RGB')).getbbox()) # im = ImageOps.invert(im) im.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( im, ((size[0] - im.size[0]) // 2, (size[1] - im.size[1]) // 2)) # write into file background.save("emoji/{}.png".format(name))
def autocrop_image(image, border = 0): from PIL import Image, ImageOps size = image.size bb_image = image bbox = bb_image.getbbox() if (size[0] == bbox[2]) and (size[1] == bbox[3]): bb_image=bb_image.convert("RGB") bb_image = ImageOps.invert(bb_image) bbox = bb_image.getbbox() image = image.crop(bbox) (width, height) = image.size width += border * 2 height += border * 2 ratio = float(width)/height cropped_image = Image.new("RGBA", (width, height), (0,0,0,0)) cropped_image.paste(image, (border, border)) #TODO find epg height logo_height = 450 / int(ADDON.getSetting('channels.per.page')) logo_height = logo_height - 2 if ADDON.getSetting('program.channel.logo') == "false": cropped_image = cropped_image.resize((int(logo_height*ratio), logo_height),Image.ANTIALIAS) return cropped_image
def autocrop_image(infile,outfile): infile = xbmc.translatePath(infile) image = Image.open(infile) border = 0 size = image.size bb_image = image bbox = bb_image.getbbox() if (size[0] == bbox[2]) and (size[1] == bbox[3]): bb_image=bb_image.convert("RGB") bb_image = ImageOps.invert(bb_image) bbox = bb_image.getbbox() image = image.crop(bbox) (width, height) = image.size width += border * 2 height += border * 2 ratio = float(width)/height cropped_image = Image.new("RGBA", (width, height), (0,0,0,0)) cropped_image.paste(image, (border, border)) #TODO find epg height logo_height = 450 / int(ADDON.getSetting('channels.per.page')) logo_height = logo_height - 2 cropped_image = cropped_image.resize((int(logo_height*ratio), logo_height),Image.ANTIALIAS) outfile = xbmc.translatePath(outfile) cropped_image.save(outfile)
def post(self): # ??????? imgStr = self.get_argument("txt", default="", strip=False) # imgStr.replace(" ", "+") imgStr = base64.b64decode(imgStr) print("imgStr:", type(imgStr)) image = Image.open(io.StringIO(imgStr)) image.thumbnail((28, 28), Image.ANTIALIAS) image = image.convert('L') image = ImageOps.invert(image) image.save(work_dir + "/web-tmp.bmp", format="BMP") #??????? #print(image) # img_url = self.get_argument("img_url", default=0, strip=False) # print(img_url) server = "0.0.0.0:8500" prediction = do_inference(server, image) print('######### prediction : ', prediction) self.write(json.dumps(prediction)) # ?? grpc ???????????????? grpc ???
def cmd_info(message, parameters, recursion=0): await client.send_typing(message.channel) async for msg in client.logs_from(message.channel, limit=25): try: if msg.attachments: img = Image.open(BytesIO(requests.get(msg.attachments[0]['url']).content)).convert('RGB') neg = ImageOps.invert(img) neg.save("tmp/negative.png","PNG") img.save("tmp/positive.png","PNG") frames = [imageio.imread("tmp/negative.png"), imageio.imread("tmp/positive.png")] imageio.mimsave("tmp/epilepsy.gif", frames, duration=0.07) with open("tmp/epilepsy.gif", "rb") as outputGif: await client.send_file(message.channel, outputGif, filename="epilepsy.gif") os.system("rm tmp/epilepsy.gif tmp/negative.png tmp/positive.png") return except Exception as e: e = discord.Embed(colour=0xB5434E) e.description = "Error ocurred, 2 lazy to check what was it, try again later." await client.send_message(message.channel, embed=e) return
def apply_effects(image, effects): """method to apply effects to original image from list of effects """ for effect in effects: gray = ImageOps.grayscale(image) # dictionary with all the availble effects all_effects = { 'BLUR': image.filter(ImageFilter.BLUR), 'CONTOUR': image.filter(ImageFilter.CONTOUR), 'EMBOSS': image.filter(ImageFilter.EMBOSS), 'SMOOTH': image.filter(ImageFilter.SMOOTH), 'HULK': ImageOps.colorize(gray, (0, 0, 0, 0), '#00ff00'), 'FLIP': ImageOps.flip(image), 'MIRROR': ImageOps.mirror(image), 'INVERT': ImageOps.invert(image), 'SOLARIZE': ImageOps.solarize(image), 'GREYSCALE': ImageOps.grayscale(image), } phedited = all_effects[effect] image = phedited return phedited
def test_bbox(self): images = ( ('width-small.jpg', (68, 192, 732, 1728)), ('width-large.jpg', (106, 128, 1094, 1152)), ('height-small.jpg', (30, 96, 370, 864)), ('height-large.jpg', (68, 192, 732, 1728)), ('height-small-horizontal.jpg', (96, 30, 864, 370)), ('height-large-horizontal.jpg', (192, 68, 1728, 732)), ('text-small.jpg', (0, 0, 800, 1858)), ('width-small-noise.jpg', (0, 0, 800, 1920)), ('width-large-noise.jpg', (10, 0, 1200, 1280)), ('height-large-noise.jpg', (4, 6, 796, 1728)), ('height-large-horizontal-noise.jpg', (16, 28, 1919, 788)), ) for name, bbox in images: img_path = 'tests/fixtures/images/%s' % name img = Image.open(img_path) img = ImageOps.invert(img.convert(mode='L')) self.assertEqual(self.container.bbox(img), bbox)
def invert_images(image_folder): print("start invert images...") origin_image_folder = os.path.join(image_folder, "origin\\") print("original image folder: " + origin_image_folder) invert_image_folder = os.path.join(image_folder, "invert\\") print("inverted image folder: " + invert_image_folder) os.makedirs(invert_image_folder) for file_name in os.listdir(origin_image_folder): image_path = os.path.join(origin_image_folder, file_name) if os.path.isfile(image_path): # ignore folder print("processing image: " + file_name) image = Image.open(origin_image_folder + file_name) invert_img = image.convert("RGB") inverted_image = ImageOps.invert(invert_img) inverted_image.save(invert_image_folder + file_name)
def create_xml(folder_name, digits, gridSizeX, gridSizeY, gridSizeZ, voxelSize): grid = ET.Element("grid") grid.set("gridSizeX", str(gridSizeX)) grid.set("gridSizeY", str(gridSizeY)) grid.set("gridSizeZ", str(gridSizeZ)) grid.set("voxelSize", str(voxelSize)) grid.set("subvoxelBits", "8") grid.set("originX", "0") grid.set("originY", "0") grid.set("slicesOrientation", "Y") grid.set("originZ", "0") channels = ET.SubElement(grid, "channels") channel = ET.SubElement(channels, "channel") channel.set("type", "DENSITY") channel.set("bits", "8") channel.set("slices", "invert/%0" + str(digits) + "d.png") tree = ET.ElementTree(grid) tree.write(os.path.join(folder_name, "manifest.xml"))
def displayImageFileOnLCD(filename): print 'displays ', filename title = 'Review Mode' # resize/dither to screen resolution and send to LCD try: image = Image.open(filename) except IOError: print ("cannot identify image file", filename) image = Image.open('unidentified.jpg') im_width, im_height = image.size if im_width < im_height: image = image.rotate(90, expand=1) image.thumbnail(SCREEN_SIZE, Image.ANTIALIAS) image_sized = Image.new('RGB', SCREEN_SIZE, (0, 0, 0)) image_sized.paste(image,((SCREEN_SIZE[0] - image.size[0]) / 2, (SCREEN_SIZE[1] - image.size[1]) / 2)) # draw texts draw = ImageDraw.Draw(image_sized) font = ImageFont.truetype('arial.ttf', 18) draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0)) draw.text((2, 2), title, fill='black', font=font) draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0)) draw.text((290, 218), filename, fill='black', font=font) font = ImageFont.truetype('arial.ttf', 10) draw.rectangle([(300, 0), (399, 14)], fill=(255,255,255), outline=(0,0,0)) draw.text((302, 2), hostIP, fill='black', font=font) # display on LCD image_sized = ImageOps.invert(image_sized) image_sized = image_sized.convert('1') # convert image to black and white lcd.write(image_sized.tobytes())
def write(self, s): global lcd b1 = bytearray() b1.extend(s[:(P_WIDTH*P_HEIGHT)]) mi = min(b1) ma = max(b1) ra = ma-mi b2 = bytearray() for pix in range(P_WIDTH*P_HEIGHT): b2.append( (b1[pix]*(255/ra))-mi ) print(max(b1), min(b1), max(b2), min(b2)) image = Image.frombuffer('L', P_SIZE, b2, "raw", 'L', 0, 1) image.thumbnail(S_SIZE, Image.NEAREST) # draw = ImageDraw.Draw(image) # font = ImageFont.truetype('arial.ttf', 18) # # draw.rectangle([(0, 0), (115, 22)], fill=255, outline=0) # draw.text((2, 2), "TESt *", fill='black', font=font) image = ImageOps.invert(image) image = image.convert('1') lcd.write(image.tobytes())
def write(self, s): global lcd image = Image.frombuffer('L', P_SIZE, s, "raw", 'L', 0, 1) image = image.crop((self.x, 0, self.x+1, P_HEIGHT)) self.image_scan.paste(image,(self.x, 0)) if self.x < P_WIDTH-1: self.x += 1 image = ImageOps.invert(self.image_scan) image.thumbnail(S_SIZE, Image.NEAREST) image = image.convert('1') lcd.write(image.tobytes())
def displayImageFileOnLCD(filename): print 'displays ', filename title = 'Review Mode' # resize/dither to screen resolution and send to LCD try: image = Image.open(filename) except IOError: print ("cannot identify image file", filename) image = Image.open('unidentified.jpg') im_width, im_height = image.size if im_width < im_height: image = image.rotate(90) image.thumbnail(SCREEN_SIZE, Image.ANTIALIAS) image_sized = Image.new('RGB', SCREEN_SIZE, (0, 0, 0)) image_sized.paste(image,((SCREEN_SIZE[0] - image.size[0]) / 2, (SCREEN_SIZE[1] - image.size[1]) / 2)) # draw texts draw = ImageDraw.Draw(image_sized) font = ImageFont.truetype('arial.ttf', 18) draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0)) draw.text((2, 2), title, fill='black', font=font) draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0)) draw.text((290, 218), filename, fill='black', font=font) font = ImageFont.truetype('arial.ttf', 10) draw.rectangle([(300, 0), (399, 14)], fill=(255,255,255), outline=(0,0,0)) draw.text((302, 2), hostIP, fill='black', font=font) # display on LCD image_sized = ImageOps.invert(image_sized) image_sized = image_sized.convert('1') # convert image to black and white lcd.write(image_sized.tobytes())
def write(self, s): global lcd self.size += len(s) image = Image.frombuffer('L', (416, 240), s, "raw", 'L', 0, 1) image = image.crop((0, 0, S_WIDTH, S_HEIGHT)) image = ImageOps.invert(image) image = image.convert('1') lcd.write(image.tobytes())
def displayImageFileOnLCD(filename): print 'displays ', filename # resize/dither to screen resolution and send to LCD image = Image.open(filename) im_width, im_height = image.size if im_width < im_height: image = image.rotate(90) image.thumbnail(S_SIZE, Image.ANTIALIAS) image_sized = Image.new('RGB', S_SIZE, (0, 0, 0)) image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2)) image_sized = ImageOps.invert(image_sized) image_sized = image_sized.convert('1') # convert image to black and white lcd.write(image_sized.tobytes())
def displayImageFileOnLCD(filename): print 'displays ', filename title = 'Review Mode' # resize/dither to screen resolution and send to LCD try: image = Image.open(filename) except IOError: print ("cannot identify image file", filename) image = Image.open('unidentified.jpg') im_width, im_height = image.size if im_width < im_height: image = image.rotate(90) image.thumbnail(S_SIZE, Image.ANTIALIAS) image_sized = Image.new('RGB', S_SIZE, (0, 0, 0)) image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2)) # draw the filename draw = ImageDraw.Draw(image_sized) font = ImageFont.truetype('arial.ttf', 18) draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0)) draw.text((2, 2), title, fill='black', font=font) draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0)) draw.text((290, 218), filename, fill='black', font=font) # display on LCD image_sized = ImageOps.invert(image_sized) image_sized = image_sized.convert('1') # convert image to black and white lcd.write(image_sized.tobytes())
def __call__(self, img_group, is_flow=False): v = random.random() if v < 0.5: ret = [img.transpose(Image.FLIP_LEFT_RIGHT) for img in img_group] if self.is_flow: for i in range(0, len(ret), 2): ret[i] = ImageOps.invert(ret[i]) # invert flow pixel values when flipping return ret else: return img_group
def invert(message: discord.Message, image_arg: image): """ Invert the colors of an image. """ image_arg.set_extension("jpg") # This function only works in images because of PIL limitations assert not image_arg.gif, "**This command does not support GIF files.**" # Invert the colors and upload the image image_arg.modify(ImageOps.invert) await send_image(message, image_arg, quality=100)
def augment(self, image, batch, c, only_resize=False): if only_resize: image = ImageOps.invert(image.convert('L')).resize(self.image_size) else: rand_rotate = self.rand_rotate_map[batch, c] * 90 # rotate by 0, pi/2, pi, 3pi/2 image = ImageOps.invert(image.convert('L')) \ .rotate(rand_rotate + np.random.rand() * 22.5 - 11.25, translate=np.random.randint(-10, 11, size=2).tolist()) \ .resize(self.image_size) # rotate between -pi/16 to pi/16, translate bewteen -10 and 10 np_image = np.reshape(np.array(image, dtype=np.float32), newshape=(self.image_size[0] * self.image_size[1])) max_value = np.max(np_image) # normalization is important if max_value > 0.: np_image = np_image / max_value return np_image # mat = transform.AffineTransform(translation=np.random.randint(-10, 11, size=2).tolist()) # return np.reshape( # util.invert( # transform.resize( # transform.warp( # transform.rotate( # util.invert(image), # angle=rand_rotate + np.random.rand() * 22.5 - 11.25 # ), mat # ), output_shape=self.image_size # ) # ), newshape=(self.image_size[0] * self.image_size[1]) # )
def invert_img(imdir,outdir): im = Image.open(imdir) out_filename = outdir ImageOps.invert(im).save(out_filename, 'JPEG', quality = 100)
def icon_to_array(file="icons/color.png", width=64): img = Image.open(file).remove_transparency().resize_fixed_aspect(width=width).convert('L') return np.array(ImageOps.invert(img)) / 256
def invert_mask(self): """Invert image for use as a mask""" return ImageOps.invert(self.as_mask())
def main(): if not os.path.exists('emoji'): os.mkdir('emoji') font = ImageFont.truetype('kimberley bl.ttf', 128) for stat, bits in stat_ranges.items(): numbers, colour = bits for number in numbers: im = Image.new("RGBA", (300, 300), (255, 255, 255, 0)) draw = ImageDraw.Draw(im) draw.text((0, 0), number, font=font, fill=colour) # remove unneccessory whitespaces if needed im = im.crop(ImageOps.invert(im.convert('RGB')).getbbox()) # im = ImageOps.invert(im) im.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( im, ((size[0] - im.size[0]) // 2, (size[1] - im.size[1]) // 2)) # background.paste( # im.filter(ImageFilter.FIND_EDGES).convert('1'), # ((size[0] - im.size[0]) // 2, (size[1] - im.size[1]) // 2)) # write into file number = number.replace('±', '_') number = number.replace('+', 'plus') background.save("emoji/{}.png".format('{}{}'.format(stat, number)))
def main(): size = (128, 128) if not os.path.exists('emoji'): os.mkdir('emoji') for font, glyphs in fonts.items(): font = ImageFont.truetype(font, 128) for name, glyph in glyphs.items(): for colour_name, colour in colours.items(): im = Image.new("RGBA", (300, 300), (255, 255, 255, 0)) draw = ImageDraw.Draw(im) draw.text((100, 100), glyph, font=font, fill=colour) # remove unneccessory whitespaces if needed im = im.crop(ImageOps.invert(im.convert('RGB')).getbbox()) # im = ImageOps.invert(im) im.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( im, ((size[0] - im.size[0]) // 2, (size[1] - im.size[1]) // 2)) # write into file background.save("emoji/{}{}.png".format(colour_name, name))
def convert_image_to_ascii(image, new_width=100): image = scale_image(image, new_width) # convert to grayscale image = image.convert('L') #invertion if args.doInvert: image = ImageOps.invert(image) pixels_to_chars = map_pixels_to_ascii_chars(image) len_pixels_to_chars = len(pixels_to_chars) image_ascii = [pixels_to_chars[index: index + new_width] for index in xrange(0, len_pixels_to_chars, new_width)] return "\n".join(image_ascii)
def invert_images(self, image_directory: str, image_file_ending: str = '*.bmp'): """ In-situ converts the white on black images of a directory to black on white images :param image_directory: The directory, that contains the images :param image_file_ending: The pattern for finding files in the image_directory """ image_paths = [y for x in os.walk(image_directory) for y in glob(os.path.join(x[0], image_file_ending))] for image_path in tqdm(image_paths, desc="Inverting all images in directory {0}".format(image_directory)): white_on_black_image = Image.open(image_path).convert("L") black_on_white_image = ImageOps.invert(white_on_black_image) black_on_white_image.save(os.path.splitext(image_path)[0] + ".png")
def invert(self, ctx, target): """ Ever wanted to see the stuff of nightmares? """ try: member = await commands.MemberConverter().convert(ctx, target) url = member.avatar_url except: url = target url = url.replace("gif", "png").strip("<>") m = await ctx.send("pls wait am generating") try: b = BytesIO() async with aiohttp.ClientSession() as session: async with session.get(url) as r: img = Image.open(BytesIO(await r.read())) bio = BytesIO() if (img.mode == 'RGBA'): r,g,b,a = img.split() rgb_image = Image.merge('RGB', (r,g,b)) inverted = ImageOps.invert(rgb_image) r,g,b = inverted.split() img = Image.merge('RGBA', (r,g,b,a)) else: img = ImageOps.invert(img) img.save(bio, "PNG") bio.seek(0) await ctx.send(file=discord.File(bio, filename="invert.png")) await m.delete() except Exception as e: print(e) await m.edit(content="Unable to generate image. Provide a mention or valid URL.")
def filter_footer(self, img): """Filter to remove the hight quality footer for an image.""" # Some sites like MangaFox add an extra footer in the original # image. This footer remove importan space in the Kindle, and # we need to remove it. # # The algorithm use as a leverage the normal noise present in # an scanned image, that is higher than the one in the footer. # This means that this filter will only work in medium quality # scanners, but possibly not in high quality ones. # # The process is like this: # # 1.- Binarize the image, moving the noise at the same level # that the real information. # # 2.- Use a MinFilter of size 3 to a big mass of pixels that # containg high frequency data. That usually means # pixels surrounded with blanks. # # 3.- Do a Gaussian filter to lower more the high frequency # data, moving the mass close arround the pixel. This # will lower more the pixels surrounded with gaps. # # 4.- Discard the pixels with low mass. # _img = ImageOps.invert(img.convert(mode='L')) _img = _img.point(lambda x: x and 255) _img = _img.filter(ImageFilter.MinFilter(size=3)) _img = _img.filter(ImageFilter.GaussianBlur(radius=5)) _img = _img.point(lambda x: (x >= 48) and x) # If the image is white, we do not have bbox return img.crop(_img.getbbox()) if _img.getbbox() else img
def filter_margin(self, img): """Filter to remove empty margins in an image.""" # This filter is based on a simple Gaussian with a threshold _img = ImageOps.invert(img.convert(mode='L')) _img = _img.filter(ImageFilter.GaussianBlur(radius=3)) _img = _img.point(lambda x: (x >= 16) and x) # If the image is white, we do not have bbox return img.crop(self.bbox(_img)) if _img.getbbox() else img
def clean_up(image_folder): # delete invert, manifest.xml files = ["manifest.xml", "model.zip", "model.svx", "invert"] for file_name in files: file_path = os.path.join(image_folder, file_name) if os.path.exists(file_path): if os.path.isfile(file_path): os.remove(file_path) else: shutil.rmtree(file_path)
def create_zip(folder_name): file_name = 'model.zip' zip_file = zipfile.ZipFile(os.path.join(folder_name, "model.svx"), 'w', zipfile.ZIP_DEFLATED) zip_file.write(os.path.join(folder_name, "manifest.xml"), "manifest.xml", compress_type=zipfile.ZIP_DEFLATED) for f_name in os.listdir(os.path.join(folder_name, "invert\\")): full_file_path = os.path.join(folder_name, "invert\\" + f_name) relative_file_path = os.path.relpath(full_file_path, folder_name) zip_file.write(full_file_path, relative_file_path, compress_type=zipfile.ZIP_DEFLATED) zip_file.close() print("created zip file: " + folder_name + file_name)
def write(self, s): global lcd image = Image.frombuffer('L', PRINTER_SIZE, s, "raw", 'L', 0, 1) if self.mode == FRAME_MODE: image.thumbnail(SCREEN_SIZE, Image.NEAREST) image = ImageOps.invert(image) image = image.convert('1', dither=self.ditherMode) if self.mode == SCAN_MODE: image = image.crop((self.x, 0, self.x+1, PRINTER_HEIGHT)) self.image_scan.paste(image,(self.x, 0)) if self.x < PRINTER_WIDTH-1: self.x += 1 else: self.scanDone = True image = ImageOps.invert(self.image_scan) image.thumbnail(SCREEN_SIZE, Image.NEAREST) image = image.convert('1') if self.mode == SCAN_MODE_FIX: image = image.crop((PRINTER_WIDTH/2, 0, (PRINTER_WIDTH/2)+1, PRINTER_HEIGHT)) image_total = Image.new('L', (self.x+1, PRINTER_HEIGHT), 0) image_total.paste(self.image_scan, (0, 0)) image_total.paste(image,(self.x, 0)) self.image_scan = image_total.copy() if self.x < 5000: self.x += 1 else: self.scanDone = True image = ImageOps.invert(self.image_scan) if image.size[0] > PRINTER_SIZE[0]: image = image.crop((image.size[0]-1 - PRINTER_SIZE[0], 0, image.size[0]-1, PRINTER_HEIGHT)) image.thumbnail(SCREEN_SIZE, Image.NEAREST) image_sized = Image.new('L', SCREEN_SIZE, 0) image_sized.paste(image,(0, 0)) image = image_sized.convert('1') period = time.time() - self.lastTime if period > 0.05: self.lastTime = time.time() lcd.write(image.tobytes())
def invert(self, ctx, url :str): if not ctx.message.mentions: if not url: url = ctx.message.author.avatar_url else: pass else: url = ctx.message.mentions[0].avatar_url # Download the image img_name = "{}.png".format(url[url.rfind("/")+1:url.rfind(".")]) try: await self.download_img(ctx, url, img_name) except asyncio.TimeoutError: await ctx.send("Image is too big.") os.remove(img_name) return except ValueError: await ctx.send("Invalid link.") return # Invert the image try: image = Image.open(img_name) width, height = image.size if (width * height) > 89478485: # Checks if image is too big await ctx.send("Image is too big.") os.remove(img_name) return if image.mode == "RGBA": image.load() r, g, b, a = image.split() image = Image.merge("RGB", (r, g, b)) image = ImageOps.invert(image) r, g, b = image.split() image = Image.merge("RGBA", (r, g, b, a)) else: image = ImageOps.invert(image) except NotImplementedError: await ctx.send("Image format not supported.") os.remove(img_name) return except OSError: await ctx.send("Link not supported.") os.remove(img_name) return image.save(img_name) await ctx.channel.send(file=discord.File(img_name)) os.remove(img_name)