我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用PIL.Image.alpha_composite()。
def save_text_and_map_on_whitebg(self, map): # if no map or nothing changed if map is None or (map == self.previous_map_no_text and self.previous_display_text == self.display_text): return self.map_no_text = map self.previous_map_no_text = self.map_no_text self.previous_display_text = self.display_text self.map_no_text.save(self.mapPath + '/' + self.roombaName + 'map_notext.png', "PNG") final = Image.new('RGBA', self.base.size, (255,255,255,255)) # white # paste onto a white background, so it's easy to see final = Image.alpha_composite(final, map) # draw text self.draw_text(final, self.display_text, self.fnt) final.save(self.mapPath + '/'+self.roombaName + '_map.png', "PNG") # try to avoid other programs reading file while writing it, # rename should be atomic. os.rename(self.mapPath + '/' + self.roombaName + '_map.png', self.mapPath + '/' + self.roombaName + 'map.png')
def _add_label(img: Image, texts: list, colour: str): """ Adds a label with text to an image. :param img: Image to add label to. """ label = _create_label(100, 25, texts, colour, '#000000') img = img.convert('RGBA') temp_canvas = Image.new('RGBA', img.size) img_width, img_height = img.size label_width, label_height = label.size label_x = int((0.5 * img_width) - (0.5 * label_width)) # Center vertically label_y = img_height - label_height temp_canvas.paste(label, (label_x, label_y)) return Image.alpha_composite(img, temp_canvas)
def main(): images_dir = '/Users/alan/Documents/research/nips2017/dcgan_w_results' font_size = 30 images = [] font = ImageFont.truetype('/Library/Fonts/Arial.ttf', font_size) for file_name in sorted(os.listdir(images_dir)): if os.path.splitext(file_name)[-1] != '.png' or file_name == 'real_samples.png': continue image = Image.open(os.path.join(images_dir, file_name)).convert('RGBA') text = 'Epoch '+str(int(file_name.split('_')[-1].split('.')[0])) layer = Image.new('RGBA', image.size, (255, 255, 255, 0)) draw = ImageDraw.Draw(layer) w, h = draw.textsize(text, font=font) draw.text(((image.size[0]-w)//2, (image.size[1]-h)//2), text, font=font, fill=(255, 255, 255, 180)) image = Image.alpha_composite(image, layer) images.append(image) images = np.stack(images) imageio.mimsave(os.path.join(images_dir, 'animation.gif'), images, duration=0.1)
def create_img_with_text(base_img, input_text, out_file=OUT_FILE): input_text = textwrap.fill(input_text, width=TEXT_WIDTH) if os.path.isfile(out_file): os.remove(out_file) base = Image.open(base_img).convert('RGBA') base = _resize(base) txt = Image.new('RGBA', base.size, OVERLAY_COLOR) draw_context = ImageDraw.Draw(txt) draw_context.text(TEXT_OFFSET, input_text, font=FONT, fill=TEXT_COLOR) out = Image.alpha_composite(base, txt) out.save(out_file) return out_file
def create_match_image(match): table_border = 10 table_image = await draw_match_table(match) image = Image.new('RGBA', (table_image.size[0] + (table_border * 2), table_image.size[1] + table_border + 64)) draw = ImageDraw.Draw(image) draw.rectangle([0, 0, image.size[0], image.size[1]], fill=background_color) draw.rectangle([0, 64, image.size[0], image.size[1]], fill=trim_color) image.paste(table_image, (table_border, 64)) title = TextCell(f"{'Radiant' if match['radiant_win'] else 'Dire'} Victory", font_size=48, color=("green" if match['radiant_win'] else "red")) title.render(draw, image, 64, 0, image.size[0] - 64, 64) team_icon = Image.open(radiant_icon if match['radiant_win'] else dire_icon).resize((64, 64)) temp_image = Image.new("RGBA", image.size) temp_image.paste(team_icon, (0, 0)) image = Image.alpha_composite(image, temp_image) fp = BytesIO() image.save(fp, format="PNG") fp.seek(0) return fp
def blend_at_intersection(self, images): pre_blend_images = [] for idx, image in enumerate(images): x_start, y_start = self.get_start_indices(idx) image_data = np.asarray(image) overlap_data = self.overlap_map[y_start:y_start + self.image_size, x_start:x_start + self.image_size] alpha_image = image_data.copy() alpha_image[:, :, 3] = image_data[:, :, 3] / overlap_data pre_blend_image = np.zeros(self.dest_image_size + (4,), dtype=np.uint8) pre_blend_image[y_start:y_start + self.image_size, x_start:x_start + self.image_size] = alpha_image pre_blend_images.append(Image.fromarray(pre_blend_image, 'RGBA')) dest_image = pre_blend_images[0] for blend_image in pre_blend_images[1:]: dest_image = Image.alpha_composite(dest_image, blend_image) return dest_image
def stitch_map(tiles, width, height, bbox, dpi): """ Merge tiles together into one image. Args: tiles (list of dict of file): tiles for each layer width (float): page width in mm height (height): page height in mm dpi (dpi): resolution in dots per inch Returns: PIL.Image: merged map. """ size = (int(width * dpi_to_dpmm(dpi)), int(height * dpi_to_dpmm(dpi))) background = Image.new('RGBA', size, (255, 255, 255)) for layer in tiles: layer_img = Image.new("RGBA", size) for (x, y), tile_path in layer.items(): tile = Image.open(tile_path) layer_img.paste(tile, ((x - bbox.min.x) * TILE_SIZE, (y - bbox.min.y) * TILE_SIZE)) background = Image.alpha_composite(background, layer_img) add_scales_bar(background, bbox) return background.convert("RGB")
def draw_text(img, text): """ Draws text on an image. """ text_layer = Image.new('RGBA', img.size, (255,255,255,0)) draw_layer = ImageDraw.Draw(text_layer) font = ImageFont.truetype('Arial.ttf', find_fitting_size(img.size, .70, text, 'Arial.ttf')) text_x, text_y = draw_layer.textsize(text, font=font) x0 = (text_layer.size[0]-text_x)/2 y0 = text_layer.size[1]-text_y x1 = x0 + text_x y1 = y0 + text_y text_padding = 10 border_padding_x = 10 border_padding_y = 10 draw_layer.rectangle([x0-border_padding_x, y0-border_padding_y, x1+border_padding_x, y1+border_padding_y], fill=(0,0,0,128)) draw_layer.text((x0, y0-text_padding), text, font=font, fill=(255,255,255,255)) return Image.alpha_composite(img, text_layer)
def _create_map_image(self): images = self._get_images() self._map_image = Image.new('RGBA', self._map_size) for img in images: if not isinstance(img, Image.Image): img = Image.open(BytesIO(img.content)).convert('RGBA') self._map_image = Image.alpha_composite(self._map_image, img)
def mesclarImagem(mascara): #mescla a respectiva mascara a identidade identidade = Image.open('identidade.jpg').resize(mascara.size).convert('RGBA') mescla = Image.alpha_composite(identidade, mascara) return binarize(mescla) #return mescla # para testes do OCR sem a binarização # criando de fato, nossa lista de imagens pre-processadas para o OCR tesseract
def _draw_image_with_alpha(self, image: PILImage.Image, image2: PILImage.Image): im2 = PILImage.new('RGBA', image.size, (0, 0, 0, 0)) im2.paste(image2, self.position) im2 = PILImage.alpha_composite(image, im2) image.paste(im2, (0, 0))
def transparent_paste(self, base_image, icon, position): ''' needed because PIL pasting of transparent imges gives weird results ''' image = Image.new('RGBA', self.base.size, self.transparent) image.paste(icon,position) base_image = Image.alpha_composite(base_image, image) return base_image
def create_tritone(image_path, colors, blur, bg_color, palette_name): colors_triplets = [string_to_rgb_triplet(color) if isinstance( color, str) else color for color in colors] color_list = list(permutations(colors_triplets)) im = imread(image_path, mode='L') im = np.asarray(im).copy() blur_px_per_mp = blur blur = im.size * blur_px_per_mp / (1000000) gaussian_filter(im, output=im, sigma=blur) threshold_matrix = sigmoid(im) base_name = os.path.splitext(os.path.basename(image_path))[0] if palette_name: background = make_gradient((im.shape[1], im.shape[0]), palette_name) else: background = Image.new( 'RGBA', (im.shape[1], im.shape[0]), make_tuple(bg_color)) # Create directory to store the images if not os.path.exists('tritonize'): os.makedirs('tritonize') for i, color_set in enumerate(color_list): im_color = color_select(threshold_matrix, color_set) imfile = toimage(im_color, mode='RGBA') merged = Image.alpha_composite(background, imfile) merged.save("tritonize/{}_{}.png".format(base_name, i + 1))
def get_image(self, nome_lista, descricao, nome): imgs = os.listdir("img") img_name = random.choice(imgs) im = Image.open(img_name) im = im.convert("RGBA") #color filter r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) col = Image.new('RGBA', im.size, (r,g,b,128)) im = Image.alpha_composite(im, col) #text box text_box_w = int(im.size[0] * 0.7) text_box_h = int(im.size[1] * 0.32) txt = Image.new('RGBA', (text_box_w, text_box_h), (255,255,255,169)) font = ImageFont.truetype("FreeMono.ttf", size=40) d = ImageDraw.Draw(txt) text_size = d.textsize(nome_lista + '\n' + descricao, font) text_start_w = int((text_box_w - text_size[0]) / 2) text_start_h = int((text_box_h - text_size[1]) / 2) d.multiline_text((text_start_w, text_start_h), nome_lista + '\n' + descricao, font=font, spacing=4, align='center' , fill=(0,0,0,255)) w = int((im.size[0] - text_box_w) / 2) h = int((im.size[1] - text_box_h) / 2) im.alpha_composite(txt, (w, h)) im.save("res/" + nome + ".png") return "res/" + nome + ".png"
def get_tile(char, fg_color, bg_color, opaque): ch_x = char % 0x10 ch_y = int(char / 0x10) tile_bg = Image.new("RGBA", (8, 14), color="#" + BG_COLORS[bg_color % 0x8]) tile_fg = FG_GRAPHICS[fg_color].crop((ch_x * 8, ch_y * 14, ch_x * 8 + 8, ch_y * 14 + 14)) result = Image.alpha_composite(tile_bg, tile_fg) if not opaque: result = Image.blend(tile_bg, result, 0.7) return result
def overlay(self, img, box=(0,0), mask=None, copy=False): """Paste an image respecting alpha channels (unlike Image.paste).""" if isinstance(box, BoundingBox): box = box.corners if img.mode.endswith('A'): if len(box) == 2: box = (box[0], box[1], min(self.width, box[0]+img.width), min(self.height, box[1]+img.height)) img = Image.alpha_composite(self.crop(box).to_rgba(), img.crop((0, 0, box[2]-box[0], box[3]-box[1]))) base = self.copy() if copy else self base.paste(img, box, mask) return base
def meme_text(text, serverid): with open("info.json", "r") as info_file: data = info_file.read() data = json.loads(data) meme = randint(0,(len(data["memes_text"]) -1)) image_name = data["memes_text"][meme]["image"] margin = data["memes_text"][meme]["size"]["left"] offset = data["memes_text"][meme]["size"]["up"] style = data["memes_text"][meme]["style"] print("Creating meme " + data["memes_text"][meme]["image"] + " for server " + serverid) if not os.path.isfile("images/" + image_name): print("Downloading new Images") file_download(data["memes_text"][meme]["image_url"], "images/", image_name) if not os.path.isfile("fonts/" + data["styles"][style]["font"]): print("Downloading new Font") file_download(data["styles"][style]["font_url"], "fonts/", data["styles"][style]["font"]) meme_font = ImageFont.truetype("fonts/" + data["styles"][style]["font"], data["styles"][style]["font_size"]) base = Image.open("images/" + image_name).convert('RGBA') width, height = base.size txt = Image.new('RGBA', base.size, (255,255,255,0)) d = ImageDraw.Draw(txt) dif = (data["memes_text"][meme]["size"]["right"] - data["memes_text"][meme]["size"]["left"]) wrap = textwrap.wrap(" ".join(text.split()), width=dif/data["styles"][style]["font_size"]) offset += (data["memes_text"][meme]["size"]["bottom"]-offset)/2-(meme_font.getsize(wrap[0])[1]*len(wrap)/2) if offset < data["memes_text"][meme]["size"]["up"]: offset = data["memes_text"][meme]["size"]["up"] for line in wrap: d.text((margin+(data["memes_text"][meme]["size"]["center"]-meme_font.getsize(line)[0])/2, offset), line, font=meme_font, fill=data["styles"][style]["font_color"]) offset += meme_font.getsize(text)[1] if offset > data["memes_text"][meme]["size"]["bottom"] - meme_font.getsize(line)[1]: break out = Image.alpha_composite(base, txt) out.save("server/" + serverid + "/output/" + image_name); print("Meme saved to: server/" + serverid + "/output/" + image_name) return "server/" + serverid + "/output/" + image_name
def add_text_overlay(image, text, font=_default_font): rgba_image = image.convert('RGBA') text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0)) image_draw = ImageDraw.Draw(text_overlay) text_size_x, text_size_y = image_draw.textsize(text, font=font) text_xy = ((rgba_image.size[0] / 2) - (text_size_x / 2), (rgba_image.size[1] / 2) - (text_size_y / 2)) image_draw.text(text_xy, text, font=font, fill=(255, 255, 255, 128)) image_with_text_overlay = Image.alpha_composite(rgba_image, text_overlay) return image_with_text_overlay
def optimize(img, query): if not isinstance(img, BytesIO): ext = query['format'] if 'format' in query else img.format.lower() # the return format try: quality = int(query['quality']) if 'quality' in query else None except ValueError as e: raise ITSTransformError("ITSTransform Error: " + str(e)) with tempfile.NamedTemporaryFile(dir="/tmp/", delete=True) as tmp_file: if ext.lower() == "jpg": ext = "jpeg" # convert first, then optimize if ext.lower() == "jpeg": # convert to JPG and/or compress # need to convert to RGB first, then can save in any format if img.format != "JPEG": if img.mode in ["RGBA", "LA"]: new_img = Image.new("RGBA", img.size) new_img = Image.alpha_composite(new_img, img) img = img.convert("RGB") img = optimize_jpg(img, tmp_file, quality) elif ext.lower(): # convert from PNG, JPG and WEBP to formats other than JPG img = convert(img, ext, tmp_file) # only optimize pngs if quality param is provided if img.format == "PNG" and quality is not None: img = optimize_png(img, tmp_file, quality) return img
def paste_image(image1, image2, x, y): temp_image = Image.new("RGBA", image1.size) temp_image.paste(image2, (x, y)) return Image.alpha_composite(image1, temp_image) # colors an image with one single color for all the pixes that are currently not transparent
def get(self): key = sha256(random().hex().encode('utf8')).hexdigest()[-self.length:] id = sha256(key.encode('utf8')).hexdigest() self.storage.update({id: key}) base = Image.new('RGBA', self.size, (255, 255, 255, 0)) text = Image.new('RGBA', self.size) draw = ImageDraw.Draw(text) while True: text_w, text_h = draw.textsize(key, font=self.font) base_w, base_h = base.size if text_h >= base_h or text_w >= base_w: self.font = ImageFont.truetype(self.font.path, self.font.size - 1) else: break draw.text(((base_w - text_w) / 2, (base_h - text_h) / 2), key, font=self.font, fill=self.color) text = self._transform(text) out = Image.alpha_composite(base, text) out = self._noise(out) # for debug # out.show() # print(key) f = BytesIO() out.save(f, 'PNG') raw = f.getvalue() return raw, id
def output_overlay(output=None, overlay=None): # Take an overlay Image overlay_img = _get_overlay_image(overlay) # ...and a captured photo output_img = Image.open(output).convert('RGBA') # Combine the two and save the image as output new_output = Image.alpha_composite(output_img, overlay_img) new_output.save(output)
def create_sample(self): found_bboxes = [] images = [] dominating_colour = None for _ in range(self.numbers_per_image): house_number_crop, bbox, median_colour = self.get_number_crop() if len(images) > 0: while True: if is_close(median_colour, dominating_colour): break house_number_crop, bbox, median_colour = self.get_number_crop() else: dominating_colour = median_colour house_number_crop, bbox = self.adjust_house_number_crop(house_number_crop, bbox) paste_bbox = self.find_paste_location(bbox, found_bboxes) found_bboxes.append(paste_bbox) images.append(house_number_crop) base_image = self.create_base_image(tuple(dominating_colour)) for image, bbox in zip(images, found_bboxes): base_image_data = np.asarray(base_image, dtype=np.uint8).copy() image_array = np.asarray(image, dtype=np.uint8) image_holder = np.zeros_like(base_image_data, dtype=np.uint8) image_holder[bbox.top:bbox.top + bbox.height, bbox.left:bbox.left + bbox.width, :] = image_array[:] image = Image.fromarray(image_holder, mode='RGBA') base_image_data[bbox.top:bbox.top + bbox.height, bbox.left:bbox.left + bbox.width, 3] = 255 - image_array[..., 3] base_image = Image.fromarray(base_image_data, mode='RGBA') base_image = Image.alpha_composite(base_image, image) return base_image, found_bboxes
def draw_text_on(image, resources_path, text): """ Args: image (Image): Image to draw on. text (str): String to draw. Returns: Image: Image with string drawn at a random location and rotation. """ width, height = image.size font_size = width // 15 font = ImageFont.truetype(resources_path + "/comic_sans_font.ttf", font_size) text_base = Image.new('RGBA', image.size, (255, 255, 255, 0)) # Base transparent image to write text on drawer = ImageDraw.Draw(text_base) max_x = max([width - (len(text)*font_size), 10]) max_y = max([height - font_size, 10]) x, y = random.randint(0, max_x), random.randint(0, max_y) angle = random.uniform(-10, 10) # 1/4 chance to print text in red instead of white if random.random() < 0.25: drawer.text((x, y), text, (255, 0, 0), font=font) else: drawer.text((x, y), text, (255, 255, 255), font=font) rotated_text = text_base.rotate(angle) result = Image.alpha_composite(image.convert('RGBA'), rotated_text) return result
def draw_all(self, triangles): img_a = Image.new('RGBA', size=(256, 256)) draw_a = ImageDraw.Draw(img_a) draw_a.polygon([(0, 0), (0, 255), (255, 255), (255 ,0)], fill=(255, 255, 255, 255)) for single in triangles: img_a = Image.alpha_composite(img_a, self.draw_single(single)) pixels = [img_a.getpixel((x, y)) for x in range(0, 256) \ for y in range(0, 256)] #img_a.save('triangle.jpg', 'jpeg') return pixels
def save(self, path): # Check arguments path = exception.arg_check(path, str) # Draw image if it hasn't been if self._workingImage is None: self.draw() # Resize background image. # Get scale of actual image to background image. bgScale = float(self._height)/float(self._background.height) # Calculate width assuming resizing background image height to actual # image height. bgWidth = int(math.ceil(bgScale*self._background.width)) # Calculate number of times background image is requred to tile to fit # width. bgTile = int(math.ceil(float(self._width)/float(bgWidth))) # Resize background image to match actual image height. bgResize = self._background.resize((bgWidth,self._height), pilimage.LANCZOS) # Create image to save saveImage = pilimage.new('RGBA', (self._width, self._height)) # Paste background for tile in xrange(bgTile): saveImage.paste(bgResize, box=((tile)*bgWidth,0), mask=bgResize) # Paste working image saveImage = pilimage.alpha_composite(saveImage, self._workingImage) # Resize/scale down with antialiasing to smooth jagged lines saveImage = saveImage.resize((self._width/_SECTOR_IMAGE_SCALE, self._height/_SECTOR_IMAGE_SCALE), pilimage.LANCZOS) # Save image saveImage.save(path) ## Orbit map image class. # # The orbit map image class is used to create images of orbit maps.
def test(): test_dir = "test" images, classes = next(iter(test_loader)) input.data.resize_(images.size()).copy_(images) output = counter(input) num_test = images.size(0) for i in range(num_test): count = int(round(output[i].data[0])) image = images[i].cpu().numpy() image = np.swapaxes(image, 0, 1) image = np.swapaxes(image, 1, 2) ones = np.ones([image.shape[0], image.shape[1], 1]) image = np.concatenate((image, image, image, ones), axis=2) fnt = ImageFont.truetype("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-B.ttf", 14) base = Image.fromarray(np.uint8(image * 255.0)) txt = Image.new("RGBA", base.size, (0, 0, 0, 0)) d = ImageDraw.Draw(txt) d.text((2,2), str(count), font=fnt, fill=(0, 255, 0, 200)) image = np.array(Image.alpha_composite(base, txt)) filename = test_dir + "/" + str(i).zfill(3) + "_" + str(count) + ".png" print(filename) scipy.misc.imsave(filename, image)
def create_img_with_text(base_img, input_text, out_file=OUT_FILE): base = Image.open(base_img).convert('RGBA') base = _resize(base) txt = Image.new('RGBA', base.size, OVERLAY_COLOR) draw_context = ImageDraw.Draw(txt) draw_context.text(TEXT_OFFSET, input_text, font=FONT, fill=TEXT_COLOR) out = Image.alpha_composite(base, txt) out.save(out_file) return out_file
def add_background(self, image, resize=False): img = Image.open(image).convert('RGBA') overlay = Image.new('RGBA', img.size, WHITE_TRANSPARENT_OVERLAY) bg_img = Image.alpha_composite(img, overlay) if resize: bg_size = (self.width * RESIZE_PERCENTAGE, self.height) bg_img.thumbnail(bg_size, Image.ANTIALIAS) left = self.width - bg_img.size[0] self.image.paste(bg_img, (left, 0)) else: self.image.paste(bg_img.resize(DEFAULT_CANVAS_SIZE, Image.ANTIALIAS), (0, 0))
def text(self, ctx, *, text): """Draws text on a background""" # check text length if len(text) > 24: await self.bot.say("Too big for me") else: result = Image.open(self.drawing_settings["userbar"][ctx.message.server.id]["background"]).convert('RGBA') process = Image.new('RGBA', (400,100), (0,0,0)) # get a font fnt = ImageFont.truetype('data/drawing/font.ttf', 37) fnt_sm = ImageFont.truetype('data/drawing/font.ttf', 20) # get a drawing context d = ImageDraw.Draw(process) # get sign sign = self.drawing_settings["text"][ctx.message.server.id]["bot_sign"] if sign == "username": sign = ctx.message.author.name # calculate text position author_width = fnt_sm.getsize("— " + sign)[0] # draw text, half opacity d.rectangle([(0,0),(400,100)], fill=(0,0,0,160)) d.text((25,25), "«" + text + "»", font=fnt, fill=(255,255,255,255)) d.text((400 - author_width - 25, 65), "— " + sign, font=fnt_sm, fill=(255,255,255,128)) d.rectangle([(10,10),(390,90)], fill=None, outline=(200,200,200,128)) result = Image.alpha_composite(result, process) result.save('data/drawing/temp.png','PNG') await self.bot.send_file(ctx.message.channel, 'data/drawing/temp.png') os.remove('data/drawing/temp.png')
def overlay(src_image, overlay_image, pos_x, pos_y): # ?????????????? ol_height, ol_width = overlay_image.shape[:2] # OpenCV???????PIL??? # BGRA??RGBA??? src_image_RGBA = cv2.cvtColor(src_image, cv2.COLOR_BGR2RGB) overlay_image_RGBA = cv2.cvtColor(overlay_image, cv2.COLOR_BGRA2RGBA) #?PIL??? src_image_PIL=Image.fromarray(src_image_RGBA) overlay_image_PIL=Image.fromarray(overlay_image_RGBA) # ??????RGBA?????? src_image_PIL = src_image_PIL.convert('RGBA') overlay_image_PIL = overlay_image_PIL.convert('RGBA') # ???????????????? tmp = Image.new('RGBA', src_image_PIL.size, (255, 255,255, 0)) # ????????????? tmp.paste(overlay_image_PIL, (pos_x, pos_y), overlay_image_PIL) # ?????????????????? result = Image.alpha_composite(src_image_PIL, tmp) return cv2.cvtColor(np.asarray(result), cv2.COLOR_RGBA2BGRA) # ?????????????
def draw_picture(img_src): fap_path = os.path.join(os.path.dirname(__file__), "fap.png") # ?????????? ???????? response = requests.get(img_src) response.raise_for_status() image_bytes = io.BytesIO(response.content) # ????????? image = Image.open(image_bytes) fap_pic = Image.open(fap_path) if image.mode != 'RGBA': image = image.convert('RGBA') image_width, image_height = image.size fap_width, fap_height = fap_pic.size def find_coeffs(pa, pb): """ https://stackoverflow.com/questions/14177744/ ????? ????????? ????, ??? ??????? - ??????? """ matrix = [] for p1, p2 in zip(pa, pb): matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]]) matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]]) A = numpy.matrix(matrix, dtype=numpy.float) B = numpy.array(pb).reshape(8) res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B) return numpy.array(res).reshape(8) trans_coeff = find_coeffs( [(217,111),(412,115),(222,372),(403,371)], [(0,0), (image_width-1,0), (0,image_height-1), (image_width-1, image_height-1)]) resp_pic = image.transform(fap_pic.size, Image.PERSPECTIVE, trans_coeff, Image.BILINEAR) # ??????????? gesture ? image resp_bytes = io.BytesIO() Image.alpha_composite(resp_pic, fap_pic).save(resp_bytes, format='PNG') resp_bytes.seek(0) return resp_bytes
def draw_gesture(img_src): gesture_path = os.path.join(os.path.dirname(__file__), "gesture.png") # ?????????? ???????? response = requests.get(img_src) response.raise_for_status() image_bytes = io.BytesIO(response.content) # ????????? image = Image.open(image_bytes) gesture = Image.open(gesture_path) if image.mode != 'RGBA': image = image.convert('RGBA') if gesture.mode != 'RGBA': gesture = gesture.convert('RGBA') # ????????? ?????? gesture ??? image image_width, image_height = image.size gest_width, gest_height = gesture.size k = 2 / 3 if (image_width / image_height) < (gest_width / gest_height): new_width = k * image_width new_height = new_width / gest_width * gest_height else: new_height = k * image_height new_width = new_height / gest_height * gest_width gesture = gesture.resize((int(new_width), int(new_height))) gest_width, gest_height = gesture.size diff0 = image_width - gest_width diff1 = image_height - gest_height gesture = ImageOps.expand(gesture, border=(diff0, diff1, 0, 0), fill=0) # ??????????? gesture ? image gestured_image = io.BytesIO() Image.alpha_composite(image, gesture).save(gestured_image, format='PNG') # ???? ?????, ??? ??? ???????? ????????? gestured_image.seek(0) return gestured_image
def render(self, dt): """ Fonction qui assure le mix des map pour générer l'image final """ #self.mapFinal = Image.new('RGBA',(self._ctxGfx.nx * self._ctxGfx.rx, self._ctxGfx.ny * self._ctxGfx.ry), (0,0,0,255)) # Vérifie si le plateau de base a été généré if self.plateau is None: self.renderMap() # calcule la couche dynamique (basé sur l'état des effets) if self.renderFx(dt): self.mapLastFx = Image.alpha_composite(self.plateau,self.mapFx) self.mapFinal = self.mapLastFx.copy() #self.renderFx(dt) #self.mapFinal = Image.alpha_composite(self.plateau,self.mapFx) # Calcul l'éclairage if self._Map.IsShadowEnabled == True: self.renderShadow() self._ctxGfx.can.delete(self.tkPlateau) self.tkPlateau = ImageTk.PhotoImage(image=self.mapFinal, master=self._ctxGfx.can) if self.tkPlateauId is not None: self._ctxGfx.can.itemconfig(self.tkPlateauId , image=self.tkPlateau) else: self.tkPlateauId = self._ctxGfx.can.create_image(0, 0, anchor=Tk.NW, image=self.tkPlateau, state= Tk.NORMAL) #self._ctxGfx.can.delete(self.tkPlateauId) self._ctxGfx.can.tag_lower(self.tkPlateauId) # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %% Affichage des Persos %% # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Pour chaque perso for p in self._EntityList.ActivePlayerList: p.render(dt) # Pour chaque monstre for p in self._EntityList.ActiveMonsterList: p.render(dt)
def prank(message: discord.Message, phrase: Annotate.CleanContent="IT'S A"): """ Prank! """ phrase = phrase.upper() # Initialize the image and font image_text = Image.new("RGBA", image_base.size, (255, 255, 255, 0)) image_font = ImageFont.truetype(prank_path + "American Captain.ttf", 50) image_context = ImageDraw.Draw(image_text) # Set width and height and scale down when necessary width, height = image_context.textsize(phrase, image_font) font_size = 50 if width > image_width: scaled_font = None while width > image_width: scaled_font = ImageFont.truetype(prank_path + "American Captain.ttf", font_size) width, height = image_context.textsize(phrase, scaled_font) font_size -= 1 image_font = scaled_font # Set x and y coordinates for centered text x = (image_width - width) / 2 y = (image_height - height / 2) - image_height / 1.3 # Draw border shadow_offset = font_size // 25 image_context.text((x - shadow_offset, y), phrase, font=image_font, fill=(0, 0, 0, 255)) image_context.text((x + shadow_offset, y), phrase, font=image_font, fill=(0, 0, 0, 255)) image_context.text((x, y - shadow_offset), phrase, font=image_font, fill=(0, 0, 0, 255)) image_context.text((x, y + shadow_offset), phrase, font=image_font, fill=(0, 0, 0, 255)) # Draw text image_context.text((x, y), phrase, font=image_font, fill=(255, 255, 255, 255)) # Combine the base image with the font image image = Image.alpha_composite(image_base, image_text) # Upload the image buffer = BytesIO() image.save(buffer, "PNG") buffer.seek(0) await client.send_file(message.channel, buffer, filename="pranked.png")
def meme_image(image_name, memename, serverid): print("Creating " + memename + " meme using " + image_name + " for server " + serverid) with open("info.json", "r") as info_file: data = info_file.read() data = json.loads(data) if not os.path.isfile("images/" + data["memes_images"][memename]["image"]): print("Downloading new Images") file_download(data["memes_images"][memename]["image_url"], "images/", data["memes_images"][memename]["image"]) frame = Image.open("images/" + data["memes_images"][memename]["image"]).convert("RGBA") pic = Image.open("server/" + serverid + "/" + image_name).convert("RGBA") if data["memes_images"][memename]["background"] == True: box = data["memes_images"][memename]["box"] if pic.size[0] < pic.size[1]: scale = (box[2]/pic.size[0]) pic = pic.resize((box[2],int(pic.size[1]*scale)), PIL.Image.ANTIALIAS) if pic.size[1] < box[3] - box[1]: scale = (box[3]/pic.size[1]) pic = pic.resize(((int(pic.size[0]*scale),box[3])), PIL.Image.ANTIALIAS) else: scale = (box[3]/pic.size[1]) pic = pic.resize(((int(pic.size[0]*scale),box[3])), PIL.Image.ANTIALIAS) if pic.size[0] < box[2] - box[0]: scale = (box[2]/pic.size[0]) pic = pic.resize((box[2],int(pic.size[1]*scale)), PIL.Image.ANTIALIAS) center = [(pic.size[0]-box[2])/2, (pic.size[1]-box[3])/2] pic = pic.crop((center[0],center[1],center[0]+box[2],center[1]+box[3])) frame.paste(pic,(box[0],box[1])) background = Image.new('RGBA', frame.size, (data["memes_images"][memename]["backgrond_color"][0],data["memes_images"][memename]["backgrond_color"][1],data["memes_images"][memename]["backgrond_color"][2],data["memes_images"][memename]["backgrond_color"][3])) frame = Image.alpha_composite(background, frame) frame.save("server/" + serverid + "/output/"+ data["memes_images"][memename]["image"]); else: if pic.size[1] < frame.size[1]: scale = (frame.size[1]/pic.size[1]) pic = pic.resize(((int(pic.size[0]*scale),frame.size[1])), PIL.Image.ANTIALIAS) if pic.size[0] < frame.size[0]: scale = (frame.size[0]/pic.size[0]) pic = pic.resize((frame.size[0],int(pic.size[1]*scale)), PIL.Image.ANTIALIAS) if pic.size[1] < frame.size[1]: scale = (frame.size[1]/pic.size[1]) pic = pic.resize(((int(pic.size[0]*scale),frame.size[1])), PIL.Image.ANTIALIAS) if pic.size[0] < frame.size[0]: scale = (frame.size[0]/pic.size[0]) pic = pic.resize((frame.size[0],int(pic.size[1]*scale)), PIL.Image.ANTIALIAS) pic.paste(frame, (10, pic.size[1]-frame.size[1]-30),frame) background = Image.new('RGBA', pic.size, (data["memes_images"][memename]["backgrond_color"][0],data["memes_images"][memename]["backgrond_color"][1],data["memes_images"][memename]["backgrond_color"][2],data["memes_images"][memename]["backgrond_color"][3])) pic = Image.alpha_composite(background, pic) pic.save("server/" + serverid + "/output/"+ data["memes_images"][memename]["image"]); print(memename + " meme saved to: server/" + serverid + "/output/" + data["memes_images"][memename]["image"]) return("server/" + serverid + "/output/" + data["memes_images"][memename]["image"])
def apply_transform(img, overlay, overlay_position=None): *overlay_position, overlay = overlay if 'overlay' in NAMESPACES: loader = OverlayTransform.get_loader(NAMESPACES['overlay']['loader']) else: raise ConfigError("No Backend has been set up for overlays.") if overlay.lower() not in OVERLAYS: namespace, *filename = overlay.split('/') filename = Path("/".join(filename)) overlay_image = loader[0].load_image(namespace, filename) else: namespace, *filename = OVERLAYS[overlay.lower()].split('/') filename = Path("/".join(filename)) overlay_image = loader[0].load_image(namespace, filename) # placement of top left corner of overlay if len(overlay_position) == 0: overlay_position = OVERLAY_PLACEMENT try: x_coord = floor((int(overlay_position[0]) / 100) * img.width) y_coord = floor((int(overlay_position[1]) / 100) * img.height) except ValueError as e: raise ITSTransformError( "Invalid arguments supplied to Overlay Transform." + "Overlay takes overlay_image_pathxPXxPY, " + "where overlay_image_path is the path to the overlay image and " + "(PX, PY) are optional percentage parameters indicating where " + "the top left corner of the overlay should be placed." ) # Only the overlay has an alpha channel if(img.mode != "RGBA"): new_img = img.copy() else: # overlay and input img have alpha channels # make an image the size of the background with # RGBA mode and alpha composite new image with background # this maintains the alpha channel of the background new_img = Image.new("RGBA", img.size) new_img = Image.alpha_composite(new_img, img) new_img.paste(overlay_image, box=[x_coord, y_coord], mask=overlay_image) img = new_img return img
def generateAvatar(player, assets=None): if player['isMale'] == 'true': gender = 'male' else: gender = 'female' if assets is None: assets = loadAvatarAssets() base = assets['base'][gender] leg_colour = (int(player['pantsColor'][0]), int(player['pantsColor'][1]), int(player['pantsColor'][2])) legs = tintImage(assets['legs'][gender], leg_colour) hair = cropImg(assets['hair'], int(player['hair']), defaultSize=(16, 32*3), objectSize=(16, 32), resize=True, displacement=(0, 0)) hair_color = tuple(map(int, player['hairstyleColor'])) hair = tintImage(hair, hair_color) acc = cropImg(assets['accessories'], int(player['accessory']), defaultSize=(16, 16*2), objectSize=(16, 16), resize=True, displacement=(0, 1)) if int(player['accessory']) <= 5: acc = tintImage(acc, hair_color) shirt = cropImg(assets['shirts'], int(player['shirt']), defaultSize=(8, 8*4), objectSize=(8, 8), resize=True, displacement=(4, 14)) skin_x = int(player['skin']) % 24 * 1 skin_y = int(player['skin']) // 24 * 1 skin_color = assets['skin colors'].getpixel((skin_x, skin_y)) base = tintImage(base, skin_color) arms = tintImage(assets['arms'][gender], skin_color) body = base.load() eyeColor = tuple(map(int, player['newEyeColor'])) white = (255, 255, 255) if player['isMale'] == 'true': body[6, 10] = eyeColor body[9, 10] = eyeColor body[6, 11] = eyeColor body[9, 11] = eyeColor body[5, 10] = white body[10, 10] = white body[5, 11] = white body[10, 11] = white else: body[6, 11] = eyeColor body[9, 11] = eyeColor body[6, 12] = eyeColor body[9, 12] = eyeColor body[5, 11] = white body[10, 11] = white body[5, 12] = white body[10, 12] = white base = Image.alpha_composite(base, hair) base = Image.alpha_composite(base, arms) base = Image.alpha_composite(base, legs) base = Image.alpha_composite(base, shirt) base = Image.alpha_composite(base, acc) base = Image.alpha_composite(base, assets['boots'][gender]) return base
def interpolate_at_intersection(self, images): def interpolate_width(data): interpolation_start = data.shape[1] - num_interpolation_pixels for i in range(num_interpolation_pixels): data[:, interpolation_start + i, 3] *= (num_interpolation_pixels - i) / num_interpolation_pixels return data def interpolate_height(data): interpolation_start = data.shape[0] - num_interpolation_pixels for i in range(num_interpolation_pixels): data[interpolation_start + i, :, 3] *= (num_interpolation_pixels - i) / num_interpolation_pixels return data pre_blend_images = [] num_interpolation_pixels = int(self.image_size * self.interpolation_area) for y_idx in range(self.image_rows): for x_idx in range(self.image_columns): image_idx = y_idx * self.image_columns + x_idx image = images[image_idx] x_start, y_start = self.get_start_indices(y_idx, x_idx) image_data = np.asarray(image).copy().astype(np.float64) # create horizontal alpha mask if x_idx < self.image_columns - 1: image_data = interpolate_width(image_data) if x_idx > 0: image_data = np.fliplr(image_data) image_data = interpolate_width(image_data) image_data = np.fliplr(image_data) # create vertical alpha mask if y_idx < self.image_rows - 1: image_data = interpolate_height(image_data) if y_idx > 0: image_data = np.flipud(image_data) image_data = interpolate_height(image_data) image_data = np.flipud(image_data) pre_blend_image = np.zeros(self.dest_image_size + (4,), dtype=np.uint8) pre_blend_image[y_start:y_start + self.image_size, x_start:x_start + self.image_size] = image_data.astype(np.uint8) pre_blend_images.append(Image.fromarray(pre_blend_image, 'RGBA')) dest_image = pre_blend_images[0] for blend_image in pre_blend_images[1:]: dest_image = Image.alpha_composite(dest_image, blend_image) dest_image = dest_image.convert('RGB') return dest_image