def get_sketch_for_posterity(self, num_bits): """Posterize the image using the number of bits, then find the areas of contiguous color and make triangles out of them, returning the resulting sketch Args: num_bits: int """ if self.color_type == RGB: im = self.source_image.convert("L") im = ImageOps.posterize(im, num_bits) im = im.convert("RGB") else: im = ImageOps.posterize(self.source_image, num_bits) areas = areas_finder.get_areas(im, 1000) triangles = [] for area in areas: triangles.extend(self.get_triangles_for_area(area)) triangles = self.filter_and_sort_triangles(triangles) num_background_triangles = min(self.num_triangles, max(50, self.num_triangles // 10)) background_triangles = self.cover_background(num_background_triangles) if len(triangles) > (self.num_triangles - num_background_triangles): over = len(triangles) - (self.num_triangles - num_background_triangles) triangles = triangles[over:] triangles = background_triangles + triangles return Sketch(self.size, self.color_type, triangles)
def hilightEdges(self): """ """ img = self.image.copy() img = ImageOps.equalize(img) xneg = ImageChops.difference(img, img.offset(-1,0)) xpos = ImageChops.difference(img, img.offset(1,0)) yneg = ImageChops.difference(img, img.offset(0,-1)) ypos = ImageChops.difference(img, img.offset(0,1)) xmax = ImageChops.lighter(xneg, xpos) ymax = ImageChops.lighter(yneg, ypos) xymax = ImageChops.lighter(xmax,ymax) xymax.show() xymax = ImageOps.autocontrast(xymax) xymax.show() xymax = ImageOps.posterize(xymax, 3) xymax = ImageOps.equalize(xymax) xymax.show() xymax = ImageOps.posterize(xymax, 2) xymax.show() self.image.show() self.image = ImageChops.screen(self.image, xymax) self.image.show()
def create_thumbnail(out, filename, types): """ Generate the thumbnail when the types==True and when the types is False generate a new image with low resolution """ file_format = FORMAT_FILE[get_file_extension(filename)] if file_format is not 'JPEG' and not types: S3BotoStorage.save(filename, ContentFile(cStringIO.StringIO(out).getvalue())) else: image = Image.open(cStringIO.StringIO(out)) # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop to thumbnail and the main image if types: imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS) imagefit = ImageOps.posterize(imagefit, 8) buf= cStringIO.StringIO() imagefit.save(buf, format= 'JPEG') S3BotoStorage.save(get_thumb_filename(filename), ContentFile(buf.getvalue())) else: buf = cStringIO.StringIO() imagefit = ImageOps.posterize(image, 8) imagefit.save( buf, quality=95, format = 'JPEG' ) S3BotoStorage.save(filename, ContentFile(buf.getvalue()))
def parse_image(image): letters = [] ownership = [] dirpath = tempfile.mkdtemp() image = Image.open(image).convert('RGB') # we can look at the top left pixel of the image to find out what our # unclaimed colour is, and thereby produce a shortlist of the themes that # this could be a screenshot of # # it must be noted that this is not a perfect approach; the pink theme, for # example, has slightly different colours for unclaimed and the background unclaimed_colours = [c[2] for c in THEMES] unclaimed_colour = closest_colour(image.getpixel((3, 3)), unclaimed_colours) colours = { c: (OPPONENT, OPPONENT, NOBODY, PLAYER, PLAYER)[i] for theme in ( t for t in THEMES if t[2] == unclaimed_colour ) for i, c in enumerate(theme) } width, height = image.size base = width/GRID_SIZE top_padding = height-width for x, y in ((x, y) for y in range(GRID_SIZE) for x in range(GRID_SIZE)): coords = ( (x * base) + base/6, (y * base) + top_padding + base/6, ((x + 1) * base) - base/6, ((y + 1) * base) + top_padding - base/6, ) crop = image.crop(coords) crop_path = os.path.join(dirpath, '{}_{}.png'.format(x, y)) ImageOps.posterize(crop, 2).save(crop_path) ownership.append( colours[closest_colour(crop.getpixel((0, 0)), colours.keys())] ) subprocess.check_output( ['tesseract', crop_path, os.path.join(dirpath, 'letter'), '-psm', '10', '-c', 'tessedit_char_whitelist={}'.format(uppercase)], stderr=subprocess.STDOUT, ) with open(os.path.join(dirpath, 'letter.txt')) as lfile: # tesseract doesn't parse | as I, so we assume if it's blank: letter = lfile.read().strip() or 'I' letters.append(letter) shutil.rmtree(dirpath) return (''.join(letters), ''.join(ownership))
def make_posterize(self, image): if image == 1: self.img1.image = ImageOps.posterize(self.img1.image, random.randint(1,8)) elif image == 2: self.img2.image = ImageOps.posterize(self.img2.image, random.randint(1,8)) elif image == 3: self.img3.image = ImageOps.posterize(self.img3.image, random.randint(1,8))
def test_sanity(): ImageOps.autocontrast(lena("L")) ImageOps.autocontrast(lena("RGB")) ImageOps.autocontrast(lena("L"), cutoff=10) ImageOps.autocontrast(lena("L"), ignore=[0, 255]) ImageOps.colorize(lena("L"), (0, 0, 0), (255, 255, 255)) ImageOps.colorize(lena("L"), "black", "white") ImageOps.crop(lena("L"), 1) ImageOps.crop(lena("RGB"), 1) ImageOps.deform(lena("L"), deformer) ImageOps.deform(lena("RGB"), deformer) ImageOps.equalize(lena("L")) ImageOps.equalize(lena("RGB")) ImageOps.expand(lena("L"), 1) ImageOps.expand(lena("RGB"), 1) ImageOps.expand(lena("L"), 2, "blue") ImageOps.expand(lena("RGB"), 2, "blue") ImageOps.fit(lena("L"), (128, 128)) ImageOps.fit(lena("RGB"), (128, 128)) ImageOps.fit(lena("RGB").resize((1, 1)), (35, 35)) ImageOps.flip(lena("L")) ImageOps.flip(lena("RGB")) ImageOps.grayscale(lena("L")) ImageOps.grayscale(lena("RGB")) ImageOps.invert(lena("L")) ImageOps.invert(lena("RGB")) ImageOps.mirror(lena("L")) ImageOps.mirror(lena("RGB")) ImageOps.posterize(lena("L"), 4) ImageOps.posterize(lena("RGB"), 4) ImageOps.solarize(lena("L")) ImageOps.solarize(lena("RGB")) success()
def cheese(z): i = 0 while (i < (RESW*RESH*65/100) or i > (RESW*RESH*95/100) ): urllib.urlretrieve("http://127.0.0.1:8081/?action=snapshot", "b%08d.jpg" % z) time.sleep(0.055) p.ChangeDutyCycle(12) time.sleep(0.055) urllib.urlretrieve("http://127.0.0.1:8081/?action=snapshot", "a%08d.jpg" % z) time.sleep(0.055) p.ChangeDutyCycle(0) time.sleep(0.055) im2 = Image.open("b%08d.jpg" % z).rotate(ROT) im1 = Image.open("a%08d.jpg" % z).rotate(ROT) draw = ImageDraw.Draw(im2) draw.rectangle([0,0,RESW,CROPH], fill=0) draw = ImageDraw.Draw(im1) draw.rectangle([0,0,RESW,CROPH], fill=0) draw.line((int(RESW/2), 0,int(RESW/2),CROPH),fill=128) diff = ImageChops.difference(im2, im1) diff = ImageOps.grayscale(diff) diff = ImageOps.posterize(diff, 6) v = diff.getcolors() i= v[0][0] #print i im1.save("b%08d.jpg" % z, quality= 90) im1 = Image.new("RGB", (RESW,RESH)) im1.paste(diff) im1.save("%08d.jpg" % z, quality= 90) im2.save("a%08d.jpg" % z, quality= 90)
def apply_posterize(pixbuf,bitsReduction): ''' for each color channel reduces the number of bits ''' width,height = pixbuf.get_width(),pixbuf.get_height() y = ImageOps.posterize(Image.frombytes(K.ImageConstants.RGB_SHORT_NAME,(width,height),pixbuf.get_pixels() ),bitsReduction) return I.fromImageToPixbuf(y)
def cheese(z): i = 0 while (i < (RESW*RESH*65/100) or i > (RESW*RESH*95/100) ): im1 = cam.get_image() time.sleep(0.055) p.ChangeDutyCycle(12) time.sleep(0.055) im2 = cam.get_image() time.sleep(0.055) p.ChangeDutyCycle(0) time.sleep(0.055) pygame.image.save(im1, "b%08d.jpg" % z) pygame.image.save(im2, "a%08d.jpg" % z) im2 = Image.open("b%08d.jpg" % z).rotate(ROT) im1 = Image.open("a%08d.jpg" % z).rotate(ROT) draw = ImageDraw.Draw(im2) draw.rectangle([0,0,RESW,CROPH], fill=0) draw = ImageDraw.Draw(im1) draw.rectangle([0,0,RESW,CROPH], fill=0) draw.line((int(RESW/2), 0,int(RESW/2),CROPH),fill=255) diff = ImageChops.difference(im2, im1) diff = ImageOps.grayscale(diff) diff = ImageOps.posterize(diff, 6) v = diff.getcolors() i= v[0][0] print i im1.save("b%08d.jpg" % z, quality= 90) im1 = Image.new("RGB", (RESW,RESH)) im1.paste(diff) im1.save("%08d.jpg" % z, quality= 90) im2.save("a%08d.jpg" % z, quality= 90)
def normalize(img, bit_depth=None): """Linear normalization and conversion to grayscale of an image.""" img = ImageOps.grayscale(img) img = ImageOps.autocontrast(img) if bit_depth is not None: img = ImageOps.posterize(img, bit_depth) return img
def compress(self, img, contrast, sharpness, channels, probability, threshold): converter = ImageEnhance.Contrast(img) img = converter.enhance(contrast) converter = ImageEnhance.Sharpness(img) img = converter.enhance(sharpness) img = ImageOps.posterize(img, channels) width, height = img.size for row in range(0, width): for col in range(0, height): if (random.random() < probability): pixel = img.getpixel((row, col)) r = pixel[0] g = pixel[1] b = pixel[2] if (r > threshold or g > threshold or b > threshold): img.putpixel((row, col), (255 - r, 255 - g, 255 - b)) return img
def GetPokemonFightNameCP(): for i in range(5): PokemonName = None PokemonCP = None img1 = GetScreen() Frame = img1.crop(((65, 190, 65+320, 190+80))) Frame = ImageOps.posterize(Frame, 6) RemoveColor(Frame, (255, 255, 255), 0.20) Frame = OnlyPureWhite(Frame) PokemonNameCP = ImgToString(Frame, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789♀♂?") PokemonNameCP = PokemonNameCP.split(' ') #New pokenom don't have the pokeball in front of name #['BLABLA', 'CP123'] if len(PokemonNameCP) == 2: CPMark = PokemonNameCP[1][:2] if CPMark == "CP": PokemonName = PokemonNameCP[0] PokemonCP = PokemonNameCP[1][2:] #@ is the pokeball #['@', 'BLABLA', 'CP123'] elif len(PokemonNameCP) == 3: CPMark = PokemonNameCP[2][:2] if CPMark == "CP": PokemonName = PokemonNameCP[1] PokemonCP = PokemonNameCP[2][2:] else: #New pokenom don't have the pokeball in front of name #['BLABLA', 'CP', '123'] CPMark = PokemonNameCP[1] if CPMark == "CP": PokemonName = PokemonNameCP[0] PokemonCP = PokemonNameCP[2] #['@', 'BLABLA', 'CP', '123'] elif len(PokemonNameCP) == 4: CPMark = PokemonNameCP[2] if CPMark == "CP": PokemonName = PokemonNameCP[1] PokemonCP = PokemonNameCP[3] if PokemonCP != None and PokemonName != None: #Little correction PokemonCP = PokemonCP.replace('O', '0') PokemonCP = PokemonCP.replace('L', '1') PokemonCP = PokemonCP.replace('l', '1') PokemonCP = PokemonCP.replace('Z', '2') PokemonCP = PokemonCP.replace('/', '7') PokemonCP = PokemonCP.replace('S', '5') PokemonCP = PokemonCP.replace('R', '8') if PokemonCP == "???": PokemonCP = "9999" try: PokemonCP = int(PokemonCP) PokemonName = FindRealPokemonName(PokemonName) #img1.save("tmp\\DEBUG_POKEFIGHT_%s_%d.png" % (PokemonName, PokemonCP)) return (PokemonName, PokemonCP) except: pass ClearScreen() return ("Unknown", 9999)
def convertir(input,output): img2 = Image.open(input) resized = ImageOps.fit(img2, (size[0], size[1]), method=Image.ANTIALIAS, bleed=0.05) expanded = ImageOps.expand(resized, border=size[5], fill=0).save('temp.JPG') fontear('temp.JPG','temp.JPG') img3 = Image.open('temp.JPG') gray = ImageOps.grayscale(img3) posterized = ImageOps.posterize(gray, 3) # (1-8) value 3 is more similar than gameboy camera posterized.save(output)
def image_posterize(src, bits="2"): # img = image_recolorize(img, black="#000000", white="#FFFFFF") """ Returns a posterized version of the src image. Bits 1-8 define your Atari system decade! The defaults set the image to a 2 bits crushed image. """ return ImageOps.posterize(src, bits)
def posterize_wb(image): """ Converts image into pure white-black one """ image = ImageOps.grayscale(image) image = ImageOps.posterize(image, 1) contrast = ImageEnhance.Contrast(image) image = contrast.enhance(4.0) return image
def posterize(image, bits, amount=100): """Apply a filter - amount: 0-1""" image = imtools.convert_safe_mode(image) posterized = imtools.remove_alpha(image) posterized = ImageOps.posterize(posterized, bits) if imtools.has_alpha(image): imtools.put_alpha(posterized, imtools.get_alpha(image)) if amount < 100: return imtools.blend(image, posterized, amount / 100.0) return posterized
def DoCanny(infile, outfile, lowThresh=LOW, highThresh=HIGH, aperature=APERATURE): import cv from cv import * from PIL import Image, ImageOps lowThresh = float(lowThresh) highThresh = float(highThresh) aperature = int(aperature) pi = ImageOps.posterize(ImageOps.grayscale(Image.open(infile)), 5) cv_img = cv.CreateImageHeader(pi.size, IPL_DEPTH_8U, 1) cv.SetData(cv_img, pi.tostring(), pi.size[0]) out = cv.CreateImage(cv.GetSize(cv_img), IPL_DEPTH_8U, 1) cv.Canny(cv_img, out, lowThresh, highThresh, aperature) pi = Image.fromstring("L", cv.GetSize(out), out.tostring()) pi.save(outfile)
def videotex_repr(self,w =80,h =72): '''Return a list of strings, one for each line of characters in the converted image. The width and height are specified in subpixels, and are always rounded up to an even number (for x) or a multiple of 3 (for y).''' # tweak w and h to proper values w = ((w+1)/2)*2 h = ((h+2)/3)*3 # convert image to grayscale and resize im = self.img.convert("L") im = im.resize((w,h),Image.ANTIALIAS) # normalize contrast im = ImageOps.autocontrast(im) # down to 3-bit im = ImageOps.posterize(im,3) # colorhack each 6-cell for i in range(w/2): for j in range(h/3): colorhack(im,i*2,j*3) # define gencode def gencode(self,image,x,y): """generate display codes for 2x3 block""" dark,light = findDarkLight(image,x,y) v = 0 for i, j in subpixels: v = (v >> 1) if image.getpixel((x+i,y+j)) == light: v = v | (1 << 5) c = '' if light != self.lastlight: c = c + '\x1b' + chr(0x40+convcolor(light)) if dark != self.lastdark: c = c + '\x1b' + chr(0x50+convcolor(dark)) c = c + chr(32+v) self.lastlight,self.lastdark = light,dark return c # generate codes for videotex self.lastdark, self.lastlight = -255, -255 codes = [] for j in range(h/3): codeline = '' for i in range(w/2): codeline = codeline + gencode(self,im,i*2,j*3) codes.append(codeline) return codes
def detect_motion(camera): global prior_image global captured_image global captured_image_file_names global rect_coords stream = io.BytesIO() camera.capture(stream, format='jpeg', use_video_port=True) stream.seek(0) if prior_image is None: prior_image = Image.open(stream) return False else: current_image = Image.open(stream) diff_image = ImageOps.posterize(ImageOps.grayscale(ImageChops.difference(prior_image, current_image)), 1) rect_coords = diff_image.getbbox() if rect_coords != None: captured_image = current_image.copy() # draw box around the image ImageDraw.Draw(captured_image).rectangle(rect_coords, outline="yellow", fill=None) image_guid = str(uuid.uuid4()) captured_image_file_name = image_guid + '.jpg' # save file to file system save_image_thread = threading.Thread(target=save_image, args=(captured_image_file_name,)) save_image_thread.start() if len(captured_image_file_names) < 5: captured_image_file_names.append(captured_image_file_name) prior_image = current_image return True else: return False
def to_videotex(self, w=80, h=72): """ Returns a list of strings, one for each line of characters in the converted image. The width and height are specified in sub-pixels, and are always rounded up to an even number (for x) or a multiple of 3 (for y). Parameters: w (int): target image width (in sub-pixels) h (int): target image height (in sub-pixels) Returns: list[str]: the Videotex sequence reproducing the image """ if not Image: return [] # tweak w and h to proper values w = ((w + 1) / 2) * 2 h = ((h + 2) / 3) * 3 # convert image to gray scale and resize im = self._image.convert("L") im = im.resize((w, h), Image.ANTIALIAS) # normalize contrast im = ImageOps.autocontrast(im) # down to 3-bit im = ImageOps.posterize(im, 3) # color hack each 6-cell for i in range(w / 2): for j in range(h / 3): self._color_hack(im, i * 2, j * 3) # generate codes for videotex self.last_dark = self.last_light = -255 codes = [] for j in range(h / 3): code_line = '' for i in range(w / 2): code_line += self._generate_code(im, i * 2, j * 3) codes.append(code_line) return codes
def obamafy(path, out_path, config): image = Image.open(path) image = ImageOps.posterize(image, config.posterization) image = image.filter(ImageFilter.MedianFilter(size=config.median)) image = ImageOps.grayscale(image) color_table = make_color_table(image, config) image_array = numpy.array(image) transform = numpy.vectorize(lambda c: color_table[c], otypes=[numpy.uint8, numpy.uint8, numpy.uint8]) image_array = numpy.dstack(transform(image_array)) obamafied = Image.fromarray(image_array) obamafied.save(get_out_path(path, out_path))
def richter_strip_ify(infile, outfile, nbits=4): im = Image.open(infile) pim = ImageOps.posterize(im, nbits) pim.save("foo.png") colors = [color for (count, color) in pim.getcolors(im.size[0]*im.size[1])] ncolors = len(colors) print "found %d colors" % ncolors newim = Image.new("RGB", (2, ncolors), "white") pix = newim.load() indx = np.argsort(np.random.uniform(size=ncolors)) for ii, color in zip(indx, colors): for jj in range(newim.size[0]): pix[jj, ii] = color yfactor = np.round(float(im.size[1]) / float(ncolors)).astype(int) ysize = yfactor * ncolors xsize = np.round(float(ysize * im.size[0]) / float(im.size[1])).astype(int) newim = newim.resize((xsize, yfactor*ncolors), Image.NEAREST) newim.save(outfile)
def applyfilter(pk, preset): post = get_object_or_404(Post, pk=pk) infile = post.images.url f = infile.split('.') newfile = f[0] + '-new.' + f[1] f = newfile.split('/') newfilename = f[-1] infile.replace("/","//") im = Image.open(infile) if preset == 'gray': im = ImageOps.grayscale(im) if preset == 'edge': im = ImageOps.grayscale(im) im = im.filter(ImageFilter.FIND_EDGES) if preset == 'poster': im = ImageOps.posterize(im,3) if preset == 'solar': im = ImageOps.solarize(im, threshold=80) if preset == 'blur': im = im.filter(ImageFilter.BLUR) if preset == 'sepia': sepia=[] #sepia2=[] r,g,b=(239,224,185) for i in range(255): sepia.extend((r*i//255,g*i//255,b*i//255)) #for i in sepia: # if i>0: # n=i-i%i # else: n=0 # sepia2.extend(n) #print (sepia2) im = im.convert("L") im.putpalette(sepia) im = im.convert("RGB") im.save(newfile) return newfilename
def cheese(self, z): i = 0 while (i < (self.RESW*self.RESH*65/100) or i > (self.RESW*self.RESH*95/100) ): im1 = self.cam.get_image() time.sleep(0.055) #155) self.ser.write('I') # turns laser on time.sleep(0.15) #55) im2 = self.cam.get_image() time.sleep(0.055) #155) self.ser.write('O') # turns laser off #time.sleep(0.1) #55) time.sleep(0.055) pygame.image.save(im1, "b%08d.jpg" % z) pygame.image.save(im2, "a%08d.jpg" % z) im2 = Image.open("b%08d.jpg" % z).rotate(self.ROT) im1 = Image.open("a%08d.jpg" % z).rotate(self.ROT) # cropping the top off images draw = ImageDraw.Draw(im2) draw.rectangle([0,0, self.RESW, self.CROPH], fill=0) draw = ImageDraw.Draw(im1) draw.rectangle([0,0, self.RESW, self.CROPH], fill=0) draw.line( (int(self.RESW/2), 0,int(self.RESW/2),self.CROPH), fill=255 ) # extracting the difference between images diff = ImageChops.difference(im2, im1) diff = ImageOps.grayscale(diff) diff = ImageOps.posterize(diff, 6) v = diff.getcolors() i = v[0][0] print i im1.save("b%08d.jpg" % z, quality = 90) im1 = Image.new("RGB", (self.RESW,self.RESH)) im1.paste(diff) im1.save("%08d.jpg" % z, quality = 90) im2.save("a%08d.jpg" % z, quality = 90)
def SortPic(): paths = [".\\sample"] for path in paths: for root, dirs, files in os.walk(path): for name in files: if name.find("000_") == -1: print(os.path.join(root, name)) img = Image.open(os.path.join(root, name)) # Test 1: Fail at 000_2015-12-09_14-22-54 # img = ImageOps.posterize(img, 1) # Test 2: img = img.convert("L") img = ImageOps.posterize(img, 1) # img = img.filter(ImageFilter.FIND_EDGES) # img = img.convert("L") # Save img.save(os.path.join(path, "000_" + name))
def posterize(img, bits_to_keep, **__): if bits_to_keep >= 8: return img return ImageOps.posterize(img, bits_to_keep)
async def _process_commands(self, command: str, path: str): ar = [x.split(" ") for x in [a.strip(" ") for a in command.split(',')]] im: Image = PIL.Image.open(path) # im.load() im = im.convert("RGBA") print(ar) fmt = "png" for e in ar: for i in range(3): e.append(None) if e[0] == "convert": mode = e[1] if not mode or mode not in "bw,rgb,rgba,luma,web,adaptive": raise commands.ConversionError("Unknown conversion mode", original=None) if mode == "bw": im = im.convert("1") if mode in ["rgb", "rgba"]: im = im.convert(mode.upper()) if mode == "luma": im = im.convert("L") if mode == "web": im = im.convert("P") if mode == "adaptive": im = im.convert("P", palette=ADAPTIVE, colors=min(int(e[2]), 256) if e[2] else 256) if e[0] == "format": if not e[1] or e[1] not in "png,jpg,gif".split(","): raise commands.ConversionError(f"Invalid output format {e[1]}", original=None) fmt = e[1] if e[0] == "bw": im = im.convert("1").convert("RGBA") if e[0] == "luma": im = im.convert("L").convert("RGBA") if e[0] == "autocontrast": im = im.convert("RGB") im = ImageOps.autocontrast(im, int(e[1]) if e[1] else 0) im = im.convert("RGBA") if e[0] == "rotate": im = im.rotate(int(e[1])) if e[0] == "invert": im = ImageOps.invert(im) if e[0] == "grayscale": im = ImageOps.grayscale(im) if e[0] == "equalize": im = ImageOps.equalize(im) if e[0] == "sepia": im = ImageOps.colorize(ImageOps.grayscale(im), (0, 0, 0), (255, 255, 255), mid=(112, 66, 20)) if e[0] == "colorize": im = ImageOps.colorize(ImageOps.grayscale(im), (0, 0, 0), (255, 255, 255), mid=self._color(e[1])) if e[0] == "posterize": im = ImageOps.posterize(im, int(e[1]) if e[1] else 128) if e[0] == "solarize": im = im.convert("RGB") if len(e) > 1: a = int(e[1]) else: a = 128 im = ImageOps.solarize(im, a) im = im.convert("RGBA") if e[0] == "flip": im = ImageOps.flip(im) if e[0] == "mirror": im = ImageOps.mirror(im) if e[0] == "blur": if len(e) > 1: a = int(e[1]) else: a = 2 im = im.filter(ImageFilter.GaussianBlur(a)) if e[0] == "boxblur": if len(e) > 1: a = int(e[1]) else: a = 2 im = im.filter(ImageFilter.BoxBlur(a)) if e[0] == "sharpen": im = im.filter(ImageFilter.UnsharpMask(int(e[1]) if e[1] else 2, int(e[2]) if e[2] else 150, int(e[3]) if e[3] else 3)) if e[0] == "scale": im = ImageOps.scale(im, float(e[1])) if e[0] == "pscale": im = ImageOps.scale(im, float(e[1]), PIL.Image.NEAREST) if e[0] == "scalexy": im = im.resize((int(im.width * float(e[1])), int(im.height * float(e[2])))) if e[0] == "pscalexy": im = im.resize((int(im.width * float(e[1])), int(im.height * float(e[2]))), PIL.Image.NEAREST) if e[0] == "scaleto": im = im.resize((int(e[1]), int(e[2])), PIL.Image.BICUBIC) if e[0] == "pscaleto": im = im.resize((int(e[1]), int(e[2])), PIL.Image.NEAREST) if e[0] == "potografy": im = im.resize((int(im.width / 20), int(im.height / 4)), PIL.Image.NEAREST) im = im.resize((int(im.width * 20), int(im.height * 4)), PIL.Image.NEAREST) im = ImageOps.posterize(im, 2) im = ImageOps.colorize(ImageOps.grayscale(im), (0, 0, 0), (255, 255, 255), mid=(112, 66, 20)) im = im.rotate(25) if e[0] == "matrix": size = (im.width, im.height) im = im.resize((int(e[1]), int(e[2])), PIL.Image.NEAREST) im = im.resize(size, PIL.Image.NEAREST) a = path.split(".") async with self.lock: self.counter += 1 b = str(self.counter) + "." + fmt # + a[-1] im.save(b) return True, b, os.path.getsize(b)
def __init__(self, num_layers=2, magnitude=5, fillcolor=(128, 128, 128)): self.num_layers = num_layers self.magnitude = magnitude self.max_level = 10 abso_level = self.magnitude / self.max_level self.level_map = { "shearX": 0.3 * abso_level, "shearY": 0.3 * abso_level, "translateX": 150.0 / 331 * abso_level, "translateY": 150.0 / 331 * abso_level, "rotate": 30 * abso_level, "color": 0.9 * abso_level, "posterize": int(4.0 * abso_level), "solarize": 256.0 * abso_level, "contrast": 0.9 * abso_level, "sharpness": 0.9 * abso_level, "brightness": 0.9 * abso_level, "autocontrast": 0, "equalize": 0, "invert": 0 } # from https://stackoverflow.com/questions/5252170/ # specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand def rotate_with_fill(img, magnitude): rot = img.convert("RGBA").rotate(magnitude) return Image.composite(rot, Image.new("RGBA", rot.size, (128, ) * 4), rot).convert(img.mode) rnd_ch_op = random.choice self.func = { "shearX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, magnitude * rnd_ch_op([-1, 1]), 0, 0, 1, 0), Image.BICUBIC, fillcolor=fillcolor), "shearY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, magnitude * rnd_ch_op([-1, 1]), 1, 0), Image.BICUBIC, fillcolor=fillcolor), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * rnd_ch_op([-1, 1]), 0, 1, 0), fillcolor=fillcolor), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * rnd_ch_op([-1, 1])), fillcolor=fillcolor), "rotate": lambda img, magnitude: rotate_with_fill(img, magnitude), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance( 1 + magnitude * rnd_ch_op([-1, 1])), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance( 1 + magnitude * rnd_ch_op([-1, 1])), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( 1 + magnitude * rnd_ch_op([-1, 1])), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( 1 + magnitude * rnd_ch_op([-1, 1])), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: ImageOps.equalize(img), "invert": lambda img, magnitude: ImageOps.invert(img) }
def image_posterize(src, bits="2"): return ImageOps.posterize(src, bits)
converter = PIL.ImageEnhance.Brightness(img).enhance(4.5) converter.save('brightness.jpg') converter = PIL.ImageEnhance.Color(img).enhance(4.5) converter.save('colorful.jpg') blur = img.filter(ImageFilter.GaussianBlur(radius = 10)) blur.save('blur.jpg') converter = PIL.ImageEnhance.Contrast(img).enhance(4.5) converter.save('highcontrast.jpg') im = ImageOps.posterize(img, 3) im.save('posterized.jpg') inverted_image = PIL.ImageOps.invert(img) inverted_image.save('invert.png') crop = img.crop((0, 0, 2500, 2500)) crop.save('cropped.jpg') rotate = img.rotate(180) rotate.save('rotated.jpg')
def pillow(self, img): return ImageOps.posterize(img, 4)
def transformImage(self, img): return ImageOps.posterize(img, self.args["bits"])
def process(self, img): return ImageOps.posterize(img, bits=self.bits)
def func_posterize(img, magnitude): return ImageOps.posterize(img, magnitude)
def posterize(img: Image.Image, bits: int) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return ImageOps.posterize(img, bits)
def FindPokemon(): ReturnToMap() #TestFindPokemon() img = GetScreen().copy() #Remove the player RemoveInSquare(img, 227, 482, 22, 40) #Remove the Experience notification RemoveInSquare(img, 24, 600, 115, 70) #Apply amask to keep only "Pokemon zone" mask = Image.new('L', (480, 800), 255) draw = ImageDraw.Draw(mask) PokemonZone = (65, 420, 135 + 300, 438 + 250) draw.ellipse(PokemonZone, fill=0) img.paste((255, 255, 255), mask=mask) Frame = img.crop((PokemonZone)) Frame = ImageOps.posterize(Frame, 2) ColorBlackList = [] if IsDay() == True: #Day Road ColorBlackList.append((64, 128, 128)) ColorBlackList.append((0, 128, 128)) #Green ColorBlackList.append((0, 192, 128)) ColorBlackList.append((128, 192, 128)) ColorBlackList.append((128, 192, 64)) ColorBlackList.append((64, 192, 128)) ColorBlackList.append((64, 192, 64)) #Day Road Boarder ColorBlackList.append((192, 192, 128)) else: #Road ColorBlackList.append((64, 128, 192)) #Green ColorBlackList.append((64, 128, 128)) ColorBlackList.append((0, 128, 128)) ColorBlackList.append((0, 64, 128)) ColorBlackList.append((0, 64, 64)) ColorBlackList.append((64, 128, 64)) #Night Road Boarder ColorBlackList.append((128, 128, 128)) #Spinned Pokestop ColorBlackList.append((192, 128, 192)) ColorBlackList.append((64, 64, 192)) ColorBlackList.append((128, 64, 192)) #Lured Pokestop ColorBlackList.append((192, 64, 192)) #Pokestop ColorBlackList.append((0, 128, 192)) ColorBlackList.append((64, 192, 192)) ColorBlackList.append((0, 192, 192)) ColorBlackList.append((0, 64, 192)) #Lured Pokestop Circle ColorBlackList.append((128, 192, 192)) #Lured Pokestop Flowers ColorBlackList.append((192, 192, 192)) #Green rustles ColorBlackList.append((0, 128, 64)) ColorBlackList.append((128, 128, 64)) ColorBlackList.append((128, 192, 128)) ColorBlackList.append((0, 192, 0)) ColorBlackList.append((128, 192, 0)) ColorBlackList.append((0, 64, 0)) ColorBlackList.append((64, 192, 0)) ColorBlackList.append((64, 192, 128)) ColorBlackList.append((0, 128, 0)) RemoveColorList(Frame, ColorBlackList) BlackOrWhite(Frame) #Search for big Pokemon before small one for i in range(10, 2, -2): PokemonPosition = FindPokemonPosition(Frame, i) if not PokemonPosition is None: PokemonPosition[0] += PokemonZone[0] PokemonPosition[1] += PokemonZone[1] return PokemonPosition return None
def __call__(self, img, ranges): # print("Called Policy 0: (Posterize,0.4,8) (Rotate,0.6,9)") if random.random() < 0.4: img = ImageOps.posterize(img, ranges["posterize"][8]) if random.random() < 0.6: img = img.rotate(ranges["rotate"][9]) return img
def _posterize_impl(pil_img, level): """Applies PIL Posterize to `pil_img`.""" level = int_parameter(level, 4) return ImageOps.posterize(pil_img.convert('RGB'), 4 - level).convert('RGBA')
def FindPokemon(): ReturnToMap(); #TestFindPokemon() img = GetScreen().copy() #Remove the player RemoveInSquare(img, 227, 482, 22, 40) #Remove the Experience notification RemoveInSquare(img, 24, 600, 115, 70) #Apply amask to keep only "Pokemon zone" mask = Image.new('L', (480, 800), 255) draw = ImageDraw.Draw(mask) PokemonZone = (65, 420, 135+300, 438+250) draw.ellipse(PokemonZone, fill=0) img.paste((255, 255, 255), mask=mask) Frame = img.crop((PokemonZone)) Frame = ImageOps.posterize(Frame, 2) ColorBlackList = [] if IsDay() == True: #Day Road ColorBlackList.append((64, 128, 128)) ColorBlackList.append((0, 128, 128)) #Green ColorBlackList.append((0, 192, 128)) ColorBlackList.append((128, 192, 128)) ColorBlackList.append((128, 192, 64)) ColorBlackList.append((64, 192, 128)) ColorBlackList.append((64, 192, 64)) #Day Road Boarder ColorBlackList.append((192, 192, 128)) else: #Road ColorBlackList.append((64, 128, 192)) #Green ColorBlackList.append((64, 128, 128)) ColorBlackList.append((0, 128, 128)) ColorBlackList.append((0, 64, 128)) ColorBlackList.append((0, 64, 64)) ColorBlackList.append((64, 128, 64)) #Night Road Boarder ColorBlackList.append((128, 128, 128)) #Spinned Pokestop ColorBlackList.append((192, 128, 192)) ColorBlackList.append((64, 64, 192)) ColorBlackList.append((128, 64, 192)) #Lured Pokestop ColorBlackList.append((192, 64, 192)) #Pokestop ColorBlackList.append((0, 128, 192)) ColorBlackList.append((64, 192, 192)) ColorBlackList.append((0, 192, 192)) ColorBlackList.append((0, 64, 192)) #Lured Pokestop Circle ColorBlackList.append((128, 192, 192)) #Lured Pokestop Flowers ColorBlackList.append((192, 192, 192)) #Green rustles ColorBlackList.append((0, 128, 64)) ColorBlackList.append((128, 128, 64)) ColorBlackList.append((128, 192, 128)) ColorBlackList.append((0, 192, 0)) ColorBlackList.append((128, 192, 0)) ColorBlackList.append((0, 64, 0)) ColorBlackList.append((64, 192, 0)) ColorBlackList.append((64, 192, 128)) ColorBlackList.append((0, 128, 0)) RemoveColorList(Frame, ColorBlackList) BlackOrWhite(Frame) #Search for big Pokemon before small one for i in range(10, 2, -2): PokemonPosition = FindPokemonPosition(Frame, i) if not PokemonPosition is None: PokemonPosition[0] += PokemonZone[0] PokemonPosition[1] += PokemonZone[1] return PokemonPosition return None
async def deepfry(img: Image, *, token: str = None, url_base: str = 'westcentralus', session: aiohttp.ClientSession = None, type=DeepfryTypes.RED) -> Image: """ Deepfry an image. img: PIL.Image - Image to deepfry. [token]: str - Token to use for Microsoft facial recognition API. If this is not supplied, lens flares will not be added. [url_base]: str = 'westcentralus' - API base to use. Only needed if your key's region is not `westcentralus`. [session]: aiohttp.ClientSession - Optional session to use with API requests. If provided, may provide a bit more speed. Returns: PIL.Image - Deepfried image. """ img = img.copy().convert('RGB') if type not in DeepfryTypes: raise ValueError( f'Unknown deepfry type "{type}", expected a value from deeppyer.DeepfryTypes' ) if token: req_url = f'https://{url_base}.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=false&returnFaceLandmarks=true' # WHY THE F**K IS THIS SO LONG headers = { 'Content-Type': 'application/octet-stream', 'Ocp-Apim-Subscription-Key': token, 'User-Agent': 'DeepPyer/1.0' } b = BytesIO() img.save('flare.png') b.seek(0) if session: async with session.post(req_url, headers=headers, data=b.read()) as r: face_data = await r.json() else: async with aiohttp.ClientSession() as s, s.post( req_url, headers=headers, data=b.read()) as r: face_data = await r.json() if 'error' in face_data: err = face_data['error'] code = err.get('code', err.get('statusCode')) msg = err['message'] raise Exception( f'Error with Microsoft Face Recognition API\n{code}: {msg}') if face_data: landmarks = face_data[0]['faceLandmarks'] # Get size and positions of eyes, and generate sizes for the flares eye_left_width = math.ceil(landmarks['eyeLeftInner']['x'] - landmarks['eyeLeftOuter']['x']) eye_left_height = math.ceil(landmarks['eyeLeftBottom']['y'] - landmarks['eyeLeftTop']['y']) eye_left_corner = (landmarks['eyeLeftOuter']['x'], landmarks['eyeLeftTop']['y']) flare_left_size = eye_left_height if eye_left_height > eye_left_width else eye_left_width flare_left_size *= 4 eye_left_corner = tuple( math.floor(x - flare_left_size / 2.5 + 5) for x in eye_left_corner) eye_right_width = math.ceil(landmarks['eyeRightOuter']['x'] - landmarks['eyeRightInner']['x']) eye_right_height = math.ceil(landmarks['eyeRightBottom']['y'] - landmarks['eyeRightTop']['y']) eye_right_corner = (landmarks['eyeRightInner']['x'], landmarks['eyeRightTop']['y']) flare_right_size = eye_right_height if eye_right_height > eye_right_width else eye_right_width flare_right_size *= 4 eye_right_corner = tuple( math.floor(x - flare_right_size / 2.5 + 5) for x in eye_right_corner) # Crush image to hell and back img = img.convert('RGB') width, height = img.width, img.height img = img.resize((int(width**.75), int(height**.75)), resample=Image.LANCZOS) img = img.resize((int(width**.88), int(height**.88)), resample=Image.BILINEAR) img = img.resize((int(width**.9), int(height**.9)), resample=Image.BICUBIC) img = img.resize((width, height), resample=Image.BICUBIC) img = ImageOps.posterize(img, 4) # Generate red and yellow overlay for classic deepfry effect r = img.split()[0] r = ImageEnhance.Contrast(r).enhance(2.0) r = ImageEnhance.Brightness(r).enhance(1.5) if type == DeepfryTypes.RED: r = ImageOps.colorize(r, Colours.RED, Colours.YELLOW) elif type == DeepfryTypes.BLUE: r = ImageOps.colorize(r, Colours.BLUE, Colours.WHITE) # Overlay red and yellow onto main image and sharpen the hell out of it img = Image.blend(img, r, 0.75) img = ImageEnhance.Sharpness(img).enhance(100.0) if token and face_data: # Copy and resize flares flare = Image.open('flare.png') flare_left = flare.copy().resize((flare_left_size, ) * 2, resample=Image.BILINEAR) flare_right = flare.copy().resize((flare_right_size, ) * 2, resample=Image.BILINEAR) del flare img.paste(flare_left, eye_left_corner, flare_left) img.paste(flare_right, eye_right_corner, flare_right) return img
KERN = args['kernel'] ascii_fillers = [ "*", "&", "#", "@", "0", "%", "S", "-", "^", "~", ";", ",", "!" ] if args.get('random', 0): random.shuffle(ascii_fillers) orig = resize_by_multiples(image=Image.open(args['path']), multiple=KERN * KERN, char_limit=100) mode_filter = ImageFilter.ModeFilter(size=KERN) color_img = orig.filter(mode_filter).filter(ImageFilter.EDGE_ENHANCE_MORE) color_img = ImageOps.posterize(color_img, 3) grey_img = color_img.convert("L") orig = orig.filter(ImageFilter.GaussianBlur) grey_pxl = grey_img.load() color_pxl = orig.load() min_grey_value = round(254 / (len(ascii_fillers) - 1)) w, h = grey_img.size for y_step in range(0, h, KERN * KERN): line = [] # [(char, color), ...] for x_step in range(0, w, KERN * KERN): grey_kern = Counter([ grey_pxl[x_step + x, y_step + y] for y in range(KERN)
def posterize(x, level): level = 1 + int(level * 7.999) return ImageOps.posterize(x, level)
def _posterize(pil_img, level): level = AugMix._int_parameter(AugMix._sample_level(level), 4) return ImageOps.posterize(pil_img, 4 - level)
def posterize(pil_img, level): level = int_parameter(sample_level(level), 4) return ImageOps.posterize(pil_img, 4 - level)
def __init__(self, Numbers=None, max_Magnitude=None): self.transforms = [ 'autocontrast', 'equalize', 'rotate', 'solarize', 'color', 'posterize', 'contrast', 'brightness', 'sharpness', 'shearX', 'shearY', 'translateX', 'translateY' ] if Numbers is None: self.Numbers = len(self.transforms) // 2 else: self.Numbers = Numbers if max_Magnitude is None: self.max_Magnitude = 10 else: self.max_Magnitude = max_Magnitude fillcolor = 128 self.ranges = { # these Magnitude range , you must test it yourself , see what will happen after these operation , # it is no need to obey the value in autoaugment.py "shearX": np.linspace(0, 0.3, 10), "shearY": np.linspace(0, 0.3, 10), "translateX": np.linspace(0, 0.2, 10), "translateY": np.linspace(0, 0.2, 10), "rotate": np.linspace(0, 360, 10), "color": np.linspace(0.0, 0.9, 10), "posterize": np.round(np.linspace(8, 4, 10), 0).astype(np.int), "solarize": np.linspace(256, 231, 10), "contrast": np.linspace(0.0, 0.5, 10), "sharpness": np.linspace(0.0, 0.9, 10), "brightness": np.linspace(0.0, 0.3, 10), "autocontrast": [0] * 10, "equalize": [0] * 10, "invert": [0] * 10 } self.func = { "shearX": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, magnitude * random.choice( [-1, 1]), 0, 0, 1, 0), Image.BICUBIC, fill=fillcolor), "shearY": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, 0, 0, magnitude * random. choice([-1, 1]), 1, 0), Image.BICUBIC, fill=fillcolor), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * random.choice( [-1, 1]), 0, 1, 0), fill=fillcolor), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * random. choice([-1, 1])), fill=fillcolor), "rotate": lambda img, magnitude: self.rotate_with_fill(img, magnitude), # "rotate": lambda img, magnitude: img.rotate(magnitude * random.choice([-1, 1])), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance( 1 + magnitude * random.choice([-1, 1])), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance( 1 + magnitude * random.choice([-1, 1])), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: img, "invert": lambda img, magnitude: ImageOps.invert(img) }
def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2, fillcolor=(128, 128, 128)): ranges = { "shearX": np.linspace(0, 0.3, 10), "shearY": np.linspace(0, 0.3, 10), "translateX": np.linspace(0, 150 / 331, 10), "translateY": np.linspace(0, 150 / 331, 10), "rotate": np.linspace(0, 30, 10), "color": np.linspace(0.0, 0.9, 10), "posterize": np.round(np.linspace(8, 4, 10), 0).astype(np.int), "solarize": np.linspace(256, 0, 10), "contrast": np.linspace(0.0, 0.9, 10), "sharpness": np.linspace(0.0, 0.9, 10), "brightness": np.linspace(0.0, 0.9, 10), "autocontrast": [0] * 10, "equalize": [0] * 10, "invert": [0] * 10 } # from https://stackoverflow.com/questions/5252170/specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand def rotate_with_fill(img, magnitude): rot = img.convert("RGBA").rotate(magnitude) return Image.composite(rot, Image.new("RGBA", rot.size, (128, ) * 4), rot).convert(img.mode) func = { "shearX": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, magnitude * random.choice( [-1, 1]), 0, 0, 1, 0), Image.BICUBIC, fillcolor=fillcolor), "shearY": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, 0, 0, magnitude * random. choice([-1, 1]), 1, 0), Image.BICUBIC, fillcolor=fillcolor), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * random.choice( [-1, 1]), 0, 1, 0), fillcolor=fillcolor), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * random. choice([-1, 1])), fillcolor=fillcolor), "rotate": lambda img, magnitude: rotate_with_fill(img, magnitude), # "rotate": lambda img, magnitude: img.rotate(magnitude * random.choice([-1, 1])), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance( 1 + magnitude * random.choice([-1, 1])), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance( 1 + magnitude * random.choice([-1, 1])), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: ImageOps.equalize(img), "invert": lambda img, magnitude: ImageOps.invert(img) } # self.name = "{}_{:.2f}_and_{}_{:.2f}".format( # operation1, ranges[operation1][magnitude_idx1], # operation2, ranges[operation2][magnitude_idx2]) self.p1 = p1 self.operation1 = func[operation1] self.magnitude1 = ranges[operation1][magnitude_idx1] self.p2 = p2 self.operation2 = func[operation2] self.magnitude2 = ranges[operation2][magnitude_idx2]
def GetPokemonFightNameCP(): for i in range(5): PokemonName = None PokemonCP = None img1 = GetScreen() Frame = img1.crop(((65, 190, 65 + 320, 190 + 80))) Frame = ImageOps.posterize(Frame, 6) RemoveColor(Frame, (255, 255, 255), 0.20) Frame = OnlyPureWhite(Frame) PokemonNameCP = ImgToString( Frame, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789♀♂?" ) PokemonNameCP = PokemonNameCP.split(' ') #New pokenom don't have the pokeball in front of name #['BLABLA', 'CP123'] if len(PokemonNameCP) == 2: CPMark = PokemonNameCP[1][:2] if CPMark == "CP": PokemonName = PokemonNameCP[0] PokemonCP = PokemonNameCP[1][2:] #@ is the pokeball #['@', 'BLABLA', 'CP123'] elif len(PokemonNameCP) == 3: CPMark = PokemonNameCP[2][:2] if CPMark == "CP": PokemonName = PokemonNameCP[1] PokemonCP = PokemonNameCP[2][2:] else: #New pokenom don't have the pokeball in front of name #['BLABLA', 'CP', '123'] CPMark = PokemonNameCP[1] if CPMark == "CP": PokemonName = PokemonNameCP[0] PokemonCP = PokemonNameCP[2] #['@', 'BLABLA', 'CP', '123'] elif len(PokemonNameCP) == 4: CPMark = PokemonNameCP[2] if CPMark == "CP": PokemonName = PokemonNameCP[1] PokemonCP = PokemonNameCP[3] if PokemonCP != None and PokemonName != None: #Little correction PokemonCP = PokemonCP.replace('O', '0') PokemonCP = PokemonCP.replace('L', '1') PokemonCP = PokemonCP.replace('l', '1') PokemonCP = PokemonCP.replace('Z', '2') PokemonCP = PokemonCP.replace('/', '7') PokemonCP = PokemonCP.replace('S', '5') PokemonCP = PokemonCP.replace('R', '8') if PokemonCP == "???": PokemonCP = "9999" try: PokemonCP = int(PokemonCP) PokemonName = FindRealPokemonName(PokemonName) #img1.save("tmp\\DEBUG_POKEFIGHT_%s_%d.png" % (PokemonName, PokemonCP)) return (PokemonName, PokemonCP) except: pass ClearScreen() return ("Unknown", 9999)
def posterize(img, level): "Control bits count used to store colors" bits = 5 - int_parameter(level, 4) return ImageOps.posterize(img, bits)
def __call__(self, img, ranges): if random.random() < 0.6: img = ImageOps.posterize(img, ranges["posterize"][7]) if random.random() < 0.6: img = ImageOps.posterize(img, ranges["posterize"][6]) return img
def do_process(self, img): return ImageOps.posterize(img, int(self.magnitude))
def __call__(self, img, ranges): if random.random() < 0.8: img = ImageOps.posterize(img, ranges["posterize"][5]) img = ImageOps.equalize(img) return img
def process(self, command, args): # autocontrast if command == 'autocontrast': return ImageOps.autocontrast(self.im) # blur if command == 'blur': return self.im.filter(ImageFilter.BLUR) # brightness if command == 'brightness': try: return ImageEnhance.Brightness(self.im).enhance(float(args[0])) except: raise Exception('Invalid brightness argument') # color if command == 'color': try: return ImageEnhance.Color(self.im).enhance(float(args[0])) except: raise Exception('Invalid color argument') # colorize if command == 'colorize': try: return ImageOps.colorize( ImageOps.grayscale(self.im), black='%s' % args[0], white='%s' % args[1] ) except: raise Exception('Invalid colorize arguments') # contour if command == 'contour': return self.im.filter(ImageFilter.CONTOUR) # contrast if command == 'contrast': try: return ImageEnhance.Contrast(self.im).enhance(float(args[0])) except: raise Exception('Invalid contrast argument') # crop if command == 'crop': try: return self.im.crop(tuple([int(a) for a in args])) except: raise Exception('Invalid crop arguments') # cropratio if command == 'cropratio': try: # get sizes width = float(self.im.size[0]) height = float(self.im.size[1]) orig_ratio = width / height target_ratio = float(args[0]) # crop if orig_ratio > target_ratio: # same height, change width target_width = int(round(height * target_ratio)) left = int(round((width / 2) - (target_width / 2))) return self.im.crop(( left, 0, left + target_width, int(height), )) elif target_ratio > orig_ratio: # same width, change height target_height = int(round(width / target_ratio)) top = int(round((height / 2) - (target_height / 2))) return self.im.crop(( 0, top, int(width), top + target_height )) else: return self.im except: raise Exception('Invalid cropratio arguments') # emboss if command == 'emboss': return self.im.filter(ImageFilter.EMBOSS) # equalize if command == 'equalize': return ImageOps.equalize(self.im) # fliphoriz if command == 'fliphoriz': return self.im.transpose(Image.FLIP_LEFT_RIGHT) # flipvert if command == 'flipvert': return self.im.transpose(Image.FLIP_TOP_BOTTOM) # gblur if command == 'gblur': try: return self.im.filter(ImageFilter.GaussianBlur(radius=int(args[0]))) except: raise Exception('Invalid gblur argument') # grayscale if command == 'grayscale': return ImageOps.grayscale(self.im) # invert if command == 'invert': return ImageOps.invert(self.im) # posterize if command == 'posterize': try: return ImageOps.posterize(self.im, int(args[0])) except: raise Exception('Invalid posterize argument') # resize if command == 'resize': try: return self.im.resize( tuple([int(a) for a in args]), resample=Image.ANTIALIAS ) except: raise Exception('Invalid resize arguments') # resizepc if command == 'resizepc': try: x, y = self.im.size return self.im.resize( (int(x * float(args[0])), int(y * float(args[1]))), resample=Image.ANTIALIAS ) except: raise Exception('Invalid resize arguments') # rotate if command == 'rotate': try: return self.im.rotate(int(args[0])) except: raise Exception('Invalid rotate argument') # sharpness if command == 'sharpness': try: return ImageEnhance.Sharpness(self.im).enhance(float(args[0])) except: raise Exception('Invalid sharpness argument') # solarize if command == 'solarize': try: return ImageOps.solarize(self.im, int(args[0])) except: raise Exception('Invalid solarize argument') # fallback raise Exception('Invalid function name "%s"' % command)
def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2, fillcolor=(128, 128, 128)): ranges = { "shearX": np.linspace(0, 0.3, 10), "shearY": np.linspace(0, 0.3, 10), "translateX": np.linspace(0, 150 / 331, 10), "translateY": np.linspace(0, 150 / 331, 10), "rotate": np.linspace(0, 30, 10), "color": np.linspace(0.0, 0.9, 10), "posterize": np.round(np.linspace(8, 4, 10), 0).astype(np.int), "solarize": np.linspace(256, 0, 10), "contrast": np.linspace(0.0, 0.9, 10), "sharpness": np.linspace(0.0, 0.9, 10), "brightness": np.linspace(0.0, 0.9, 10), "autocontrast": [0] * 10, "equalize": [0] * 10, "invert": [0] * 10, "cutout": np.linspace(0.0, 0.2, 10), } def Cutout(img, v): # [0, 60] => percentage: [0, 0.2] #assert 0.0 <= v <= 0.2 if v <= 0.: return img v = v * img.size[0] return CutoutAbs(img, v) # x0 = np.random.uniform(w - v) # y0 = np.random.uniform(h - v) # xy = (x0, y0, x0 + v, y0 + v) # color = (127, 127, 127) # img = img.copy() # PIL.ImageDraw.Draw(img).rectangle(xy, color) # return img def CutoutAbs(img, v): # [0, 60] => percentage: [0, 0.2] # assert 0 <= v <= 20 if v < 0: return img w, h = img.size x0 = np.random.uniform(w) y0 = np.random.uniform(h) x0 = int(max(0, x0 - v / 2.)) y0 = int(max(0, y0 - v / 2.)) x1 = min(w, x0 + v) y1 = min(h, y0 + v) xy = (x0, y0, x1, y1) color = (125, 123, 114) # color = (0, 0, 0) img = img.copy() ImageDraw.Draw(img).rectangle(xy, color) return img # from https://stackoverflow.com/questions/5252170/specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand def rotate_with_fill(img, magnitude): rot = img.convert("RGBA").rotate(magnitude) return Image.composite(rot, Image.new("RGBA", rot.size, (128, ) * 4), rot).convert(img.mode) func = { "shearX": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, magnitude * random.choice( [-1, 1]), 0, 0, 1, 0), Image.BICUBIC, fillcolor=fillcolor), "shearY": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, 0, 0, magnitude * random. choice([-1, 1]), 1, 0), Image.BICUBIC, fillcolor=fillcolor), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * random.choice( [-1, 1]), 0, 1, 0), fillcolor=fillcolor), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * random. choice([-1, 1])), fillcolor=fillcolor), "cutout": lambda img, magnitude: Cutout(img, magnitude), "rotate": lambda img, magnitude: rotate_with_fill(img, magnitude), # "rotate": lambda img, magnitude: img.rotate(magnitude * random.choice([-1, 1])), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance( 1 + magnitude * random.choice([-1, 1])), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance( 1 + magnitude * random.choice([-1, 1])), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: ImageOps.equalize(img), "invert": lambda img, magnitude: ImageOps.invert(img) } # self.name = "{}_{:.2f}_and_{}_{:.2f}".format( # operation1, ranges[operation1][magnitude_idx1], # operation2, ranges[operation2][magnitude_idx2]) self.p1 = p1 self.operation1 = func[operation1] self.magnitude1 = ranges[operation1][magnitude_idx1] self.p2 = p2 self.operation2 = func[operation2] self.magnitude2 = ranges[operation2][magnitude_idx2]
def test_sanity(self): ImageOps.autocontrast(hopper("L")) ImageOps.autocontrast(hopper("RGB")) ImageOps.autocontrast(hopper("L"), cutoff=10) ImageOps.autocontrast(hopper("L"), ignore=[0, 255]) ImageOps.autocontrast_preserve(hopper("L")) ImageOps.autocontrast_preserve(hopper("RGB")) ImageOps.autocontrast_preserve(hopper("L"), cutoff=10) ImageOps.autocontrast_preserve(hopper("L"), ignore=[0, 255]) ImageOps.colorize(hopper("L"), (0, 0, 0), (255, 255, 255)) ImageOps.colorize(hopper("L"), "black", "white") ImageOps.crop(hopper("L"), 1) ImageOps.crop(hopper("RGB"), 1) ImageOps.deform(hopper("L"), self.deformer) ImageOps.deform(hopper("RGB"), self.deformer) ImageOps.equalize(hopper("L")) ImageOps.equalize(hopper("RGB")) ImageOps.expand(hopper("L"), 1) ImageOps.expand(hopper("RGB"), 1) ImageOps.expand(hopper("L"), 2, "blue") ImageOps.expand(hopper("RGB"), 2, "blue") ImageOps.fit(hopper("L"), (128, 128)) ImageOps.fit(hopper("RGB"), (128, 128)) ImageOps.flip(hopper("L")) ImageOps.flip(hopper("RGB")) ImageOps.grayscale(hopper("L")) ImageOps.grayscale(hopper("RGB")) ImageOps.invert(hopper("L")) ImageOps.invert(hopper("RGB")) ImageOps.mirror(hopper("L")) ImageOps.mirror(hopper("RGB")) ImageOps.posterize(hopper("L"), 4) ImageOps.posterize(hopper("RGB"), 4) ImageOps.solarize(hopper("L")) ImageOps.solarize(hopper("RGB"))