def test_sanity(self): im = hopper("L") ImageChops.constant(im, 128) ImageChops.duplicate(im) ImageChops.invert(im) ImageChops.lighter(im, im) ImageChops.darker(im, im) ImageChops.difference(im, im) ImageChops.multiply(im, im) ImageChops.screen(im, im) ImageChops.add(im, im) ImageChops.add(im, im, 2.0) ImageChops.add(im, im, 2.0, 128) ImageChops.subtract(im, im) ImageChops.subtract(im, im, 2.0) ImageChops.subtract(im, im, 2.0, 128) ImageChops.add_modulo(im, im) ImageChops.subtract_modulo(im, im) ImageChops.blend(im, im, 0.5) ImageChops.composite(im, im, im) ImageChops.offset(im, 10) ImageChops.offset(im, 10, 20)
def random_image(img=IMG, size=(200, 100)): """Create a random PIL image by messing with a source image""" width, height = size ratio = width / height square = int(min(max(width, height) * sqrt(2), min(img.size))) x = random.randint(0, img.width - square) y = random.randint(0, img.height - square) angle = random.randint(0, 360) subsection = img.crop([x, y, x + square, y + square]) rotated = subsection.rotate(angle) inscribed = square / sqrt(2) if ratio > 1: cw, ch = inscribed, inscribed / ratio else: cw, ch = inscribed * ratio, inscribed cropbox = ( (square - cw) / 2, (square - ch) / 2, (square + cw) / 2, (square + ch) / 2, ) cropbox = tuple(map(int, cropbox)) blur = ImageFilter.GaussianBlur(1) cropped = rotated.crop(cropbox).resize(size) colorized = scramble_colors(cropped) blended = ImageChops.blend(cropped, colorized, 0.5).filter(blur) equalized = ImageOps.equalize(blended) result = ImageChops.blend(blended, equalized, 0.5) return result
def draw_segmentation_masks(mask, image=None, alpha=0.8, color=None): """Draws segmentation masks on given RGB image. Args: mask: a numpy array, shape is (H, W). image: a PIL instance. alpha: float number between 0 and 1 denoting the transparency of the masks. 0 means full transparency, 1 means no transparency. color: str or tuple or la.image.RGBMode, rgb color, point color. List containing the colors of the masks. returns: a PIL instance. """ canvas = np.zeros((mask.shape[0], mask.shape[1], 3)) if color is not None: assert len( color) == mask.max() + 1, 'color size not equal mask nunique size.' else: color = tuple([ tuple([np.random.randint(0, 256) for j in range(3)]) for i in range(int(mask.max() + 1)) ]) for label in range(int(mask.max() + 1)): if canvas[mask == label].size: canvas[mask == label] = color[label] canvas = array_to_image(canvas) if image is None: return canvas if image.size != canvas.size: return ImageChops.blend(image.resize(canvas.size), canvas, alpha=alpha) return ImageChops.blend(image, canvas, alpha=alpha)
def gen_and_save_mirror(first_path: Optional[pathlib.Path], stem: str, first: Image, middle: Image, last: Image, len_images: int, output_dirs: Dict[str, pathlib.Path]) -> None: flipped: Image = ImageOps.flip(last) mirrored: Image = ImageOps.mirror(middle) flipped_and_mirrored: Image = ImageOps.mirror(flipped) two_combo: Image = ImageChops.subtract(first, flipped) save(two_combo, output_dirs['mirror'], stem, 'combo_2', first_path) three_combo: Image = ImageChops.blend(two_combo, mirrored, 0.33) save(three_combo, output_dirs['mirror'], stem, 'combo_3', first_path) four_combo: Image = ImageChops.blend(three_combo, flipped_and_mirrored, 0.25) save(four_combo, output_dirs['mirror'], stem, 'combo_4', first_path) four_combo_2: Image = ImageOps.flip( ImageChops.difference( ImageChops.screen(ImageChops.difference(first, mirrored), flipped), flipped_and_mirrored)) save(four_combo_2, output_dirs['mirror'], stem, 'combo_4_2', first_path) if len_images > 1: pairwise_subtract: Image = ImageChops.subtract( ImageChops.blend(first, flipped, 0.5), ImageChops.blend(mirrored, flipped_and_mirrored, 0.5)) save(pairwise_subtract, output_dirs['mirror'], stem, 'pairwise_sub', first_path) sub_inv: Image = ImageChops.subtract(first, ImageChops.invert(flipped)) save(sub_inv, output_dirs['mirror'], stem, 'inv_flip_sub', first_path)
def blend(img_one, img_two, transparency): mid_size = [int((img_one.size[x] + img_two.size[x]) / 2) for x in range(2)] img_one_resized = img_one.resize(mid_size) img_two_resized = img_two.resize(mid_size) img_one_resized = img_one_resized.convert(mode='RGBA') img_two_resized = img_two_resized.convert(mode='RGBA') output = io.BytesIO() ImageChops.blend(img_one_resized, img_two_resized, transparency).save(output, format='PNG') ImageChops.blend(img_one_resized, img_two_resized, transparency).save( r'C:\Users\Luke\Downloads\PIL testing\trster.png', format='PNG') output.seek(0) return output
def deepDreamRecursive(self, image, layer, iterations, lr, num_downscales): if num_downscales > 0: # scale down the image image_small = image.filter(ImageFilter.GaussianBlur(2)) # 高斯模糊 small_size = (int(image.size[0]/2), int(image.size[1]/2)) if (small_size[0] == 0 or small_size[1] == 0): small_size = image.size image_small = image_small.resize(small_size, Image.ANTIALIAS) # run deepDreamRecursive on the scaled down image image_small = self.deepDreamRecursive(image_small, layer, iterations, lr, num_downscales-1) print('Num Downscales : {}'.format(num_downscales)) print('====Small Image=====') plt.imshow(image_small) plt.show() # Scale up the result image to the original size image_large = image_small.resize(image.size, Image.ANTIALIAS) print('====Large Image=====') plt.imshow(image_large) plt.show() # Blend the two image image = ImageChops.blend(image, image_large, BLEDN_ALPHA) print('====Blend Image=====') plt.imshow(image) plt.show() img_result = self.deepDream(image, layer, iterations, lr) print(img_result.size) img_result = img_result.resize(image.size) print(img_result.size) return img_result
def take_action(self, parsed_args): outfile = Image.new("RGB", (900, 1100), (255, 255, 255)) xpad = int(((outfile.size[0] - 150) / ((4 * parsed_args.width)) / 3)) if xpad < 1: xpad = 1 base_left_o = int( (((outfile.size[0] - (4 * parsed_args.width)) + xpad)) / 2) left_o = base_left_o nrows = int(parsed_args.ncrops / 4) top_o = int( (outfile.size[1] - int((nrows * parsed_args.height) + xpad * (nrows - 1))) / 2) for i in range(1, parsed_args.ncrops + 1): if isinstance(parsed_args.img_filename, list): filename = random.choice(parsed_args.img_filename) else: filename = parsed_args.img_filename original = Image.open(filename) crop = self._crop(parsed_args, original) if parsed_args.merge: crop = ImageChops.blend(crop, self._crop(parsed_args, original), 0.5) outfile.paste(crop, (left_o, top_o)) if i % 4 == 0: left_o = base_left_o top_o += parsed_args.height + xpad else: left_o += parsed_args.width + xpad self.save(parsed_args.outputdir, 'gallery', outfile) outfile.show()
def ELA(): # Error Level Analysis for basic image forensics original = Image.open(inp) # open up the input image original.save(TEMP, quality=95) # re-save the image with a quality of 95% temporary = Image.open(TEMP) # open up the re-saved image diff = ImageChops.difference( original, temporary) # load in the images to look at pixel by pixel differences d = diff.load() # load the image into a variable WIDTH, HEIGHT = diff.size # set the size into a tuple for x in range(WIDTH): # row by row for y in range(HEIGHT): # column by column d[x, y] = tuple(k * SCALE for k in d[ x, y]) # set the pixels to their x,y & color based on error diff.save('ela-saved.jpg') # save the ELA version of the image #diff.show() # show the ELA version new_img = ImageChops.blend( temporary, diff, ALPHA) # blend the original w/ the ELA @ a set alpha/transparency new_img.save('comp-saved.jpg', quality=95) # save the image @ 95% quality new_img.show() # display the blended image -- original + ELA
def deep_dream(self, image, layer, iterations, lr, octave_scale, num_octaves): if num_octaves > 0: image1 = image.filter(ImageFilter.GaussianBlur(2)) if (image1.size[0] / octave_scale < 1 or image1.size[1] / octave_scale < 1): size = image1.size else: size = (int(image1.size[0] / octave_scale), int(image1.size[1] / octave_scale)) image1 = image1.resize(size, Image.ANTIALIAS) image1 = self.deep_dream(image1, layer, iterations, lr, octave_scale, num_octaves - 1) print( '--------------------------------------------second deeam-----------------------------------' ) size = (image.size[0], image.size[1]) image1 = image1.resize(size, Image.ANTIALIAS) image = ImageChops.blend(image, image1, 0.6) print("-------------- Recursive level: ", num_octaves, '--------------') img_result = self.dd_helper(image, layer, iterations, lr) img_result = img_result.resize(image.size) return img_result
def main(): print("a") blankSet = np.zeros((WIDTH, HEIGHT)) im1 = Image.fromarray(blankSet, "RGBA") im2 = Image.fromarray(blankSet, "RGBA") imageDrawer1 = ImageDraw.Draw(im1) imageDrawer2 = ImageDraw.Draw(im2) imageDrawer1.rectangle((25, 25) + (475, 475), fill="green", outline="black", width=5) im1.save("pillow4Green.png") im1.show() imageDrawer2.rectangle((200, 200) + (300, 300), fill="blue", outline="black", width=5) im2.show() im2.save("pillow4Blue.png") im3 = ImageChops.add(im1, im2) im3.show() im3.save("pillow4Add.png") im4 = ImageChops.blend(im1, im2, 0.5) im4.show() im4.save("pillow4Blend.png")
def main(): print("a") mech = Image.open("Mech.png") ellipse = Image.open("Ellipse.png") ellipse = ellipse.convert("RGB") output = ImageChops.blend(mech, ellipse, 0.5) output.show()
def deep_dream(image, layer, iterations, lr, octave_scale, num_octaves): ''' Takes the image, requested layer, iterations, learning rate, and scale and performs the deep dream transformation ''' if num_octaves > 0: temp_image = image # Downscale the image by octave_scale if (temp_image.size[0] / octave_scale < 1) or (temp_image.size[1] / octave_scale < 1): size = temp_image.size else: size = (int(temp_image.size[0]/octave_scale), int(temp_image.size[1]/octave_scale)) # Call this function recursively to apply the deep dream filter to downscaled versions of this image temp_image = temp_image.resize(size, Image.ANTIALIAS) temp_image = deep_dream(temp_image, layer, iterations, lr, octave_scale, num_octaves - 1) temp_image = temp_image.resize(image.size, Image.ANTIALIAS) # Blend the processed image into the original image image = ImageChops.blend(image, temp_image, 0.6) # This is where the deep dream logic is applied to this version of the image result = image_forward(transform_image(image), layer, iterations, lr) result = result.resize(image.size) return result
def compare(pages_x, pages_y, img_format='png', all_pages=False): # create a list of tuples from corresponding pages of both sources # we assume here that the order in which to compare them is the list order pages = list(zip(pages_x, pages_y)) differences = [] diff_cnt = 0 for page_x, page_y in pages: # reset binary stream position page_x.seek(0) page_y.seek(0) # open the image and convert to RGBA mode img_x = Image.open(page_x).convert('RGBA') img_y = Image.open(page_y).convert('RGBA') diff_xy = ImageChops.difference(img_x, img_y) # check if the images are identical; if so, getbbox() will return None # http://effbot.org/zone/pil-comparing-images.htm if diff_xy.getbbox(): log.debug('Difference found') diff_cnt += 1 # http://stackoverflow.com/questions/18341754/color-in-red-diffrencies-between-two-pictures red_layer = Image.new(diff_xy.mode, diff_xy.size, 'red') # Make a red layer the same size diff_red = ImageChops.multiply(red_layer, diff_xy) comp_xy = ImageChops.blend(diff_red, img_y, 0.7) diff_stream = BufferedRandom(BytesIO()) comp_xy.save(diff_stream, format=img_format) differences.append(diff_stream) elif all_pages: log.debug('Pages are identical') # no difference detected between the 2 images; just save one of the originals diff_stream = BufferedRandom(BytesIO()) img_x.save(diff_stream, format=img_format) differences.append(diff_stream) if all_pages and len(pages_x) != len(pages_y): log.debug('Adding remaining pages (nothing to compare to)') # we need to return a complete set of pages, and both sets contain a different number of pages shortest, longest = ( pages_x, pages_y) if len(pages_x) < len(pages_y) else (pages_y, pages_x) remaining = longest[len(shortest):] for page in remaining: page.seek(0) img = Image.open(page).convert('RGBA') diff_stream = BufferedRandom(BytesIO()) img.save(diff_stream, format=img_format) differences.append(diff_stream) log.debug('{} differences found'.format(diff_cnt)) return differences
def set_image(self, image): self.image = image self.select_image = ImageChops.blend(image, Image.new('RGBA', image.size, (0x00, 0x00, 0xff, 0xff)), 0x44/0xff) self.c_image = ImageTk.PhotoImage(self.image) self.c_select_image = ImageTk.PhotoImage(self.select_image) self.w = image.width self.h = image.height
def make_grid_frames(): frame = Image.open("D:/Projects/StaticWater_Rend_NM/0001.png") flat = Image.new('RGBA', frame.size, (127, 127, 255, 255)) frameCount = 64 altFrameCount = 32 for i in range(1, frameCount + 1): frame = Image.open("D:/Projects/StaticWater_Rend_NM/{}.png".format(str(i).zfill(4))) if i <= altFrameCount: alpha = float(i) / float(altFrameCount) altFrame = Image.open("D:/Projects/StaticWater_Rend_NM/{}.png".format(str(frameCount + i).zfill(4))) altFrame = ImageChops.blend(flat, altFrame, crossfade_spline(1.0 - alpha)) frame = ImageChops.blend(flat, frame, crossfade_spline(alpha)) frame = blend_normal_maps(frame, altFrame) #frame = Image.merge('RGB', frame.split()[0:3]) frame = blend_normal_maps(frame, flat) frame.save("D:/Projects/StaticWater_Fade2/{}.png".format(str(i).zfill(4)))
def handle_image_pixel(): img1 = Image.open('avatar.jpeg') img2 = Image.open('scenery.jpeg') # 叠加 add(image1, image2, scale=1.0, offset=0)[source] :: out = ((image1 + image2) / scale + offset) ops_img = ImageChops.add(img1, img2, scale=2, offset=100) ops_img.save('chops_add.jpg') # .add_modulo(image1, image2)[source] #:: out = ((image1 + image2) % MAX) ops_img = ImageChops.add_modulo(img1, img2) ops_img.save('chops_add_modulo.jpg') # blend(image1, image2, alpha)[source] Alias for PIL.Image.Image.blend(). ops_img = ImageChops.blend(img1, img2.resize(img1.size), 0.5) ops_img.save('chops_blend.jpg') # composite(image1, image2, mask)[source] : Alias for PIL.Image.Image.composite(). # A mask image. This image can have mode "1", "L", or "RGBA", and must have the same size as the other two images ops_img = ImageChops.composite(img1, img2, Image.new('L', img1.size)) ops_img.save('chops_composite.jpg') # .constant(image, value)[source] # Fill a channel with a given grey level. ops_img = ImageChops.constant(img1, 200) ops_img.save('chops_constant.jpg') # darker(image1, image2)[source] :: # out = min(image1, image2) ops_img = ImageChops.darker(img1, img2) ops_img.save('chops_darker.jpg') # difference(image1, image2)[source] # out = abs(image1 - image2) ops_img = ImageChops.difference(img1, img2) ops_img.save('chops_difference.jpg') # duplicate(image)[source] Alias for PIL.Image.Image.copy(). # PIL.ImageChops.invert(image)[source] # out = MAX - image # PIL.ImageChops.lighter(image1, image2)[source] out = max(image1, image2) # PIL.ImageChops.logical_and(image1, image2)[source] # Logical AND between two images. # out = ((image1 and image2) % MAX) # PIL.ImageChops.logical_or(image1, image2)[source] # Logical OR between two images. # out = ((image1 or image2) % MAX) # PIL.ImageChops.multiply(image1, image2)[source] # Superimposes two images on top of each other. # out = image1 * image2 / MAX # If you multiply an image with a solid black image, the result is black. If you multiply with a solid white image, the image is unaffected. # PIL.ImageChops.offset(image, xoffset, yoffset=None)[source] # Returns a copy of the image where data has been offset by the given distances. # Data wraps around the edges. If yoffset is omitted, it is assumed to be equal to xoffset. # 参数: # xoffset – The horizontal distance. # yoffset – The vertical distance. If omitted, both distances are set to the same value. # PIL.ImageChops.screen(image1, image2)[source] #:: out = MAX - ((MAX - image1) * (MAX - image2) / MAX) # Superimposes two inverted images on top of each other. ops_img = ImageChops.screen(img1, img2) ops_img.save('chops_screen.jpg') # PIL.ImageChops.subtract(image1, image2, scale=1.0, offset=0)[source] #:: out = ((image1 - image2) / scale + offset) # Subtracts two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. ops_img = ImageChops.subtract(img1, img2) ops_img.save('chops_subtract.jpg') # PIL.ImageChops.subtract_modulo(image1, image2)[source] # out:: = ((image1 - image2) % MAX) # Subtract two images, without clipping the result. ops_img = ImageChops.subtract_modulo(img1, img2) ops_img.save('chops_subtract_modulo.jpg')
def blend_images(img1, img2, alpha): """ Returns a new image made by combining the two images. Each pixel position is added together to get the new image. The two images *must* be the same size (see resize_image). The two images *must* both be colored or grayscale. The alpha parameter (0.0 to 1.0) is the weight given to the values from the second image. """ return ImageChops.blend(img1, img2, alpha)
def manipulate(): response = requests.get(d) img = Image.open(BytesIO(response.content)) size = img.size for y in range(1,10): img2=Image.open(os.path.join(mr,"filters","filter({}).jpg".format(y))) img2=img2.resize(size, Image.ANTIALIAS) img3=ImageChops.blend(img,img2,alpha=(2/10)) img3=ImageChops.darker(img,img2) img3.save(os.path.join(mr,"outputs","Artified_img-{}.jpg".format(y)))
def add_noise(img, noise_percentage): if noise_percentage <= 0: return img noise = numpy.random.randint(0, 255, size=(img.height, img.width, 3), dtype=numpy.uint8) noise_image = Image.fromarray(noise, mode='RGB').convert('RGBA') return ImageChops.blend(img, noise_image, noise_percentage / 100)
def compare(pages_x, pages_y, img_format='png', all_pages=False): # create a list of tuples from corresponding pages of both sources # we assume here that the order in which to compare them is the list order pages = list(zip(pages_x, pages_y)) differences = [] diff_cnt = 0 for page_x, page_y in pages: # reset binary stream position page_x.seek(0) page_y.seek(0) # open the image and convert to RGBA mode img_x = Image.open(page_x).convert('RGBA') img_y = Image.open(page_y).convert('RGBA') diff_xy = ImageChops.difference(img_x, img_y) # check if the images are identical; if so, getbbox() will return None # http://effbot.org/zone/pil-comparing-images.htm if diff_xy.getbbox(): log.debug('Difference found') diff_cnt += 1 # http://stackoverflow.com/questions/18341754/color-in-red-diffrencies-between-two-pictures red_layer = Image.new(diff_xy.mode, diff_xy.size, 'red') # Make a red layer the same size diff_red = ImageChops.multiply(red_layer, diff_xy) comp_xy = ImageChops.blend(diff_red, img_y, 0.7) diff_stream = BufferedRandom(BytesIO()) comp_xy.save(diff_stream, format=img_format) differences.append(diff_stream) elif all_pages: log.debug('Pages are identical') # no difference detected between the 2 images; just save one of the originals diff_stream = BufferedRandom(BytesIO()) img_x.save(diff_stream, format=img_format) differences.append(diff_stream) if all_pages and len(pages_x) != len(pages_y): log.debug('Adding remaining pages (nothing to compare to)') # we need to return a complete set of pages, and both sets contain a different number of pages shortest, longest = (pages_x, pages_y) if len(pages_x) < len(pages_y) else (pages_y, pages_x) remaining = longest[len(shortest):] for page in remaining: page.seek(0) img = Image.open(page).convert('RGBA') diff_stream = BufferedRandom(BytesIO()) img.save(diff_stream, format=img_format) differences.append(diff_stream) log.debug('{} differences found'.format(diff_cnt)) return differences
def test_blend(self): # Arrange im1 = Image.open("Tests/images/imagedraw_ellipse_RGB.png") im2 = Image.open("Tests/images/imagedraw_floodfill_RGB.png") # Act new = ImageChops.blend(im1, im2, 0.5) # Assert self.assertEqual(new.getbbox(), (25, 25, 76, 76)) self.assertEqual(new.getpixel((50, 50)), BROWN)
def _draw_identicon(color, grid_list, pixels): identicon_im = white.copy() # identicon_im = identicon_bkgnd.copy() draw = ImageDraw.Draw(identicon_im) for grid, pixel in zip(grid_list, pixels): if grid != 0: # for not zero draw.rectangle(pixel, fill=color) identicon_im = ImageChops.blend(identicon_im, white, 0.7) out = ImageChops.multiply(identicon_im, identicon_bkgnd) return out
def test_blend(self): # Arrange im1 = Image.open("Tests/images/imagedraw_ellipse_RGB.png") im2 = Image.open("Tests/images/imagedraw_floodfill.png") # Act new = ImageChops.blend(im1, im2, 0.5) # Assert self.assertEqual(new.getbbox(), (25, 25, 76, 76)) self.assertEqual(new.getpixel((50, 50)), BROWN)
def test_blend(): # Arrange with Image.open("Tests/images/imagedraw_ellipse_RGB.png") as im1: with Image.open("Tests/images/imagedraw_floodfill_RGB.png") as im2: # Act new = ImageChops.blend(im1, im2, 0.5) # Assert assert new.getbbox() == (25, 25, 76, 76) assert new.getpixel((50, 50)) == BROWN
def imgBeauty(): image = Image.open("temp.png").convert('RGBA') fltBeauBlur = ImageFilter.GaussianBlur(3) imageBeauBlur = image.filter(fltBeauBlur) imageBeauLight = ImageChops.lighter(image, imageBeauBlur) fltBeauSharp = ImageEnhance.Sharpness(image) imageBeauSharp = fltBeauSharp.enhance(2.0) imageBeauBlend = ImageChops.blend(imageBeauSharp, imageBeauLight, 0.7) flt = ImageEnhance.Contrast(imageBeauBlend) out = flt.enhance(1.2) out.save("./temp.png") return out
def __update_preview_from_pil_file(self, new_chunk_file_path): img = Image.open(new_chunk_file_path) scaled = img.resize((int(round(self.scale_factor * self.res_x)), int(round(self.scale_factor * self.res_y))), resample=Image.BILINEAR) img.close() img_current = self._open_preview() img_current = ImageChops.blend(img_current, scaled, 1.0 / self.num_add) img_current.save(self.preview_file_path, PREVIEW_EXT) img.close() scaled.close() img_current.close()
def mix_all(self): #全局混合图片 w = self.img1.size[0] h = self.img1.size[1] ratio = float(w / h) self.img2 = self.img2.resize((self.img1.size[0], self.img1.size[1]), IM.ANTIALIAS) self.img3 = ICs.blend(self.img1, self.img2, self.s1_value.get() / 100) if ratio >= 1.77: self.photo3 = ITk.PhotoImage( self.img3.resize((755, int(h * 755 / w)), IM.ANTIALIAS)) else: self.photo3 = ITk.PhotoImage( self.img3.resize((int(w * 425 / h), 425), IM.ANTIALIAS)) self.canvas_result.create_image(380, 220, image=self.photo3)
def random_image(sourceimg=None, size=(200, 100)): """Scramble source image to create placeholder image""" if sourceimg is None: sourceimg = Image.open(str(SOURCE_IMG)) width, height = size sqrt2 = 2**.5 regionsize = int(min( max(width, height) * sqrt2, min(sourceimg.size), )) inscribed = int(regionsize / sqrt2) x = random.randint(0, sourceimg.width - regionsize) y = random.randint(0, sourceimg.height - regionsize) subsection = sourceimg.crop([x, y, x + regionsize, y + regionsize]) angle = random.randint(0, 360) rotated = subsection.rotate(angle) ratio = width / height if ratio > 1: cw, ch = inscribed, inscribed / ratio else: cw, ch = inscribed * ratio, inscribed cropbox = ( (regionsize - cw) / 2, (regionsize - ch) / 2, (regionsize + cw) / 2, (regionsize + ch) / 2, ) cropped = rotated.crop(cropbox) blur = ImageFilter.GaussianBlur(1) result = cropped.resize((width, height)) enhanced = result.filter(blur) enhanced = random_bands(enhanced) blended = ImageChops.blend(result, enhanced, 0.5) blended = ImageChops.blend(blended, ImageOps.equalize(blended), 0.5) blended = blended.filter(blur) return blended
def process_ghost(num): """Blend each frame with a previous one.""" input_file = "img/frames/me{0:03d}.png" output_file = "img/frames/me_processed{0:03d}.png" for i in range(1, num + 1): filename = input_file.format(i) im = Image.open(filename) im = im.convert("L") if i > 1 and i <= num + 1: prev = Image.open(input_file.format(i - 1)).convert("L") im = ImageChops.blend(im, prev, 0.5) output = output_file.format(i) im.save(output)
def blend(img1, img2): switch = random.randint(1, 4) if switch == 1: print('screen') return ImageChops.screen(img1, img2) if switch == 2: print('difference') return ImageChops.difference(img1, img2) if switch == 3: print('darker') return ImageChops.darker(img1, img2) if switch == 4: print('multiply') return ImageChops.multiply(img1, img2) if switch == 5: print('blend') return ImageChops.blend(img1, img2, .5)
def handle_photo(photo_path, method, frame_count=None, full_path=False): paths = ['{}/{}'.format(photo_path, file_path) for file_path in os.listdir(photo_path)] files = ['{}/{}'.format(p, f) for p in ifil(os.path.isdir, paths) for f in os.listdir(p)] files = list(ch(files, list(ifil(os.path.isfile, paths)))) finalimage = None result_name = '{count}'.format(count=frame_count) if frame_count else '' for i, file_path in enumerate(files): what = imghdr.what(file_path) if what in [None, 'gif']: files.pop(i) continue currentimage = Image.open(file_path) if what in ['png']: try: bg = Image.new("RGB", currentimage.size, (255, 255, 255)) bg.paste(currentimage, mask=currentimage) currentimage = bg except ValueError: pass if finalimage is None: finalimage = currentimage continue if frame_count and i != 1 and i % frame_count: continue if method == 'both': lighter = handle_photo(photo_path, 'lighter', frame_count, full_path=True) darker = handle_photo(photo_path, 'darker', frame_count, full_path=True) l_img = Image.open(lighter) d_img = Image.open(darker) res = ImageChops.blend(l_img, d_img, 0.5) path, name = save_result(res, photo_path, result_name, method) return name if method == 'diff': if i < 1: continue prev = Image.open(files[i - 1]) diff = ImageChops.difference(currentimage, prev) finalimage = ImageChops.add(finalimage, diff) if method == 'lighter': finalimage = ImageChops.lighter(finalimage, currentimage) if method == 'darker': finalimage = ImageChops.darker(finalimage, currentimage) path, name = save_result(finalimage, photo_path, result_name, method) return path if full_path else name
def deep_dream_vgg(image, layer, iterations, lr, octave_scale, num_octaves): if num_octaves < 0: image_1 = image.filter(ImageFilter.GaussianBlur(2)) if (image_1.size[0] / octave_scale < 1) or (image_1.size[1] / octave_scale < 1): size = image_1.size else: size = (int(image_1.size[0] / octave_scale), int(image_1.size[1] / octave_scale)) image_1 = image_1.resize(size.Image.ANTIALIAS) image_1 = deep_dream_vgg((image_1, layer, iterations, lr, octave_scale, num_octaves - 1)) size = image.size image_1 = image_1.resize(size, Image.ANTIALIAS) image = ImageChops.blend(image, image_1, .6) return dreamify(image, layer, iterations, lr).resize(image.size)
def diff_images(self, one, two, different): """ one: 第一张图片的名称 two: 第二张图片的名称 different: 生成对比图保存名称 """ img_one = self.file_path + '/new_images/' + one + 'png' img_two = self.file_path + '/old_image/' + two + 'png' img_diff = self.file_path + '/diff_image/' + different + 'png' image_one = Image.open(img_one) image_two = Image.open(img_two) one_data = list(image_one.getdata()) two_data = list(image_two.getdata()) if one_data == two_data: pass elif one_data != two_data: diff = ImageChops.blend(image_one, image_two, alpha=0.5) diff.save(img_diff)
subjects = ['Sketch', 'Painting', 'Watercolor', 'Modern', 'Impressionism', 'Abstract', 'Surreal', 'Art', 'Sculpture', 'Drawing'] while (1): random.shuffle(subjects); for i in range(0, 2): subject = subjects[i] l = StdOutListener(i) stream = Stream(auth, l) print 'Streaming ' + subject stream.filter(track=[subject]) time.sleep(10) try: img1 = Image.open('img0.jpg') img2 = Image.open('img1.jpg') img1 = img1.resize((1024, 512)) img2 = img2.resize((1024, 512)) if (random.random() < 0.1): img2 = img2.rotate(180) # out = ImageChops.blend(img1, img2, 0.5) out = ImageChops.blend(img1, img2, 0.5) out.save('out.jpg') api.update_with_media('out.jpg', "Voila, my new painting is complete! I call it " + subjects[0] + "-" + subjects[ 1] + "!" + " #" + subjects[0] + " #" + subjects[1]); time.sleep(60 * 5); except Exception as e: print e
# <codecell> imgLower = ImageChops.constant(imgAgain, 2) # <codecell> imgOver = ImageEnhance.Brightness(imgLower) # <codecell> imgTitle = Image.open(chdirz) # <codecell> imgComt = ImageChops.blend(imgTitle, enzSapz, .5) # <codecell> imgConvertz = ImageEnhance.Color(imgComt) # <codecell> img3 = ImageChops.screen(imgComt, img2) # <codecell> bighImg = ImageChops.darker(img2, imgComt) # <codecell>
def transformInner(self, imgs): return ImageChops.blend(imgs[0], imgs[1], self.args["alpha"])
import shlex from PIL import Image, ImageChops from vm_input import get_params from cache import retrieve (fn, fmash, frate, rate, time, length, mashstyle, finalname) = get_params () frames = rate * length + fmash command = ("ffmpeg -i %(file)s -ss %(time)s -vframes %(frames)d -r %(rate)s pic%%05d.png"%({"file": fn, "time": time,"frames": frames ,"rate": frate})) command2 = ("ffmpeg -r %d -i img%%05d.png %s" %(rate, finalname)) subprocess.call (shlex.split (command)) #Mash those frames and save em sequentially.... fns = [ImageChops.difference, \ ImageChops.screen, \ lambda x, y: ImageChops.blend (x, ImageChops.invert (y), .5), \ lambda x, y: ImageChops.blend (x, y, .5)] names = ["pic" + str (x).zfill (5) + ".png" for x in range (1, frames + 1)] f_names = ["img" + str (x).zfill (5) + ".png" for x in range (0, frames)] for x in range (0, frames): reduce (fns[mashstyle], map (retrieve, names [x : x + fmash])).save (f_names[x]) #call video maker! subprocess.call(shlex.split(command2)) #delete pics/manipuated images for name in names + f_names: subprocess.call (['rm', name])
def normalizeImage( self, image ): image = image.filter( ImageFilter.BLUR ) picture = ImageChops.blend( ImageOps.equalize( image ), image, .5 ) return ImageChops.multiply( picture, picture )
from PIL import Image, ImageDraw, ImageChops carrot = Image.open('carrot.png') brain = Image.open('brain.png') carrot = carrot.resize((250, 250)) arrow = Image.new('RGBA', (250, 250), "white") draw = ImageDraw.Draw(arrow) draw.rectangle((0, 50, 100, 100), fill="black") draw.polygon((100, 25, 100, 125, 150, 75), fill="black") gradient = Image.new('RGBA', (250, 250), "white") draw = ImageDraw.Draw(gradient) for x in range(250): box = (x, 0, x+1, 250) color = (255, (255-x), 0) draw.rectangle(box, fill=color) f1 = ImageChops.multiply(brain, carrot) f1.save('filter1.png') f2 = ImageChops.blend(brain, carrot, 0.2) f2.save('filter2.png') f3 = ImageChops.screen(carrot, gradient) f3.save('filter3.png')
iimg9swap = iimg8.rotate(180) # <codecell> # <codecell> # <codecell> iimg5 = ImageChops.darker(iimg5, iimg3) # <codecell> img6 = ImageChops.blend(iimg5, iimg, .5) # <codecell> # <codecell> # <codecell> iimgz7 = ImageChops.darker(iimg5, iimg9swap) # <codecell> # <codecell>
def render(self, device): return ImageChops.blend(self.p1.render(device), self.p2.render(device), self.params['100Weight'] / 100.0)
print("(That's with multiplier {})".format(args.alpha)) for i in images: j = Image.open(i) if not img: mode = j.mode size = j.size img = Image.open(i) print("\nUSING SETTINGS") print("IMAGE MODE: {}".format(mode)) print("IMAGE SIZE: X {}, Y {}\n".format(*size)) else: j = Image.open(i) j = j.resize(size) j = j.convert(mode) img = ImageChops.blend(img, j, alpha) for i in images[::-1]: j = Image.open(i) if not img: mode = j.mode size = j.size img = Image.open(i) print("\nUSING SETTINGS") print("IMAGE MODE: {}".format(mode)) print("IMAGE SIZE: X {}, Y {}\n".format(*size)) else: j = Image.open(i) j = j.resize(size) j = j.convert(mode) img = ImageChops.blend(img, j, alpha)