Python PIL.Image.alpha_composite() Examples
The following are 30
code examples of PIL.Image.alpha_composite().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
PIL.Image
, or try the search function
.
Example #1
Source File: utils.py From retinanet-examples with BSD 3-Clause "New" or "Revised" License | 6 votes |
def show_detections(detections): 'Show image with drawn detections' for image, detections in detections.items(): im = Image.open(image).convert('RGBA') overlay = Image.new('RGBA', im.size, (255, 255, 255, 0)) draw = ImageDraw.Draw(overlay) detections.sort(key=lambda d: d['score']) for detection in detections: box = detection['bbox'] alpha = int(detection['score'] * 255) draw.rectangle(box, outline=(255, 255, 255, alpha)) draw.text((box[0] + 2, box[1]), '[{}]'.format(detection['class']), fill=(255, 255, 255, alpha)) draw.text((box[0] + 2, box[1] + 10), '{:.2}'.format(detection['score']), fill=(255, 255, 255, alpha)) im = Image.alpha_composite(im, overlay) im.show()
Example #2
Source File: gaimage.py From bdfz.courses with GNU General Public License v3.0 | 6 votes |
def calc_match_rate(self): if self.match_rate > 0: return self.match_rate self.match_rate = 0 self.img = Image.new('RGBA', self.size) draw = ImageDraw.Draw(self.img) draw.polygon([(0, 0), (0, 255), (255, 255), (255, 0)], fill=(255, 255, 255, 255)) for triangle in self.triangles: self.img = Image.alpha_composite(self.img, triangle.img_t or triangle.draw_it(self.size)) # 与下方代码功能相同,此版本便于理解但效率低 # pixels = [self.img.getpixel((x, y)) for x in range(0, self.size[0], 2) for y in range(0, self.size[1], 2)] # for i in range(0, min(len(pixels), len(self.target_pixels))): # delta_red = pixels[i][0] - self.target_pixels[i][0] # delta_green = pixels[i][1] - self.target_pixels[i][1] # delta_blue = pixels[i][2] - self.target_pixels[i][2] # self.match_rate += delta_red * delta_red + \ # delta_green * delta_green + \ # delta_blue * delta_blue arrs = [np.array(x) for x in list(self.img.split())] # 分解为RGBA四通道 for i in range(3): # 对RGB通道三个矩阵分别与目标图片相应通道作差取平方加和评估相似度 self.match_rate += np.sum(np.square(arrs[i] - self.target_pixels[i]))[0]
Example #3
Source File: roomba.py From Roomba980-Python with MIT License | 6 votes |
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')
Example #4
Source File: heatmap.py From heatmappy with MIT License | 6 votes |
def heatmap(self, width, height, points, base_path=None, base_img=None): """ :param points: sequence of tuples of (x, y), eg [(9, 20), (7, 3), (19, 12)] :return: If base_path of base_img provided, a heat map from the given points is overlayed on the image. Otherwise, the heat map alone is returned with a transparent background. """ heatmap = self.grey_heatmapper.heatmap(width, height, points) heatmap = self._colourised(heatmap) heatmap = _img_to_opacity(heatmap, self.opacity) if base_path: background = Image.open(base_path) return Image.alpha_composite(background.convert('RGBA'), heatmap) elif base_img is not None: return Image.alpha_composite(base_img.convert('RGBA'), heatmap) else: return heatmap
Example #5
Source File: create_svhn_dataset_4_images.py From see with GNU General Public License v3.0 | 6 votes |
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
Example #6
Source File: weather-and-light.py From enviroplus-python with MIT License | 6 votes |
def overlay_text(img, position, text, font, align_right=False, rectangle=False): draw = ImageDraw.Draw(img) w, h = font.getsize(text) if align_right: x, y = position x -= w position = (x, y) if rectangle: x += 1 y += 1 position = (x, y) border = 1 rect = (x - border, y, x + w, y + h + border) rect_img = Image.new('RGBA', (WIDTH, HEIGHT), color=(0, 0, 0, 0)) rect_draw = ImageDraw.Draw(rect_img) rect_draw.rectangle(rect, (255, 255, 255)) rect_draw.text(position, text, font=font, fill=(0, 0, 0, 0)) img = Image.alpha_composite(img, rect_img) else: draw.text(position, text, font=font, fill=(255, 255, 255)) return img
Example #7
Source File: drawdota.py From MangoByte with MIT License | 6 votes |
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=discord_color2) draw.rectangle([0, 64, image.size[0], image.size[1]], fill=discord_color1) 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
Example #8
Source File: roomba.py From Roomba980-Python with MIT License | 6 votes |
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") if( self.enableMapWithText ): 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) final = final.rotate(self.angle, expand=True) #(NW 12/4/2018 fixed bug causing distorted maps when rotation is not 0 - moved rotate to here) # 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')
Example #9
Source File: create_svhn_dataset_4_images.py From stn-ocr with GNU General Public License v3.0 | 6 votes |
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
Example #10
Source File: print.py From geos with BSD 3-Clause "New" or "Revised" License | 6 votes |
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")
Example #11
Source File: img_aux_processing.py From optimize-images with MIT License | 6 votes |
def remove_transparency(img: ImageType, bg_color=DEFAULT_BG_COLOR) -> ImageType: """Remove alpha transparency from PNG images Expects a PIL.Image object and returns an object of the same type with the changes applied. Special thanks to Yuji Tomita and Takahashi Shuuji (https://stackoverflow.com/a/33507138) """ if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info): orig_image = img.convert('RGBA') background = Image.new('RGBA', orig_image.size, bg_color) img = Image.alpha_composite(background, orig_image) return img.convert("RGB") else: return img
Example #12
Source File: viz_functional.py From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License | 6 votes |
def apply_colormap_on_image(org_im, activation, colormap_name): """ Apply heatmap on image Args: org_img (PIL img): Original image activation_map (numpy arr): Activation map (grayscale) 0-255 colormap_name (str): Name of the colormap """ # Get colormap color_map = mpl_color_map.get_cmap(colormap_name) no_trans_heatmap = color_map(activation) # Change alpha channel in colormap to make sure original image is displayed heatmap = copy.copy(no_trans_heatmap) heatmap[:, :, 3] = 0.4 heatmap = Image.fromarray((heatmap*255).astype(np.uint8)) no_trans_heatmap = Image.fromarray((no_trans_heatmap*255).astype(np.uint8)) # Apply heatmap on image heatmap_on_image = Image.new("RGBA", org_im.size) heatmap_on_image = Image.alpha_composite(heatmap_on_image, org_im.convert('RGBA')) heatmap_on_image = Image.alpha_composite(heatmap_on_image, heatmap) return no_trans_heatmap, heatmap_on_image
Example #13
Source File: misc_functions.py From pytorch-cnn-visualizations with MIT License | 6 votes |
def apply_colormap_on_image(org_im, activation, colormap_name): """ Apply heatmap on image Args: org_img (PIL img): Original image activation_map (numpy arr): Activation map (grayscale) 0-255 colormap_name (str): Name of the colormap """ # Get colormap color_map = mpl_color_map.get_cmap(colormap_name) no_trans_heatmap = color_map(activation) # Change alpha channel in colormap to make sure original image is displayed heatmap = copy.copy(no_trans_heatmap) heatmap[:, :, 3] = 0.4 heatmap = Image.fromarray((heatmap*255).astype(np.uint8)) no_trans_heatmap = Image.fromarray((no_trans_heatmap*255).astype(np.uint8)) # Apply heatmap on iamge heatmap_on_image = Image.new("RGBA", org_im.size) heatmap_on_image = Image.alpha_composite(heatmap_on_image, org_im.convert('RGBA')) heatmap_on_image = Image.alpha_composite(heatmap_on_image, heatmap) return no_trans_heatmap, heatmap_on_image
Example #14
Source File: roomba.py From Roomba980-Python with MIT License | 5 votes |
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
Example #15
Source File: roomba.py From Roomba980-Python with MIT License | 5 votes |
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
Example #16
Source File: bbox_plotter.py From see with GNU General Public License v3.0 | 5 votes |
def render_text(self, dest_image, text): label_image = Image.new(dest_image.mode, dest_image.size) # only keep ascii characters # labels = ''.join(filter(lambda x: len(x) == len(x.encode()), labels)) draw = ImageDraw.Draw(label_image) text_width, text_height = draw.textsize(text, font=self.font) draw.rectangle([dest_image.width - text_width - 1, 0, dest_image.width, text_height], fill=(255, 255, 255, 160)) draw.text((dest_image.width - text_width - 1, 0), text, fill='green', font=self.font) dest_image = Image.alpha_composite(dest_image, label_image) return dest_image
Example #17
Source File: bbox_plotter.py From kiss with GNU General Public License v3.0 | 5 votes |
def render_text(self, dest_image, source_image, text, i, bottom=False): label_image = Image.new(dest_image.mode, dest_image.size) draw = ImageDraw.Draw(label_image) paste_width = (i + 1) * source_image.width text_width, text_height = draw.textsize(text, self.font) insert_height = source_image.height - text_height - 1 if bottom else 0 draw.rectangle([paste_width - text_width - 1, insert_height, paste_width, insert_height + text_height], fill=(255, 255, 255, 160)) draw.text((paste_width - text_width - 1, insert_height), text, fill='green', font=self.font) dest_image = Image.alpha_composite(dest_image, label_image) return dest_image
Example #18
Source File: bbox_plotter.py From kiss with GNU General Public License v3.0 | 5 votes |
def render_objectness_scores(self, objectness_scores, dest_image, image, bottom=False): if len(objectness_scores) == 0: return dest_image if isinstance(objectness_scores, tuple) and self.plot_objectness_classification_result: objectness_scores = objectness_scores[1] objectness_scores = F.softmax(objectness_scores) objectness_classification = map(lambda x: "{:.2f}".format(float(x)), objectness_scores[:, 1].data) elif isinstance(objectness_scores, tuple) and not self.plot_objectness_classification_result: objectness_scores = objectness_scores[0] objectness_classification = map(lambda x: "{:.2f}".format(float(F.mean(x).data)), objectness_scores[:, 0].data) elif objectness_scores.shape[-1] == 2: objectness_scores = F.softmax(objectness_scores) objectness_classification = map(lambda x: "{:.2f}".format(float(x)), objectness_scores[:, 1].data) else: objectness_classification = map(lambda x: "{:.2f}".format(float(F.mean(x).data)), objectness_scores[:, 0].data) for i, char in enumerate(objectness_classification, start=1): label_image = Image.new(dest_image.mode, dest_image.size) draw = ImageDraw.Draw(label_image) paste_width = (i + 1) * image.width text_width, text_height = draw.textsize(char, self.font) insert_height = image.height - text_height - 1 if bottom else 0 draw.rectangle([paste_width - text_width - 1, insert_height, paste_width, insert_height + text_height], fill=(255, 255, 255, 160)) draw.text((paste_width - text_width - 1, insert_height), char, fill='green', font=self.font) dest_image = Image.alpha_composite(dest_image, label_image) return dest_image
Example #19
Source File: gaimage2.py From bdfz.courses with GNU General Public License v3.0 | 5 votes |
def calc_error_rate(self, target_pixels): # 将所有三角形合成 self.img = Image.new("RGBA", self.size, (255, 255, 255, 0)) for t in self.triangles: self.img = Image.alpha_composite(self.img, t.img_t or t.draw()) # 计算误差值 arrs = tuple(np.array(x) for x in self.img.split()) for i in range(3): self.error_rate += np.sum(np.square(arrs[i] - target_pixels[i])) # [0]
Example #20
Source File: pubgheatmap.py From pubgheatmap with MIT License | 5 votes |
def buildTimedHeatMap(pointsList, circlesCoords, redCoords, planePath, imgFile_path): mapimg = Image.open(imgFile_path).convert('RGBA') game_events_image = Image.new('RGBA', mapimg.size, (255,255,255,0)) draw = ImageDraw.Draw(game_events_image) if redCoords[1] > 0: draw.ellipse([redCoords[0][0] - redCoords[1], redCoords[0][1] - redCoords[1], redCoords[0][0] + redCoords[1], redCoords[0][1] + redCoords[1]], fill=(255, 0, 0, 50)) # draw line of plane moving if len(planePath) == 2 and planePath[0] is not None and planePath[1] is not None: length = 2000 starty = planePath[0][1] - length * math.sin(planePath[1]) startx = planePath[0][0] - length * math.cos(planePath[1]) endy = planePath[0][1] + length * math.sin(planePath[1]) endx = planePath[0][0] + length * math.cos(planePath[1]) draw.line(xy=[(startx, starty), (endx, endy)], width=3, fill=(0, 255, 255)) draw.ellipse([circlesCoords[0][0] - circlesCoords[1], circlesCoords[0][1] - circlesCoords[1], circlesCoords[0][0] + circlesCoords[1], circlesCoords[0][1] + circlesCoords[1]], outline='white') mapimg = Image.alpha_composite(mapimg, game_events_image) heatmapper = Heatmapper(point_diameter=25, point_strength=0.5, opacity=0.7) heatmapImg = heatmapper.heatmap_on_img(pointsList, mapimg) return heatmapImg
Example #21
Source File: weather-and-light.py From enviroplus-python with MIT License | 5 votes |
def draw_background(progress, period, day): """Given an amount of progress through the day or night, draw the background colour and overlay a blurred sun/moon.""" # x-coordinate for sun/moon x = x_from_sun_moon_time(progress, period, WIDTH) # If it's day, then move right to left if day: x = WIDTH - x # Calculate position on sun/moon's curve centre = WIDTH / 2 y = calculate_y_pos(x, centre) # Background colour background = map_colour(x, 80, mid_hue, day_hue, day) # New image for background colour img = Image.new('RGBA', (WIDTH, HEIGHT), color=background) # draw = ImageDraw.Draw(img) # New image for sun/moon overlay overlay = Image.new('RGBA', (WIDTH, HEIGHT), color=(0, 0, 0, 0)) overlay_draw = ImageDraw.Draw(overlay) # Draw the sun/moon circle = circle_coordinates(x, y, sun_radius) overlay_draw.ellipse(circle, fill=(200, 200, 50, opacity)) # Overlay the sun/moon on the background as an alpha matte composite = Image.alpha_composite(img, overlay).filter(ImageFilter.GaussianBlur(radius=blur)) return composite
Example #22
Source File: generator.py From 2buntu-blog with Apache License 2.0 | 5 votes |
def blit_template_image(output, template, filename): """ Blit the specified file from the template to the output image. """ img = Image.open(path.join(path.dirname(__file__), 'img', template, filename)) return Image.alpha_composite(output, img)
Example #23
Source File: radar_map.py From hdfm with GNU General Public License v3.0 | 5 votes |
def update_overlay(self): """ :return: True if updated, False if not """ # If no config has been received, try to get one. if not self.area_map.has_config(): rc = self.area_map.get_config() # If still no config, wait till later. if not rc: return False # Get any overlays new overlays. files = glob(os.path.join(DUMP, '*DWRO*')) new_files = [x for x in files if os.path.basename(x) != self.filename] # If there are none, delete old ones and exit. if not new_files: for file in files: os.remove(file) return False # Update using the first new overlay. self.overlay = Image.open(new_files[0]).convert('RGBA') self.overlay = self.overlay.resize((900, 900)) # Combine map and overlay. self.img = Image.alpha_composite( self.area_map.get_map(), self.overlay ) # Timestamp the radar. self.timestamp() # Update overlay filename. self.filename = os.path.basename(new_files[0]) # Save file if necessary. if self.do_save: self.save() # Delete all overlays. for file in files: os.remove(file) return True
Example #24
Source File: tritonize.py From tritonize with MIT License | 5 votes |
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))
Example #25
Source File: image_generator.py From YOLOv2 with MIT License | 5 votes |
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) # 画像周辺のパディングを削除
Example #26
Source File: functions.py From ttkwidgets with GNU General Public License v3.0 | 5 votes |
def overlay(image, color): """ Overlay a rectangle of color (RGBA) on the image and return the result. """ width, height = image.size im = Image.new("RGBA", (width, height), color) preview = Image.alpha_composite(image, im) return preview
Example #27
Source File: test_panoptic.py From seamseg with BSD 3-Clause "New" or "Revised" License | 5 votes |
def save_prediction_image(_, panoptic_pred, img_info, out_dir, colors, num_stuff): msk, cat, obj, iscrowd = panoptic_pred img = Image.open(img_info["abs_path"]) # Prepare folders and paths folder, img_name = path.split(img_info["rel_path"]) img_name, _ = path.splitext(img_name) out_dir = path.join(out_dir, folder) ensure_dir(out_dir) out_path = path.join(out_dir, img_name + ".jpg") # Render semantic sem = cat[msk].numpy() crowd = iscrowd[msk].numpy() sem[crowd == 1] = 255 sem_img = Image.fromarray(colors[sem]) sem_img = sem_img.resize(img_info["original_size"][::-1]) # Render contours is_background = (sem < num_stuff) | (sem == 255) msk = msk.numpy() msk[is_background] = 0 contours = find_boundaries(msk, mode="outer", background=0).astype(np.uint8) * 255 contours = dilation(contours) contours = np.expand_dims(contours, -1).repeat(4, -1) contours_img = Image.fromarray(contours, mode="RGBA") contours_img = contours_img.resize(img_info["original_size"][::-1]) # Compose final image and save out = Image.blend(img, sem_img, 0.5).convert(mode="RGBA") out = Image.alpha_composite(out, contours_img) out.convert(mode="RGB").save(out_path)
Example #28
Source File: create_svhn_dataset.py From stn-ocr with GNU General Public License v3.0 | 5 votes |
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
Example #29
Source File: drawdota.py From MangoByte with MIT License | 5 votes |
def get_neutral_image(item): background = Image.new("RGBA", (64, 64)) size = background.size circle_diameter = 48 circle_thickness = 4 img_scale = circle_diameter / 64 inner_radius = circle_diameter / 2 inner_circle = ((size[0] / 2) - inner_radius, (size[1] / 2) - inner_radius, (size[0] / 2) + inner_radius, (size[1] / 2) + inner_radius) outer_radius = inner_radius + circle_thickness outer_circle = ((size[0] / 2) - outer_radius, (size[1] / 2) - outer_radius, (size[0] / 2) + outer_radius, (size[1] / 2) + outer_radius) if item: draw = ImageDraw.Draw(background) draw.ellipse(outer_circle, fill="#393939") item_img = await get_item_image(item) item_img = item_img.resize((int(item_img.size[0] * img_scale), int(item_img.size[1] * img_scale))) item_img = item_img.crop(( math.floor((item_img.size[0] - background.size[0]) / 2), math.floor((item_img.size[1] - background.size[1]) / 2), item_img.size[0] - math.ceil((item_img.size[0] - background.size[0]) / 2), item_img.size[1] - math.ceil((item_img.size[1] - background.size[1]) / 2)) ) mask_circle = Image.new("RGBA", background.size) mask_draw = ImageDraw.Draw(mask_circle) mask_draw.ellipse(inner_circle, fill="#ffffff") temp_image = Image.new("RGBA", (64, 64)) temp_image.paste(item_img, (0, 0), mask=mask_circle) return Image.alpha_composite(background, temp_image) else: return background
Example #30
Source File: imagetools.py From MangoByte with MIT License | 5 votes |
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