def changeImage(slice_num): global PreViewImage, PreviewName, stlfilename global image_tk PreviewName.set("Preview Images - "+stlfilename[:-4]+str(slice_num)+".png") OperationValue = OperationVar.get() imageBlank = Image.new("RGB", (768,480),0) image_im_m1 = imageBlank if (OperationValue == 1): imageFile = FileputPath+stlfilename[:-4]+str(int(slice_num)) +".png" try: image_im = Image.open(imageFile) except: print imageFile+" error" showinfo("Error:", imageFile+" Open Error!") #checkslice_ui.destroy() return if (OperationValue == 2): imageFile = FileputPath+stlfilename[:-4]+str(int(slice_num)) +".png" try: image_im = Image.open(imageFile) except: print imageFile+" error" showinfo("Error:", imageFile+" Open Error!") #checkslice_ui.destroy() return imageFilem1 = FileputPath+stlfilename[:-4]+str(int(slice_num)-1)+".png" try: image_im_m1 = Image.open(imageFilem1) except: image_im_m1 = imageBlank image_im = image_im.convert("L") image_im = ImageOps.colorize(image_im, (0,0,0), (255,0,0)) image_im = image_im.convert("RGB") image_im_m1 = image_im_m1.convert("L") image_im_m1 = ImageOps.colorize(image_im_m1, (0,0,0), (255,255,255)) image_im_m1 = image_im_m1.convert("RGB") try: image_im = Image.blend(image_im, image_im_m1, 0.3) except: null() image_im_enhance = ImageEnhance.Brightness(image_im) image_im = image_im_enhance.enhance(2.0) image_tk = ImageTk.PhotoImage(image_im) PreViewImage.configure(image = image_tk) return
def color_tiles(img): size = img.size small_img = img.resize((int(size[0]/2), int(size[1]/2)), BILINEAR) bw_img = small_img.convert('1', dither=False) gray_img = bw_img.convert('L') result = Image.new('RGB', size) tile1 = ImageOps.colorize(gray_img, 'green', 'red') tile2 = ImageOps.colorize(gray_img, 'purple', 'yellow') tile3 = ImageOps.colorize(gray_img, 'yellow', 'brown') tile4 = ImageOps.colorize(gray_img, 'red', 'cyan') result.paste(tile1, (0, 0)) result.paste(tile2, (int(size[0]/2), 0)) result.paste(tile3, (0, int(size[1]/2))) result.paste(tile4, (int(size[0]/2), int(size[1]/2))) return result
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 __call__(self): portal_skins = getToolByName(self.context, 'portal_skins') if not hasattr(self, 'filename'): self.filename = self.request.img if not hasattr(self, 'color'): self.color = self.request.color color = self.color img = portal_skins.restrictedTraverse(self.filename) img_data = getattr(img, '_data', False) or getattr(img, 'data', False) image = Image.open(StringIO(img_data)) alpha = None if image.mode == 'RGBA': alpha = image.split()[3] elif image.mode == 'P' and image.format == 'PNG': # PNG images can have transparency and be palette-based. # This is probably not the most clever method but it works alpha = image.convert('RGBA').split()[3] r, g, b = getrgb(color) if image.mode != 'L': grayscale_image = image.convert('L') else: grayscale_image = image newimage = ImageOps.colorize(grayscale_image, (r, g, b), (255, 255, 255)) output = StringIO() if alpha: newimage.putalpha(alpha) newimage.save(output, format='PNG') self.request.response.setHeader('Content-Type', 'image/png') return output.getvalue()
def tint_image(img: Image, color): """ Tint an image a certain colour and then blur it slightly. :param img: A PIL.Image instance :param color: Either a hex string or an RGB tuple. :return: A tinted and slightly blurred image. """ # Get the alpha channel of the image alpha = img.split()[-1] # Convert Image to greyscale gray_scale = ImageOps.grayscale(img) # Fix reduced contrast on Image gray_scale = ImageOps.autocontrast(gray_scale) # Tint the greyscale image tinted = ImageOps.colorize(gray_scale, (0, 0, 0, 0), color) # raise brightness of image tinted = ImageEnhance.Brightness(tinted).enhance(1.5) # Return alpha channel tinted.putalpha(alpha) return tinted
def tint_image(src: Image, color: tuple=(255, 255, 255)): src.load() r, g, b, alpha = src.split() gray = ImageOps.grayscale(src) result = ImageOps.colorize(gray, (0, 0, 0, 0), color) result.putalpha(alpha) return result
def tats(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 9) colours = util.order_colours_by_brightness(colours) bg = random.choice(colours[:3]) light = random.choice(colours[3:6]) dark = random.choice(colours[6:]) dist = math.sqrt( sum(map(lambda t: math.pow(t[0] - t[1], 2), zip(light, dark)))) if dist < 100: light = util.modify_hls(light, l=lambda l: l + 100) light = util.modify_hls(light, s=lambda s: s + 100) dark = util.modify_hls(dark, s=lambda s: s + 100) layer = Image.open( os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/tats.png') layer.load() r, g, b, a = layer.split() layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, tuple(dark), tuple(light)) layer.putalpha(a) im = Image.new('RGB', layer.size, tuple(bg)) im.paste(layer, mask=layer) return im
def random_texture(): files = list(iglob('resources/textures/*.png')) file = files[np.random.randint(0, len(files))] texture = Image.open(file).convert('L') texture = ImageOps.colorize(texture, 'black', (np.random.randint( 50, 256), np.random.randint(50, 256), np.random.randint(50, 256))) return texture
def make_image(args, string, font=None): '''creates an artificial image from a string as generated by make_string and the parameters defined in args.''' if font is None: font = args.font fnt = ImageFont.truetype(font, args.font_size) img = Image.new(args.colorspace, args.shape, color='white') text = Image.new('L', args.text_box) angle = np.random.uniform(-args.max_angle, args.max_angle) d = ImageDraw.Draw(text) d.text((0, 0), string, font=fnt, fill=255) text = text.rotate(angle, expand=True) text = ImageOps.colorize(text, black=(255, 255, 255), white=(0, 0, 0)) if args.pos is not None: x_pos = random.randint( 0, int(args.shape[0] - args.pos[0] * args.shape[0])) y_pos = random.randint( 0, int(args.shape[1] - args.pos[1] * args.shape[1])) else: x_pos = 0 y_pos = 0 img.paste(text, (x_pos, y_pos)) return img
def make_stamp(org_title: str, base_file: str, org_title_width: int, output=None) -> io.BytesIO: img = Image.open(base_file) org_title = org_title.upper() font_filename = "./static/fonts/Stamp.ttf" font_size = 35 font = ImageFont.truetype(font_filename, font_size) text_size = font.getsize(org_title) while text_size[0] > org_title_width: font_size -= 1 font = ImageFont.truetype(font_filename, font_size) text_size = font.getsize(org_title) img_txt = Image.new('L', text_size) d = ImageDraw.Draw(img_txt) d.text((0, 0), org_title, fill=255, font=font) w = img_txt.rotate(-4.6, expand=1) img.paste(ImageOps.colorize(w, (0, 0, 0), (61, 62, 140)), (int(img.size[0]/2-text_size[0]/2), int(img.size[1]/2-text_size[1]/2)), w) if output is None: output = io.BytesIO() img.save(output, format='PNG') return output
def get_combined_mask(self, alpha: int = 50, show_soma: bool = True) -> Image: prop_cycle = plt.rcParams['axes.prop_cycle'] colors = prop_cycle.by_key()['color'] combined_masks = Image.new('RGBA', size=(self.opto_specs.width, self.opto_specs.height)) for i_neuron in range(self.opto_specs.n_neurons): c_mask = Image.fromarray(self.masks_nyx[i_neuron, ...]) c_mask = ImageOps.colorize(c_mask.convert('L'), black='black', white=colors[i_neuron % len(colors)]) c_mask = c_mask.convert('RGBA') c_pixels = c_mask.load() for x in range(self.opto_specs.width): for y in range(self.opto_specs.height): if c_pixels[x, y] == (0, 0, 0, 255): c_pixels[x, y] = (0, 0, 0, 0) else: c_pixels[x, y] = c_pixels[x, y][:3] + (alpha, ) combined_masks.alpha_composite(c_mask) if show_soma: draw = ImageDraw.Draw(combined_masks) soma_center_rad = 2 for x_s, y_s in zip(self.xs_n, self.ys_n): draw.ellipse([(x_s - soma_center_rad, y_s - soma_center_rad), (x_s + soma_center_rad, y_s + soma_center_rad)], fill=(255, 0, 0)) return combined_masks
def recolor_iris(image: PILImage, iris_results: IrisResults, iris_color: Tuple[int, int, int]) -> PILImage: """Colorize an eye. Args: image (Image): PIL image instance containing a face. iris_results (IrisResults): Iris detection results. iris_color (tuple): Tuple of `(red, green, blue)` representing the new iris color to apply. Color values must be integers in the range [0, 255]. Returns: (Image) The function returns the modified PIL image instance. """ iris_location, iris_size = _get_iris_location(iris_results, image.size) # nothing fancy - just grab the iris part as an Image and work with that eye_image = image.transform(iris_size, Image.EXTENT, data=iris_location) eye_image = eye_image.convert(mode='L') eye_image = ImageOps.colorize(eye_image, 'black', 'white', mid=iris_color) # build a mask for copying back into the original image # no fancy anti-aliasing or blending, though mask = _get_iris_mask(iris_results, iris_location, iris_size, image.size) image.paste(eye_image, iris_location, mask) return image
def make_watermark(): canvas = make_canvas() image = Image.new('RGBA', size=canvas[0], color=canvas[1]) for one in make_text(): text_ = one[0] text_size = int(one[1]) / 100 font_family = one[2] angle = one[3] text_opacity = one[4] position = one[5] font_size = find_font_size(text_, font_family, image, text_size) font = ImageFont.truetype(font_family, font_size) text_layer = Image.new('L', canvas[0]) draw = ImageDraw.Draw(text_layer) draw.text(position, text_, font=font, fill=text_opacity) rotated_text_layer = text_layer.rotate(angle, expand=0) image.paste( ImageOps.colorize(rotated_text_layer, (0, 0, 0), (0, 0, 0)), (0, 0), rotated_text_layer) image.save('WaterMark.png') image.show()
async def deepfry(img: BinaryIO) -> BinaryIO: """Deepfry logic!""" colours = ( ((254, 0, 2), (255, 255, 15)), ((36, 113, 229), (255,) * 3), ) # Crush image to hell and back img = img.convert("RGB") width, height = img.width, img.height img = img.resize((int(width ** 0.75), int(height ** 0.75)), resample=Image.LANCZOS) img = img.resize((int(width ** 0.88), int(height ** 0.88)), resample=Image.BILINEAR) img = img.resize((int(width ** 0.9), int(height ** 0.9)), resample=Image.BICUBIC) img = img.resize((width, height), resample=Image.BICUBIC) # Generate colour overlay overlay = img.split()[0] overlay = ImageEnhance.Contrast(overlay).enhance(2.0) overlay = ImageEnhance.Color(overlay).enhance(1.75) overlay = ImageEnhance.Brightness(overlay).enhance(1.5) color = random.choice([colours[0], colours[1]]) overlay = ImageOps.colorize(overlay, color[0], color[1]) # Overlay red and yellow onto main image and sharpen the hell out of it img = Image.blend(img, overlay, 0.75) img = ImageEnhance.Sharpness(img).enhance(150) return img
def superimpose(a_path: Text, b_path: Text, out_path: Text): """Given two image paths, writes their superposition to out_path. Both images should be greyscale; they will be convered to red and blue respectively. Args: a_path: Path to one image. b_path: Path to another image. out_path: The path to which to write the new image. """ im1 = Image.open(a_path).convert("L") im2 = Image.open(b_path).convert("L") im1 = ImageOps.colorize(im1, black="red", white="white") im2 = ImageOps.colorize(im2, black="blue", white="white") ImageChops.darker(im1, im2).save(out_path)
async def deepfry(img: Image) -> Image: colours = ((50, 30, 40), (255, 240, 245)) img = img.copy().convert("RGB") # Crush image to hell and back img = img.convert("RGB") width, height = img.width, img.height img = img.resize((int(width**.85), int(height**.85)), resample=Image.LANCZOS) img = img.resize((int(width**.92), int(height**.92)), resample=Image.BILINEAR) img = img.resize((int(width**.97), int(height**.97)), resample=Image.BICUBIC) img = img.resize((width, height), resample=Image.BICUBIC) img = ImageOps.posterize(img, 7) # Generate colour overlay overlay = img.split()[0] overlay = ImageEnhance.Contrast(overlay).enhance(1.2) overlay = ImageEnhance.Brightness(overlay).enhance(1.0) overlay = ImageOps.colorize(overlay, colours[0], colours[1]) # Overlay red and yellow onto main image and sharpen the hell out of it img = Image.blend(img, overlay, 0.15) img = ImageEnhance.Sharpness(img).enhance(300) return img
def CreateHoverPng(self, nom, x, y, width, height, typeObject): # on précise les global nécéssaires -> c'est surtout des variables du .ini global HOVER_MASK, HOVER_MODE img = Image.open("./ui/Pictures/background.png") #bb = (int(x),int(y),int(width),int(height)) crop_rectangle = (int(x) - 1, int(y) - 1, int(x) - 1 + int(width) + 2, int(y) - 1 + int(height) + 2) cropped_im = img.crop(crop_rectangle) #.convert('RGBA') cropped_im.save("./ui/Pictures/" + nom + ".png") if HOVER_MODE == 'standard': poly = Image.new('RGBA', cropped_im.size) pdraw = ImageDraw.Draw(poly) bb = (0, 0, int(width), int(height)) if typeObject == "rect": pdraw.rectangle(bb, fill=HOVER_MASK) else: pdraw.ellipse(bb, fill=HOVER_MASK) #(255,255,255,84) cropped_im.paste(poly, mask=poly) cropped_im.save("./ui/Pictures/" + nom + "_hover.png") else: cropped_im = ImageOps.grayscale(cropped_im) cropped_im = ImageOps.colorize(cropped_im, black=HOVER_MASK, white="white") cropped_im.save("./ui/Pictures/" + nom + "_hover.png")
def get_text_image(it, dataset_size, hindi_vocab, background_images, Fonts, verbose): text = random.choice(hindi_vocab) back = random.choice(background_images) font = random.choice(Fonts) brightness = get_brightness(Image.open(back)) col, R, G, B, T = get_color(brightness) base = Image.open(back) font = ImageFont.truetype("Fonts/" + font, 30, layout_engine=ImageFont.LAYOUT_RAQM, encoding="unic") txt = Image.new('L', (font.getsize(text)[0], font.getsize(text)[1])) draw = ImageDraw.Draw(txt) draw.text((3, 0), text, font=font, fill=T) angle = random.randint(-4, 4) w = txt.rotate(angle, expand=1) base.paste(ImageOps.colorize(w, (0, 0, 0), (R, G, B)), (0, 0), w) im1 = base.crop((0, 0, w.size[0] + 3, w.size[1] + 3)) im1.save("Train/" + str(it) + ".jpg") f = open("Ground_truths.txt", "a+") f.write(str(it) + " " + text + "\n") f.close() if verbose: print("Actual progress:- ", (it + 1), " / ", dataset_size) return im1
def test_colorize_2color(): # Test the colorizing function with 2-color functionality # Open test image (256px by 10px, black to white) with Image.open("Tests/images/bw_gradient.png") as im: im = im.convert("L") # Create image with original 2-color functionality im_test = ImageOps.colorize(im, "red", "green") # Test output image (2-color) left = (0, 1) middle = (127, 1) right = (255, 1) assert_tuple_approx_equal( im_test.getpixel(left), (255, 0, 0), threshold=1, msg="black test pixel incorrect", ) assert_tuple_approx_equal( im_test.getpixel(middle), (127, 63, 0), threshold=1, msg="mid test pixel incorrect", ) assert_tuple_approx_equal( im_test.getpixel(right), (0, 127, 0), threshold=1, msg="white test pixel incorrect", )
def run(self): if self.test_mode: images = self._generate_image() color_images = [ ImageOps.colorize(image.convert('L'), black=color, white=(255, 255, 255)) for image, color in zip(images, COLOR_LIST) ] image = Image.composite(color_images[0], color_images[1], images[1]) image.save('test.png') else: update_interval = self.config.get('update_interval', 0) epaper = epd.EPD() while True: time_begin = time.time() log.info('generating image') images = self._generate_image() buf = [epaper.getbuffer(image) for image in images] log.info('updating e-paper') epaper.init() epaper.display(*buf) epaper.sleep() time_elapsed = time.time() - time_begin log.info('update done. elapsed: %f sec' % time_elapsed) if update_interval == -1: return if time_elapsed < update_interval: time.sleep(update_interval - time_elapsed)
def test_colorize_2color_offset(self): # Test the colorizing function with 2-color functionality and offset # Open test image (256px by 10px, black to white) im = Image.open("Tests/images/bw_gradient.png") im = im.convert("L") # Create image with original 2-color functionality with offsets im_test = ImageOps.colorize( im, black="red", white="green", blackpoint=50, whitepoint=100 ) # Test output image (2-color) with offsets left = (25, 1) middle = (75, 1) right = (125, 1) self.assert_tuple_approx_equal( im_test.getpixel(left), (255, 0, 0), threshold=1, msg="black test pixel incorrect", ) self.assert_tuple_approx_equal( im_test.getpixel(middle), (127, 63, 0), threshold=1, msg="mid test pixel incorrect", ) self.assert_tuple_approx_equal( im_test.getpixel(right), (0, 127, 0), threshold=1, msg="white test pixel incorrect", )
async def deepfry(img: Image) -> Image: colours = ((randint(50, 200), randint(40, 170), randint(40, 190)), (randint(190, 255), randint(170, 240), randint(180, 250))) img = img.copy().convert("RGB") # Resim formatı ayarla img = img.convert("RGB") width, height = img.width, img.height img = img.resize( (int(width**uniform(0.8, 0.9)), int(height**uniform(0.8, 0.9))), resample=Image.LANCZOS) img = img.resize( (int(width**uniform(0.85, 0.95)), int(height**uniform(0.85, 0.95))), resample=Image.BILINEAR) img = img.resize( (int(width**uniform(0.89, 0.98)), int(height**uniform(0.89, 0.98))), resample=Image.BICUBIC) img = img.resize((width, height), resample=Image.BICUBIC) img = ImageOps.posterize(img, randint(3, 7)) # Renk yerleşimi oluştur overlay = img.split()[0] overlay = ImageEnhance.Contrast(overlay).enhance(uniform(1.0, 2.0)) overlay = ImageEnhance.Brightness(overlay).enhance(uniform(1.0, 2.0)) overlay = ImageOps.colorize(overlay, colours[0], colours[1]) # Kırmızı ve sarıyı ana görüntüye yerleştir ve keskinleştir img = Image.blend(img, overlay, uniform(0.1, 0.4)) img = ImageEnhance.Sharpness(img).enhance(randint(5, 300)) return img
async def deepfry(img: Image) -> Image: colours = ((randint(50, 200), randint(40, 170), randint(40, 190)), (randint(190, 255), randint(170, 240), randint(180, 250))) # Crush image to hell and back width, height = img.width, img.height img = img.resize( (int(width**uniform(0.8, 0.9)), int(height**uniform(0.8, 0.9))), resample=Image.LANCZOS) img = img.resize( (int(width**uniform(0.85, 0.95)), int(height**uniform(0.85, 0.95))), resample=Image.BILINEAR) img = img.resize( (int(width**uniform(0.89, 0.98)), int(height**uniform(0.89, 0.98))), resample=Image.BICUBIC) img = img.resize((width, height), resample=Image.BICUBIC) img = ImageOps.posterize(img, randint(3, 7)) # Generate colour overlay overlay = img.split()[0] overlay = ImageEnhance.Contrast(overlay).enhance(uniform(1.0, 2.0)) overlay = ImageEnhance.Brightness(overlay).enhance(uniform(1.0, 2.0)) overlay = ImageOps.colorize(overlay, colours[0], colours[1]) # Blend random colors onto and sharpen the image img = Image.blend(img, overlay, uniform(0.1, 0.4)) img = ImageEnhance.Sharpness(img).enhance(randint(5, 300)) return img
async def deepfry(img): img = Image.open(img) colours = ((random.randint(50, 200), random.randint(40, 170), random.randint(40, 190)), (random.randint(190, 255), random.randint(170, 240), random.randint(180, 250))) img = img.convert("RGB") width, height = img.width, img.height img = img.resize((int(width**random.uniform( 0.8, 0.9)), int(height**random.uniform(0.8, 0.9))), resample=Image.LANCZOS) img = img.resize((int(width**random.uniform( 0.85, 0.95)), int(height**random.uniform(0.85, 0.95))), resample=Image.BILINEAR) img = img.resize((int(width**random.uniform( 0.89, 0.98)), int(height**random.uniform(0.89, 0.98))), resample=Image.BICUBIC) img = img.resize((width, height), resample=Image.BICUBIC) img = ImageOps.posterize(img, random.randint(3, 7)) overlay = img.split()[0] overlay = ImageEnhance.Contrast(overlay).enhance(random.uniform(1.0, 2.0)) overlay = ImageEnhance.Brightness(overlay).enhance(random.uniform( 1.0, 2.0)) overlay = ImageOps.colorize(overlay, colours[0], colours[1]) img = Image.blend(img, overlay, random.uniform(0.1, 0.4)) img = ImageEnhance.Sharpness(img).enhance(random.randint(5, 300)) image_name = "deepfried.jpeg" fried_file = os.path.join(Config.DOWN_PATH, image_name) img.save(fried_file, "JPEG") return fried_file
def tint_image(src, color="#FFFFFF"): src.load() r, g, b, alpha = src.split() gray = ImageOps.grayscale(src) result = ImageOps.colorize(gray, (0, 0, 0, 0), color) result.putalpha(alpha) return result
def draw_text(canvas, canvas_res, img_res, txtpos, entries): for i in range(len(entries)): pos, ori, text = resolve(entries[i]) if (ori == "h"): # horizontal text draw = ImageDraw.Draw(canvas) font = ImageFont.truetype(font_location, fontsize) draw.multiline_text(txtpos[i], text, font=font, fill='black') elif (ori == "v"): # vertical text (tx, ty), (tpx, tpy) = calc_text_pos_v(canvas_res, img_res, entries[i]) # Create text on transparent background and rotate. Resize for nicer text. img_res_scale = (img_res[1] * scale, img_res[1] * scale ) # square from y-side to get sensible rotation v_canvas = Image.new('L', img_res_scale) v_draw = ImageDraw.Draw(v_canvas) font = ImageFont.truetype(font_location, fontsize * scale) v_draw.multiline_text((tx * scale, ty * scale), text, font=font, fill='white') rotation_degrees = 90 v_canvas = v_canvas.rotate(rotation_degrees, expand=1) v_canvas = v_canvas.resize(img_res, Image.ANTIALIAS) colorization = ImageOps.colorize(v_canvas, (255, 255, 255), (0, 0, 0)) canvas.paste(colorization, (tpx, tpy), v_canvas)
def create_font_image(images, fonts, image_index, font_index, text='A', rotation=0, padding=12, output_size=64, color=(255, 0, 0)): assert image_index >= 0 and image_index < len(images) assert font_index >= 0 and font_index < len(fonts) img = images[image_index].copy() font = fonts[font_index] assert output_size < img.size[0] and output_size < img.size[1] txt = Image.new('L', (output_size, output_size)) txt_draw = ImageDraw.Draw(txt) w, h = txt_draw.textsize(text, font=font) txt_draw.text(((output_size - w) / 2, (output_size - h - padding) / 2), text, font=font, fill=255) rotated = txt.rotate(rotation) x = random.randrange(0, img.size[0] - output_size) y = random.randrange(0, img.size[1] - output_size) img = img.crop((x, y, x + output_size, y + output_size)) img.paste(ImageOps.colorize(rotated, (0, 0, 0), color), (0, 0), rotated) return img
def process(self, a: np.ndarray, *args) -> np.ndarray: out = None src_space = self.src_space if self.src_space == '': assert np.max(a) <= 1.0 a = np.around(a * 0xff).astype(np.uint8) src_space = 'L' src_space = 'L' for i in range(a.shape[Z]): img = Image.fromarray(a[i], mode=src_space) img = ImageOps.colorize( **{ 'image': img, 'black': self.black, 'white': self.white, 'blackpoint': 0x00, 'midpoint': 0x79, 'whitepoint': 0xff, }) img = img.convert(self.dst_space) a_img = np.array(img, dtype=np.uint8) if out is None: out = np.zeros((a.shape[Z], *a_img.shape), dtype=np.uint8) out[i] = a_img return out
def print_small(msg,copy): img = Image.open('blank.png') #.new('RGBA', (135, 90), color = (255, 255, 0) qr_basewidth = 150 big_code = pyqrcode.create(str(msg), error='L', version=2) big_code.png('code.png', scale=12, module_color=[0, 0, 0, 128], background=[0xff, 0xff, 0xff, 0xff]) qr_img = Image.open('code.png','r') qr_img = qr_img.convert("RGBA") qr_wpercent = (qr_basewidth/float(qr_img.size[0])) qr_hsize = int((float(qr_img.size[1])*float(qr_wpercent))) qr_img = qr_img.resize((qr_basewidth,qr_hsize), Image.ANTIALIAS) qr_img_w, qr_img_h = qr_img.size qr_img=qr_img.rotate(90,expand=1) img.paste(qr_img,(-14,575))#,qr_img_w,qr_img_h)) txt = Image.new('L',(500,500)) d = ImageDraw.Draw(txt) d.text( (0,0), msg, font=shield_fnt, fill=255) w=txt.rotate(90, expand=1) start = 75 img.paste( ImageOps.colorize(w, (0,0,0), (0,0,0)), (120,start+140), w) img_final = Image.open('blank.png') spacer = 245 for x in xrange(0,copy): cur_spacer = x*spacer*-1 print cur_spacer img_final.paste(img, (0,cur_spacer)) img_final.save('./gen/logo_gen.png') os.system('brother_ql_create --model QL-800 ./gen/logo_gen.png -r 90 > ./gen/'+str(msg)+'.bin') os.system('brother_ql_print ./gen/'+str(msg)+'.bin usb://0x4f9:0x209b')
def make_bb_images(path_to_bb="../nih_data/BBox_List_2017.csv", pathology="Effusion"): path_to_images = "../nih_data/images/" path_to_bb_images = "../nih_data/bb_images/" + pathology + "/" if not os.path.exists(path_to_bb_images): os.makedirs(path_to_bb_images) df = pd.read_csv(path_to_bb) df_pathology = df[df["Finding Label"] == pathology] pathology_indices = df_pathology["Image Index"].values count = 0 for pathology_index in pathology_indices: df_index = df[df["Image Index"].isin([pathology_index])] multiplicity = len(df_index) if multiplicity == 1: # pathology_unique_indices.append(pathology_index) image = Image.open(path_to_images + pathology_index).convert('L') image = ImageOps.colorize(image, black=[0, 0, 0], white=[255, 255, 255]) draw = ImageDraw.Draw(image) # print(df_index.iloc[:,[2,3,4,5]].values[0]) [x, y, w, h] = list(df_index.iloc[:, [2, 3, 4, 5]].values[0]) draw.rectangle([x, y, x + w, y + h], outline=(255, 255, 0)) image.save(path_to_bb_images + pathology_index) count += 1 return count
async def deepfry(img: Image) -> Image: colours = ( (randint(50, 200), randint(40, 170), randint(40, 190)), (randint(190, 255), randint(170, 240), randint(180, 250)), ) img = img.copy().convert("RGB") # Crush image to W2H and back img = img.convert("RGB") width, height = img.width, img.height img = img.resize( (int(width ** uniform(0.8, 0.9)), int(height ** uniform(0.8, 0.9))), resample=Image.LANCZOS, ) img = img.resize( (int(width ** uniform(0.85, 0.95)), int(height ** uniform(0.85, 0.95))), resample=Image.BILINEAR, ) img = img.resize( (int(width ** uniform(0.89, 0.98)), int(height ** uniform(0.89, 0.98))), resample=Image.BICUBIC, ) img = img.resize((width, height), resample=Image.BICUBIC) img = ImageOps.posterize(img, randint(3, 7)) # Generate colour overlay overlay = img.split()[0] overlay = ImageEnhance.Contrast(overlay).enhance(uniform(1.0, 2.0)) overlay = ImageEnhance.Brightness(overlay).enhance(uniform(1.0, 2.0)) overlay = ImageOps.colorize(overlay, colours[0], colours[1]) # Overlay red and yellow onto main image and sharpen the W2H out of it img = Image.blend(img, overlay, uniform(0.1, 0.4)) img = ImageEnhance.Sharpness(img).enhance(randint(5, 300)) return img
def floodfill_axons(axon_array, myelin_array): """ This function does a floodfill operation on the myelin_array. The seed points are the centroids of the axon objects in the axon_array. The goal is to fill the center of the myelin objects with the axon mask. Note: The myelin objects need to be closed in order to prevent the axon_mask from flooding the entire image. :param axon_array: the binary array corresponding to the axon mask :param myelin_array: the binary array corresponding to the myelin mask :return: the binary axon array corresponding to the axon mask after the floodfill """ # Get the centroid indexes centroid_index_map = get_centroids(axon_array) # Create an image with the myelinMask and floodfill at the coordinates of the centroids # Note: The floodfill algorithm only works on RGB images. Thus, the mask must be colorized before applying # the floodfill. Then, the array corresponding to the floodfilled color can be extracted. myelin_image = Image.fromarray(myelin_array * 255) myelin_image = ImageOps.colorize(myelin_image, (0, 0, 0, 255), (255, 255, 255, 255)) for i in range(len(centroid_index_map[0])): ImageDraw.floodfill( myelin_image, xy=(centroid_index_map[1][i], centroid_index_map[0][i]), value=(127, 127, 127, 255), ) # Extract the axon_mask overlay axon_extracted_array = np.array(myelin_image.convert("LA")) axon_extracted_array = axon_extracted_array[:, :, 0] axon_extracted_array = np.equal(axon_extracted_array, 127 * np.ones_like(axon_extracted_array)) axon_extracted_array = axon_extracted_array.astype(np.uint8) return axon_extracted_array
def import_viirs(self): """Import a VIIRS DNB file.""" # Allows user to search through his directory for VIIRS Image file. file_types = [('TIFF Files', '*.tif'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.file_log_var.set(file_name) # Checks to see if file is empty. If not, displays image on canvas. if file_name != '': pilimg = Image.open(file_name) pilimg_width, pilimg_height = pilimg.size pilimg.tile = [ t for t in pilimg.tile if t[1][2] < pilimg_width and t[1][3] < pilimg_height ] canvas_size = (self.img_canvas.winfo_width(), self.img_canvas.winfo_height()) pilimg_r = pilimg.resize(canvas_size, Image.ANTIALIAS) pilimg_col = ImageOps.colorize(ImageOps.grayscale(pilimg_r), (0, 0, 0), (255, 255, 255)) pilimg_cont = ImageOps.autocontrast(pilimg_col, cutoff=.4, ignore=None) self.img = ImageTk.PhotoImage(pilimg_cont) self.img_canvas.create_image(canvas_size[0] / 2, canvas_size[1] / 2, image=self.img) else: print('File is empty.')
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"))