def _overlay_boxes(self, image, predictions): """ Adds the predicted boxes on top of the image Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `labels`. """ if predictions.has_field("labels"): labels = predictions.get_field("labels") else: labels = torch.ones(len(predictions.bbox), dtype=torch.float) boxes = predictions.bbox colors = self._compute_colors_for_labels(labels).tolist() pil_image = ToPILImage()(np.transpose(image, (1, 2, 0))) draw = Draw(pil_image) for box, color in zip(boxes, colors): box = box.to(torch.int64) top_left, bottom_right = box[:2].tolist(), box[2:].tolist() draw.rectangle( [top_left[0], top_left[1], bottom_right[0], bottom_right[1]], outline=tuple(color), width=2) del draw return np.array(pil_image)
def draw_balloon(img_draw: ImageDraw.Draw, points: Box, fill=None, width=0): r_x0 = points.top_left.x r_y0 = points.top_left.y + BOX_RADIUS r_x1 = points.bottom_right.x r_y1 = points.bottom_right.y - BOX_RADIUS img_draw.rectangle([r_x0, r_y0, r_x1, r_y1], fill=fill, width=width) r_x0 = points.top_left.x + BOX_RADIUS r_y0 = points.top_left.y r_x1 = points.bottom_right.x - BOX_RADIUS r_y1 = points.bottom_right.y img_draw.rectangle([r_x0, r_y0, r_x1, r_y1], fill=fill, width=width) diam = 2 * BOX_RADIUS c_x0 = points.top_left.x c_y0 = points.top_left.y c_x1 = c_x0 + diam c_y1 = c_y0 + diam img_draw.ellipse([c_x0, c_y0, c_x1, c_y1], fill=fill, width=width) c_x0 = points.bottom_right.x - diam c_x1 = c_x0 + diam img_draw.ellipse([c_x0, c_y0, c_x1, c_y1], fill=fill, width=width) c_y0 = points.bottom_right.y - diam c_y1 = c_y0 + diam img_draw.ellipse([c_x0, c_y0, c_x1, c_y1], fill=fill, width=width) arrow_x = 10 arrow_y = 10 if BOX_RADIUS < 10 else BOX_RADIUS arrow = [ (points.top_left.x - arrow_x, points.bottom_right.y), (points.top_left.x, points.bottom_right.y - arrow_y), (points.top_left.x + diam, points.bottom_right.y - arrow_y), (points.top_left.x + diam, points.bottom_right.y), ] img_draw.polygon(arrow, fill=fill)
async def nearest(self, ctx: Context, colour: Colour, n: int = 1): # TODO text clipping, maybe allow hex as an optional arg? nearest = self.get_colour_names(colour, n=n) async with ctx.channel.typing: async with spawn_thread(): with Image.new( 'RGBA', (SIDE_WIDTH, int(SIDE_WIDTH / 5 * len(nearest)))) as img: draw = Draw(img) for rectangle_index, (colour, name) in enumerate(nearest): offset = int(rectangle_index * SIDE_WIDTH / 5) draw.rectangle([ 0, 0 + offset, SIDE_WIDTH, SIDE_WIDTH / 5 + offset ], fill=colour.rgb) font_colour = (0, 0, 0) if colour.contrast( Colour(0x000000)) >= 15 else (255, 255, 255) name = antialiased_text(name, FONT_SMALL, SIDE_WIDTH, int(SIDE_WIDTH / 5), fill=font_colour) img.paste(name, (0, 0 + offset), name) buffer = save_image(img) await ctx.channel.messages.upload(buffer, filename='cool.png')
def eval(config: dict, model_path='checkpoints/model_epoch30.pth'): ssd = build_model(config, is_test=True) ssd.load_state_dict(torch.load(model_path)) ssd.train(False) net = Predictor(ssd) data_transform = transforms.Compose([ transforms.ToRelativeBoxes(), transforms.Resize(config['image_size']), transforms.Scale(), transforms.ToTensor() ]) target_transform = MatchPrior(priors, config) val_set = CityscapesDataset(config, 'dataset/val', None, data_transform, target_transform, True) test_image = val_set.get_image(0) boxes, labels, conf, _, _ = net.predict(test_image) drawer = Draw(test_image) for i in range(boxes.shape[0]): top_left = tuple(boxes[i][:2].numpy().flatten()) bottom_right = tuple(boxes[i][2:].numpy().flatten()) drawer.rectangle((top_left, bottom_right)) test_image.save("predict.jpg")
def draw_bbox(image_path, boxes, is_image_file=False): if is_image_file == False: pil_image = Image.open(image_path) else: pil_image = image_path fnt = ImageFont.truetype('arial.ttf', 35) draw = Draw(pil_image) #for box, color, score in zip(boxes, colors, scores): for box in boxes: box = box.to(torch.int64) top_left, bottom_right = box[:2].tolist(), box[2:].tolist() draw.rectangle( [top_left[0], top_left[1], bottom_right[0], bottom_right[1]], outline=(0, 0, 0)) #draw.rectangle([top_left[0], top_left[1], bottom_right[0], bottom_right[1]], outline=tuple(color), width=15) mtext = "{:.2f}".format(0.8020) left_off = 7 top_off = 5 xmin, ymin, xmax, ymax = top_left[0], top_left[1], bottom_right[ 0], bottom_right[1] #draw.rectangle([xmin, ymin, xmin+100, ymin+40], outline=(0,0,0), width=10) #draw.text((xmin-1+left_off,ymin+top_off), mtext, font=fnt, fill=(0,0,0,128)) #draw.text((xmin+left_off,ymin-1+top_off), mtext, font=fnt, fill=(0,0,0,128)) #draw.text((xmin+1+left_off,ymin+top_off), mtext, font=fnt, fill=(0,0,0,128)) #draw.text((xmin+left_off,ymin+1+top_off), mtext, font=fnt, fill=(0,0,0,128)) #draw.text((xmin+left_off,ymin+top_off), mtext, font=fnt, fill=(255,255,255,128)) del draw return pil_image
def __imgBox(self, obj_list, image, im_width, im_height): im = image.convert('RGBA') drawn = Draw(im) fontsize = im_height * 0.01 font = ImageFont.truetype('arial.ttf', int(round(fontsize))) coords = [] for inst in obj_list: label = inst.tag_name probability = inst.probability x0, y0 = inst.bounding_box.left * im_width, inst.bounding_box.top * im_height x1, y1 = x0 + inst.bounding_box.width * im_width, y0 + inst.bounding_box.height * im_height xC, yC = abs(x0 + x1) / 2, abs(y0 + y1) / 2 xC, yC = self.__img_to_drone_coords(xC, yC, im_width, im_height) coords.append((xC, yC)) drawn.rectangle([(x0, y0), (x1, y1)], outline=(255, 0, 0, 255)) drawn.text((x0, y0), f'{label}: {round(probability, 3)}; ({xC}, {yC})', fill=(0, 0, 0, 255), font=font) return im, coords
def plot_target(self, imgs, targets): toImg = transforms.ToPILImage() cls_name = ['car', 'person', 'fire'] for i in range(imgs.size(0)): img = toImg(imgs[i, ...]) img = img.resize((540, 540)) img_w, img_h = img.size ori_w, ori_h = img.size target = [] for t in targets: if t[0] == i: target.append(t) draw = Draw(img) for idx, cls_, cx, cy, w, h in target: if (cls_ == 0 or cls_ == 2): continue x1 = int(float(cx) * img_w - float(w) * img_w / 2) y1 = int(float(cy) * img_h - float(h) * img_h / 2) x2 = int(float(cx) * img_w + float(w) * img_w / 2) y2 = int(float(cy) * img_h + float(h) * img_h / 2) # if (x2 - x1 > 120 or y2 -y1 > 120): # print(x2-x1, y2-y1) #print(x2-x1, y2-y1) draw.rectangle([(x1, y1), (x2, y2)], outline=(255, 255, 0)) self.viz.image(np.array(img).transpose((2, 0, 1)), win=i)
def draw_text(text, font_spec, text_color, xy=None, anchor=None, box_color=None, box_padding=0, border_color=None, border_width=0, image=None): """Draws centered text on an image, optionally in a box.""" draw = Draw(image) text_size = font_spec['size'] font = ImageFont.truetype(font_spec['file'], size=text_size) # Measure the width of each character. character_widths = [] for character in text: # Override the measured width, if specified. width_overrides = font_spec['width_overrides'] if character in width_overrides.keys(): character_width = width_overrides[character] else: character_width, _ = draw.textsize(character, font) character_widths.append(character_width) text_width = sum(character_widths) # If any xy is specified, use it. text_height = font_spec['height'] if xy: x = xy[0] - text_width // 2 y = xy[1] - text_height // 2 # If any anchor is specified, adjust the xy. if anchor == 'center': x = image.width // 2 - text_width // 2 y = image.height // 2 - text_height // 2 elif anchor == 'center_x': x = image.width // 2 - text_width // 2 elif anchor == 'center_y': y = image.height // 2 - text_height // 2 elif anchor == 'bottom_right': x = image.width - box_padding - border_width - text_width y = image.height - box_padding - border_width - text_height # Draw the box background and border. box_xy = [x - box_padding, y - box_padding, x + text_width + box_padding, y + text_height + box_padding] border_xy = [box_xy[0] - border_width, box_xy[1] - border_width, box_xy[2] + border_width, box_xy[3] + border_width] if border_color: draw.rectangle(border_xy, border_color) if box_color: draw.rectangle(box_xy, box_color) # Draw the text character by character. y -= font_spec['y_offset'] for index in range(len(text)): character = text[index] draw.text((x, y), character, text_color, font) x += character_widths[index]
def eval(config: dict, model_path='checkpoints/model_epoch40.pth'): ssd = build_model(config, is_test=True) ssd.load_state_dict(torch.load(model_path)) ssd.train(False) net = Predictor(ssd) data_transform = transforms.Compose([ transforms.ToRelativeBoxes(), transforms.Resize(config['image_size']), transforms.Scale(), transforms.ToTensor() ]) target_transform = MatchPrior(priors, config) val_set = CityscapesDataset(config, 'dataset/val', None, data_transform, target_transform, True) for i, _ in enumerate(val_set): if i % 10 == 0: print("Image {}".format(i)) image = val_set.get_image(i) probs, boxes, disparity = net.predict(image) labels = torch.argmax(probs, dim=probs.dim() - 1) chosen_indices = [] for class_index in range(1, config['num_classes'] + 1): class_mask = labels == class_index # If there's no prediction in this class, skip the class if class_mask.long().sum() <= 0: continue class_probabilities = probs[class_mask, class_index] class_boxes = boxes[class_mask] class_indices = nms(class_boxes, class_probabilities, 0.5) chosen_indices.append(class_indices) chosen_indices = torch.cat(chosen_indices) probs = probs[chosen_indices] boxes = boxes[chosen_indices] box_drawer = Draw(image) for box in boxes: top_left = tuple(box[:2].numpy().flatten()) bottom_right = tuple(box[2:].numpy().flatten()) box_drawer.rectangle((top_left, bottom_right)) image.save('result.jpg') # TODO change to all image evaluation break
def bb_orig_img(img): img_arr = Image.open(expand_path(img)) xmin, ymin, xmax, ymax = train_p2bb.get(img) crop_img_arr = img_to_array(img_arr)[ymin:ymax, xmin:xmax, :] draw = Draw(img_arr) draw_dots(draw, train_p2bb.get(img)) draw.rectangle(train_p2bb.get(img), outline='red') return img_arr, crop_img_arr
def draw_occluder(array, occluder, v=8): hw = array.shape[0] im = Image.fromarray(array).convert("L") draw = Draw(im) o = [occluder[0], -occluder[1], occluder[2], -occluder[3]] o = [int((x + 1) * hw / 2) for x in o] draw.rectangle(tuple(o), fill=v, outline=v) return np.array(im)
def make_image(tmpdir): img = PilImage.new("RGBA", (500, 200), "black") draw = Draw(img) draw.rectangle((50, 50, 100, 180), fill="green") draw.rectangle((250, 80, 450, 160), fill="red") filename = str(tmpdir / "image.png") img.save(filename) return Image(filename)
def draw(self, draw_ctx: Draw): self._establish_order() if self.background_color is not None: draw_ctx.rectangle( [(0, 0), tuple(self.canvas_size + (1, 1))], fill=self.background_color.to8bit_rgba()) for entity in self.z_order: if entity.visible: entity.draw(draw_ctx)
def vis_boxes(self, thickness: int = 2) -> Image.Image: if self.boxes.shape[0] == 0: return self.image img = self.image.copy() drawer = Draw(img) for box in self.boxes: drawer.rectangle(box.tolist(), width=thickness, outline="white") return img
def prettify(frame): off = 5 h, w = frame.shape[:2] pretty = Image.new('RGB', (w + off, h + off), '#ffffff') draw = Draw(pretty) draw.rectangle([off, off, w + off, h + off], '#cccccc', '#cccccc') pretty.paste(Image.fromarray(frame), (0, 0)) draw.rectangle([0, 0, w, h], outline='#666666') return numpy.array(pretty)
def draw_occluder(self, array, occluder): im = Image.fromarray(array) draw = Draw(im) occluder = [int(x * self.hw / 2) for x in occluder] draw.rectangle( [0, occluder[0], self.hw, sum(occluder)], fill=tuple(self.color_list[self.n_obj]), outline=tuple(self.color_list[self.n_obj]), ) return np.array(im)
def create_noise_dots(image, width=1, number=30): draw = Draw(image) w, h = image.size while number: color = random_color(10, 150) x1 = random.randint(0, w) y1 = random.randint(0, h) draw.rectangle(((x1, y1), (x1 + 1, y1 + 1)), fill=color, width=width) number -= 1 return image
def get_classification(self, inp_image): """Determines the color of the traffic light in the image Args: image (cv::Mat): image containing the traffic light Returns: int: ID of traffic light color (specified in styx_msgs/TrafficLight) """ image_array = np.array(inp_image) image = np.reshape(image_array, (1, image_array.shape[0], image_array.shape[1], image_array.shape[2])) results = self.sess.run( [ self.graph.get_tensor_by_name('prefix/detection_boxes:0'), self.graph.get_tensor_by_name('prefix/detection_scores:0'), self.graph.get_tensor_by_name('prefix/detection_classes:0') ], {self.graph.get_tensor_by_name('prefix/image_tensor:0'): image}) pilimg = Image.fromarray(image_array) classes = [] for boxid in range(len(results[0][0])): if results[1][0][boxid] > 0.5: predclass = results[2][0][boxid] classes.append(predclass) if self.save_pred_images: width = pilimg.size[0] height = pilimg.size[1] box = results[0][0][boxid] xmin = int(box[1] * width) ymin = int(box[0] * height) xmax = int(box[3] * width) ymax = int(box[2] * height) draw = Draw(pilimg) draw.rectangle([(xmin, ymin), (xmax, ymax)], outline='red') draw.text((xmax + 5, ymin + 5), "Class: " + str(self.class_map_str[predclass]), font=self.font) if self.save_pred_images: pilimg.save( "/capstone/ros/classifier_output/bag/{:0>5d}.jpg".format( self.prediction_counter)) self.prediction_counter += 1 if classes: keys = Counter(classes).keys() vals = Counter(classes).values() pred_class = keys[np.argmax(vals)] return self.class_map[pred_class] else: return TrafficLight.UNKNOWN
def _draw_date_box(self, draw: ImageDraw.Draw, top_left_corner: Tuple[int, int], width: int, date: datetime) -> int: """ Draws a date/time clock onto the canvas at the given position. Args: draw: The ImageDraw instance to draw on the desired canvas. top_left_corner: Where to start the box. width: The fixed horizontal dimension of the box. date: The date/time to display on the clock. Returns: The bottom y coordinate of the box, so that further elements may be drawn after it """ time_str = format_time(date, 'HH:mm', locale='pt_BR') time_font = self.fonts['huge'] time_font_height = time_font.getsize('X')[1] date_str = format_date(date, "EEEE\ndd 'de' MMM 'de' yyyy", locale='pt_BR').capitalize() date_font = self.fonts['large'] date_font_height = date_font.getsize('X')[1] margin = 20 * self.scaler_value bottom_y = int(top_left_corner[1] + time_font_height + date_font_height * 2 + margin * 4) draw.rectangle( ( top_left_corner[0], top_left_corner[1], top_left_corner[0] + width, bottom_y ), fill=self.colors['date_box_background'] ) time_y = top_left_corner[1] + margin draw.text( (top_left_corner[0] + margin, time_y), time_str, fill=self.colors['date_box_text'], font=time_font, ) draw.multiline_text( (top_left_corner[0] + margin, time_y + time_font_height + margin), date_str, fill=self.colors['date_box_text'], font=date_font ) return bottom_y
def draw_bounding_box(self, bio: BytesIO, bbox: BoundingBox) -> BytesIO: if not bbox.is_usable: return (bio, False) image = Image.open(bio) #shape=[(bbox.left,bbox.top), # (bbox.left +bbox.width, bbox.top+bbox.height)] drawing = Draw(image) drawing.rectangle(bbox.shape, outline="red") bout = BytesIO() image.save(bout, "PNG") bout.seek(0) return bout
async def colour_changed(self, ctx: EventContext, old: Role, new: Role): # We only care about colour changes if old.colour == new.colour: return # TODO make this event configured per-server # TODO make channel configurable per server channel = new.guild.system_channel # Weird if channel is None: return async with spawn_thread(): # one colour is 100x100 -> 200x100 is the image size with Image.new('RGBA', (2 * SIDE_WIDTH, SIDE_WIDTH)) as img: draw = Draw(img) # Draws the coloured rectangles for rectangle_index, colour in enumerate( map(Colour, (old.colour, new.colour))): offset = rectangle_index * SIDE_WIDTH draw.rectangle( [0 + offset, 0, SIDE_WIDTH + offset, SIDE_WIDTH], fill=colour.rgb) # This makes text black if the contrast between black text and the background colour # is high because white text becomes unreadable on light coloured backgrounds. font_colour = (0, 0, 0) if colour.contrast( Colour(0x000000)) >= 15 else (255, 255, 255) nearest_colour = self.get_colour_names(colour, n=1).pop().name name = antialiased_text(nearest_colour, FONT_SMALL, SIDE_WIDTH, fill=font_colour, offset_y=3 / 4, wrap_width=18) code = antialiased_text(str(colour).upper(), FONT_BIG, SIDE_WIDTH, fill=font_colour) img.paste(name, (0 + offset, 0), name) img.paste(code, (0 + offset, 0), code) img = add_title(img, new.name, FONT_SMALL, height=25) buffer = save_image(img) await channel.messages.upload(buffer, filename='cool.png')
def make_mask(f, hw): im = Image.new("L", (hw, hw)) draw_mask = Draw(im) for i, o in enumerate(f.transpose()): if np.linalg.norm(o[:3]) == 0: continue r = int(o[-1] * hw / 2) p = [int((x + 1) * hw / 2.0) for x in o] box = (p[0] - r, p[1] - r, p[0] + r, p[1] + r) if i < 5: draw_mask.ellipse(box, fill=i + 1, outline=i + 1) else: draw_mask.rectangle(box, fill=i + 1, outline=i + 1) return np.array(im)
def process(self, fft): fft = (fft * 15) * self.bar_window img = Image.new("RGB", self.size) d = Draw(img) bar_width = self.size[0] / self.config.segs half_height = self.size[1] / 2.0 for i in range(0, self.config.segs): val = max(fft[i], self.config.min) / 2.0 d.rectangle([ i * bar_width, half_height - val, (i + 1) * bar_width, half_height + val ]) del d return img
def _error_image_action(self, error_list, scaled=False): """ Create image with hints of clashes. error_list contains coordinates of characters which encounters clashes. Picture is for overview only,so it is always have dimensions 320x200. """ char_x_size = 1 x_offset = 3 if self._errors_action == "none": return image = self._src_image.copy().convert("RGBA") # TODO: refactor this crap below if scaled: image = image.resize((320, 200)) if image.size[0] == 320: x_offset = 7 if scaled: char_x_size = 2 if image.size[0] == 160: char_x_size = 1 image_map = image.copy() drawable = Draw(image_map) for chrx, chry in error_list: drawable.rectangle((chrx * char_x_size, chry, chrx * char_x_size + x_offset, chry + 7), outline="red") image = Image.blend(image, image_map, 0.65) del drawable if self._errors_action in ('save', 'grafx2'): file_obj = open(get_modified_fname(self._fname, 'png', '_error.'), "wb") image.save(file_obj, "png") file_obj.close() if self._errors_action == 'grafx2': os.system("grafx2 %s %s" % (self._fname, get_modified_fname(self._fname, 'png', '_error.'))) else: clashes = image.resize((640, 400)) clashes.show()
def DrawLapDuration(self, drw: ImageDraw.Draw): height = 125 width = 225 top = self._resolution[1] - height drw.rectangle( ((0, self._resolution[1] - height), (width, self._resolution[1])), fill=(0, 0, 0, 255)) index = 0 text_height = 40 for lap_number, lap_duration_ms in self._lap_duration_queue[-3:]: drw.text( (0, top + (text_height * index)), '%s %s' % (lap_number, _FormatLapDuration(lap_duration_ms)), font=self._font, fill=(0, 255, 0, 255)) index += 1
def make_zoomin(image, frames): h, w = image.shape[:2] scale = F.h / float(h) / F.zoom_frac step = (1 - scale) / (F.zoom + 1) original = Image.fromarray(image) for i in range(F.zoom): small = original.resize( (int(w * scale + .5), int(h * scale + .5)), Image.LANCZOS) scale += step small_w = small.size[0] frame = Image.new('RGB', (w, F.h), '#ffffff') off = (w - small_w) // 2 frame.paste(small, (off, 0)) draw = Draw(frame) draw.rectangle([off, 0, off + small_w, F.h], outline='#666666') add_frame(frames, numpy.array(frame), .2 if i > 0 else 1)
def draw_bbox(img_obj, bbox, save_dir, gt_bool=False): ''' :param img_obj: PIL Image Object :param bbox: [xmin, ymin, xmax, ymax] :return: ''' if gt_bool: color = (200, 10, 10) else: color = (10, 200, 10) draw_handle = Draw(img_obj) draw_handle.rectangle(bbox, outline=color) img_obj.save(save_dir) print('Draw bbox {}'.format(save_dir))
def _get_image(self, traj, id, augments=None): """Returns image from the given trajectory and sample ID as a numpy array """ traj_name = self.all_trajs[traj] filename = "{}.{}".format(id, self.fileformat) path = os.path.join(self.dir, "screens", self.game, traj_name, filename) img = Image.open(path) img.load() if augments is not None: if "shadow" in augments: # (alpha, x, y, w, h) # Draw a randomly placed rectangle on the image draw = Draw(img, "RGBA") rect_color = (0, 0, 0, augments["shadow"][0]) rect_w = augments["shadow"][3] rect_h = augments["shadow"][4] rect_x = augments["shadow"][1] rect_y = augments["shadow"][2] draw.rectangle([ rect_x - rect_w / 2, rect_y - rect_h / 2, rect_x + rect_w / 2, rect_y + rect_h / 2 ], rect_color) if "brightness" in augments: enhancer = ImageEnhance.Brightness(img) img = enhancer.enhance(augments["brightness"]) if "rotate" in augments: img = img.rotate(augments["rotate"]) if "shear" in augments: raise NotImplementedError if "tx" in augments and "ty" in augments: # Shift img = ImageChops.offset(img, xoffset=augments["tx"], yoffset=augments["ty"]) if "zx" in augments and "zy" in augments: # Zoom raise NotImplementedError if "flip" in augments and augments["flip"]: img = img.transpose(Image.FLIP_LEFT_RIGHT) img = img.resize(self.size, Image.BILINEAR) img = np.asarray(img, dtype=np.uint8) return img
def add_title(image: Image, text: str, font: ImageFont, height: int, **text_kwargs): """ Adds a title strip to the top of the image. Changes the size of the image to be `image.size + (0, height)` See this for reference: https://cdn.discordapp.com/attachments/400042308189290509/448185670339395605/cool.png :param image: The image to add the title to :param text: The text to be written on the title :param font: The font that will be used to write the title text :param height: The height of the title :param text_kwargs: Extra keyword arguments to be passed into antialiased_text :return: New image with the title """ f_width, f_height = font.getsize(text) if f_height > height: raise ValueError('Height of title must be larger than the font') x, y = image.size with Image.new('RGBA', (x, y + height)) as img: draw = Draw(img) img.paste(image, (0, height), image) with Image.new('RGBA', (x, y + height)) as shadow: # Draw the shadow box and apply blur cool = Draw(shadow) for i in range(1, 6): cool.rectangle([(0, height + i), (x, height + 1 + i)], fill=(38, 38, 38, 31 * (6 - i))) img.paste(shadow, (0, 0), shadow) draw.rectangle([0, 0, x, height], fill=(32, 34, 37)) text = antialiased_text(text, font, size_x=x, size_y=height, fill=(255, 255, 255), **text_kwargs) img.paste(text, (0, 0), text) return img.copy()
def plot_oriyolo(self, imgs, detections): detections = non_max_suppression(detections, self.opt.conf_thres, self.opt.nms_thres) toImg = transforms.ToPILImage() # we only show the image_batch[0] idx = [] i = 0 cls_name = ['car', 'person', 'fire'] for detection in detections: if detection is not None: idx.append(i) i += 1 if len(idx) == 0: self.viz.text('no bbox found with the conf_thres in %.2f' % (self.opt.conf_thres), win=1) return for i in idx: img = toImg(imgs[i, ...]) ori_w, ori_h = img.size img = img.resize((270, 270)) detection = detections[i] w, h = img.size draw = Draw(img) if detection is not None: for x1, y1, x2, y2, conf, cls_conf, cls_pred in detection: x1 = float(x1) / ori_w * w y1 = float(y1) / ori_h * h x2 = float(x2) / ori_w * w y2 = float(y2) / ori_h * h x1 = max(0, int(x1)) y1 = max(0, int(y1)) x2 = min(int(x2), w) y2 = min(int(y2), h) draw.rectangle([(x1, y1), (x2, y2)], outline=(255, 0, 0)) #print(cls_pred) name = cls_name[int(cls_pred)] name += "=%.4f" % float(cls_conf) f = ImageFont.truetype("fonts-japanese-gothic.ttf", 15) draw.text((x1, y1), name, 'blue', font=f) self.viz.image(np.array(img).transpose((2, 0, 1)), win=i + 2)
def drawclock(fontpath,fontsize,fgcolor,bgcolor,style,case,drawLEDs=False): # init font scaledfontsize = pt2pxy(fontsize) font = ImageFont.truetype(size=scaledfontsize,filename=fontpath) lines = decodeLetters(style,case) img = Image.new("RGBA", (pt2pxx(WIDTH), pt2pxy(HEIGHT))) draw = Draw(img) draw.rectangle(((0,0), (pt2pxx(WIDTH),pt2pxy(HEIGHT))), fill=bgcolor) for h in corner_holes: drawhole(draw,h,fgcolor) if drawLEDs: drawleds(draw,led_xs,led_ys,fgcolor) drawletters(draw,lines,font,case,led_xs,led_ys,fgcolor) del draw return img
def get_frame(self, n, im_width, im_height): """Return a single frame as a PIL Image. Arguments: n -- the frame index im_width -- the width of the Image to return im_height -- the height of the Image to return """ offset, length, duration = self.frames[n] tiles = self.tiles[offset:offset + length] # Create new blank image img = PILImage.new('RGBA', (im_width, im_height)) draw = PILDraw(img) draw.rectangle(((0, 0), (im_width, im_height)), fill=self.bg) src = self.get_processed_image() # Blit tiles for tile in tiles: x, y, u, v = tile # Fix edge repeat by overlapping tiles 1px x *= self.tile_w - 1 y *= self.tile_h - 1 if x > 0: x += 1 if y > 0: y += 1 # Crop tile u *= self.tile_w v *= self.tile_h box = (u, v, u + self.tile_w, v + self.tile_h) part = src.crop(box) # Paste onto frame box = (x, y, x + self.tile_w, y + self.tile_h) img.paste(part, box) return img
((16, 8), (18, 8)), ((8, 9), (18, 9)), ((11, 12), (18, 12)), ((11, 13), (18, 13)), ((8, 16), (18, 16)), ((3, 19), (8, 19)), ((3, 23), (8, 22)), ] # <codecell> from PIL import Image from PIL.ImageDraw import Draw img = Image.new("RGBA", (100, 100)) draw = Draw(img) draw.rectangle(((0,0), (100, 100)), fill=(255, 100, 0)) draw.rectangle((50,80,100,200), fill=0) # img.save("foo.png") imshow(numpy.asarray(img)) # <codecell> given_image_size = (600, 900) image_min_dimen = min(given_image_size) image_center = (given_image_size[0] / 2, given_image_size[1] / 2) from PIL import Image from PIL.ImageDraw import Draw from math import sin, cos, radians import random img = Image.new("RGBA", given_image_size)
def display_pil_image(im): """Displayhook function for PIL Images, rendered as PNG.""" b = BytesIO() im.save(b, format='png') data = b.getvalue() ip_img = display.Image(data=data, format='png', embed=True) return ip_img._repr_png_() # register display func with PNG formatter: png_formatter = get_ipython().display_formatter.formatters['image/png'] dpi = png_formatter.for_type(Image.Image, display_pil_image) # <codecell> from PIL import Image from PIL.ImageDraw import Draw img = Image.new("RGBA", (100, 100)) draw = Draw(img) draw.rectangle(((0,0), (100, 100)), fill=(255, 100, 0)) # img.save("foo.png") imshow(img) # <codecell>