Python PIL.ImageDraw.Draw() Examples
The following are 30
code examples of PIL.ImageDraw.Draw().
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.ImageDraw
, or try the search function
.

Example #1
Source File: polapizero_03.py From polapi-zero with MIT License | 7 votes |
def displayImageFileOnLCD(filename): print 'displays ', filename title = 'Review Mode' # resize/dither to screen resolution and send to LCD image = Image.open(filename) im_width, im_height = image.size if im_width < im_height: image = image.rotate(90) image.thumbnail(S_SIZE, Image.ANTIALIAS) image_sized = Image.new('RGB', S_SIZE, (0, 0, 0)) image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2)) # draw filename draw = ImageDraw.Draw(image_sized) font = ImageFont.truetype('arial.ttf', 18) draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0)) draw.text((2, 2), title, fill='black', font=font) draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0)) draw.text((290, 218), filename, fill='black', font=font) # display on LCD image_sized = ImageOps.invert(image_sized) image_sized = image_sized.convert('1') # convert image to black and white lcd.write(image_sized.tobytes())
Example #2
Source File: demo.py From StackGAN with MIT License | 6 votes |
def drawCaption(img, caption): img_txt = Image.fromarray(img) # get a font fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 50) # get a drawing context d = ImageDraw.Draw(img_txt) # draw text, half opacity d.text((10, 256), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 512), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) if img.shape[0] > 832: d.text((10, 832), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 1088), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) idx = caption.find(' ', 60) if idx == -1: d.text((256, 10), caption, font=fnt, fill=(255, 255, 255, 255)) else: cap1 = caption[:idx] cap2 = caption[idx+1:] d.text((256, 10), cap1, font=fnt, fill=(255, 255, 255, 255)) d.text((256, 60), cap2, font=fnt, fill=(255, 255, 255, 255)) return img_txt
Example #3
Source File: OP_1_Connection.py From OP_Manager with MIT License | 6 votes |
def check_OP_1_Connection(): connected = Image.new('1', (128, 64)) draw = ImageDraw.Draw(connected) draw.text((0, 25), "Connecting.....", font=getFont(), fill='white') displayImage(connected) # if is_connected(): if do_mount("OP1"): connected = Image.new('1', (128, 64)) draw = ImageDraw.Draw(connected) draw.text((0, 25), "Connected", font=getFont(), fill='white') displayImage(connected) return True else: connected = Image.new('1', (128, 64)) draw = ImageDraw.Draw(connected) draw.text((0, 25), "No Connection!", font=getFont(), fill='white') displayImage(connected) config["USB_Mount_Path"] = "" config["OP_1_Mounted_Dir"] = "" time.sleep(1) return False
Example #4
Source File: __main__.py From anishot with MIT License | 6 votes |
def render_frame(image, y, frame): w, h = image.size fw, fh = frame.size x = (fw - w) // 2 draw = Draw(frame) # Draw shadow and image. off = ARGS.shadow_size draw.rectangle( [x + off, y + off, x + off + w, y + off + h], ARGS.rgb_shadow) frame.paste(image, (x, y)) draw.rectangle([x, y, x + w, y + h], outline=ARGS.rgb_outline) # Draw a frame border. draw.rectangle([0, 0, fw - 1, fh - 1], outline=ARGS.rgb_window)
Example #5
Source File: OP_1_Connection.py From OP_Manager with MIT License | 6 votes |
def unmount_OP_Z(): if getMountPath("OPZ") != "": unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((30, 25), "Ejecting!", font=getFont(), fill='white') displayImage(unmountDisplay) unmountdevice(config["OP_Z_Mounted_Dir"]) config["USB_Mount_Path"] = "" unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((30, 25), "Ejected!", font=getFont(), fill='white') displayImage(unmountDisplay) time.sleep(1) return True else: unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((15, 25), "No Device to Eject", font=getFont(), fill='white') displayImage(unmountDisplay) time.sleep(1) return False
Example #6
Source File: visualization.py From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License | 6 votes |
def _draw_single_box(image, xmin, ymin, xmax, ymax, display_str, font, color='black', thickness=4): draw = ImageDraw.Draw(image) (left, right, top, bottom) = (xmin, xmax, ymin, ymax) draw.line([(left, top), (left, bottom), (right, bottom), (right, top), (left, top)], width=thickness, fill=color) text_bottom = bottom # Reverse list and print from bottom to top. text_width, text_height = font.getsize(display_str) margin = np.ceil(0.05 * text_height) draw.rectangle( [(left, text_bottom - text_height - 2 * margin), (left + text_width, text_bottom)], fill=color) draw.text( (left + margin, text_bottom - text_height - margin), display_str, fill='black', font=font) return image
Example #7
Source File: util.py From bnn with MIT License | 6 votes |
def side_by_side(rgb, bitmap): h, w, _ = rgb.shape canvas = Image.new('RGB', (w*2, h), (50, 50, 50)) # paste RGB on left hand side lhs = zero_centered_array_to_pil_image(rgb) canvas.paste(lhs, (0, 0)) # paste bitmap version of labels on right hand side # black with white dots at labels rhs = bitmap_to_pil_image(bitmap) rhs = rhs.resize((w, h)) canvas.paste(rhs, (w, 0)) # draw on a blue border (and blue middle divider) to make it # easier to see relative positions. draw = ImageDraw.Draw(canvas) draw.polygon([0,0,w*2-1,0,w*2-1,h-1,0,h-1], outline='blue') draw.line([w,0,w,h], fill='blue') canvas = canvas.resize((w, h//2)) return canvas
Example #8
Source File: polapizero_04.py From polapi-zero with MIT License | 6 votes |
def displayImageFileOnLCD(filename): print 'displays ', filename title = 'Review Mode' # resize/dither to screen resolution and send to LCD image = Image.open(filename) im_width, im_height = image.size if im_width < im_height: image = image.rotate(90) image.thumbnail(S_SIZE, Image.ANTIALIAS) image_sized = Image.new('RGB', S_SIZE, (0, 0, 0)) image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2)) # draw filename draw = ImageDraw.Draw(image_sized) font = ImageFont.truetype('arial.ttf', 18) draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0)) draw.text((2, 2), title, fill='black', font=font) draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0)) draw.text((290, 218), filename, fill='black', font=font) # display on LCD image_sized = ImageOps.invert(image_sized) image_sized = image_sized.convert('1') # convert image to black and white lcd.write(image_sized.tobytes())
Example #9
Source File: gradient.py From wallgen with MIT License | 6 votes |
def nGradient(side, *colors): img = Image.new("RGB", (side,side), "#FFFFFF") draw = ImageDraw.Draw(img) nc = len(colors) div = side//(nc-1) [r,g,b] = colors[0] p=0 for i in range(1,nc): dc = [(y-x)/div for x,y in zip(colors[i-1], colors[i])] for x in range(p, p+div): draw.line([x,0,x,side], fill=tuple(map(int, [r,g,b]))) r+=dc[0] g+=dc[1] b+=dc[2] p+=div return img
Example #10
Source File: shapes.py From wallgen with MIT License | 6 votes |
def drawSlants(side): randcolor = lambda : (randint(0,255),randint(0,255),randint(0,255)) img = Image.new("RGB", (side,side), "#FFFFFF") draw = ImageDraw.Draw(img) y = 0 min_w = int(side * 0.01) max_w = int(side * 0.1) adj = max_w * 2 while y <= side+adj: w = randint(min_w, max_w) c = randcolor() draw.line([-adj , y, y, -adj], width=w, fill=c) draw.line([y, side+adj, side+adj, y], width=w, fill=c) y+=w return img ################# # TRIANGULATION # #################
Example #11
Source File: show_my_ip.py From unicorn-hat-hd with MIT License | 6 votes |
def create_image_from_text(in_text): colours = (255, 255, 250) font_file = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf' font_size = 12 font = ImageFont.truetype(font_file, font_size) w, h = font.getsize(in_text) text_x, text_y = width, 0 text_width, text_height = width, 0 text_width += w + width # add some padding so the ip scrolls off the unicorn hat text_height = max(text_height, h, 16) # no more than the size of the unicorn hat image = Image.new('RGB', (text_width, text_height), (0, 0, 0)) draw = ImageDraw.Draw(image) draw.text((text_x, text_y), in_text, colours, font=font) return (image, text_width) # DISPLAY
Example #12
Source File: utils.py From PythonHomework with MIT License | 6 votes |
def draw_text( img: Image, text: str, location: tuple = (0, 0), text_color=(0, 0, 0) ) -> Image: draw = ImageDraw.Draw(img) try: # For Linux font = ImageFont.truetype("DejaVuSans.ttf", 20) except Exception: logger.warning("No font DejaVuSans; use default instead") # For others font = ImageFont.load_default() draw.text(location, text, font=font, fill=text_color) return img
Example #13
Source File: captcha.py From Jtyoui with MIT License | 6 votes |
def make_photo(self, dir_): """生成验证码 :param dir_: 存放验证码照片的文件夹 """ from PIL import Image # 安装pillow: pip install pillow from PIL import ImageFont from PIL import ImageDraw from PIL import ImageFilter image = Image.new('RGB', (self.width, self.height), (255, 255, 255)) font = ImageFont.truetype('arial.ttf', 36) draw = ImageDraw.Draw(image) for w in range(self.width): for h in range(self.height): draw.point((w, h), fill=self.color1()) for index, t in enumerate(self.flag): draw.text(((self.width - 10) // self.number * index + 10, 10), t, font=font, fill=self.color2()) image = image.filter(ImageFilter.BLUR) image.save(dir_ + sep + ''.join(self.flag) + '.jpg', 'jpeg') return image
Example #14
Source File: trainer.py From StackGAN with MIT License | 6 votes |
def drawCaption(self, img, caption): img_txt = Image.fromarray(img) # get a font fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 50) # get a drawing context d = ImageDraw.Draw(img_txt) # draw text, half opacity d.text((10, 256), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 512), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) if img.shape[0] > 832: d.text((10, 832), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 1088), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) idx = caption.find(' ', 60) if idx == -1: d.text((256, 10), caption, font=fnt, fill=(255, 255, 255, 255)) else: cap1 = caption[:idx] cap2 = caption[idx+1:] d.text((256, 10), cap1, font=fnt, fill=(255, 255, 255, 255)) d.text((256, 60), cap2, font=fnt, fill=(255, 255, 255, 255)) return img_txt
Example #15
Source File: work_vcode.py From TaiwanTrainVerificationCode2text with Apache License 2.0 | 6 votes |
def draw(self, image): fontpath = FONTPATH[ random.sample(range(2),1)[0] ] color = (self.color[0], self.color[1], self.color[2], 255) font = ImageFont.truetype( fontpath , randint(25, 27) * 10) text = Image.new("RGBA", (250, 300), (0, 0, 0, 0)) textdraw = ImageDraw.Draw(text) textdraw.text((0, 0), str(self.number), font=font, fill=color) #textdraw.text((0, 0), 'j', font=font, fill=color) text = text.rotate(self.angle, expand=True) text = text.resize((int(text.size[0] / 10), int(text.size[1] / 10))) base = int(self.priority * (200 / 6)) rand_min = (self.offset - base - 2) if (self.offset - base - 2) >= -15 else -15 rand_min = 0 if self.priority == 0 else rand_min rand_max = (33 - text.size[0]) if self.priority == 5 else (33 - text.size[0] + 10) try: displace = randint(rand_min, rand_max) except: displace = rand_max location = (base + displace, randint(3, 23)) self.next_offset = location[0] + text.size[0] image.paste(text, location, text) # plt.imshow(image)
Example #16
Source File: birds_skip_thought_demo.py From StackGAN with MIT License | 6 votes |
def drawCaption(img, caption): img_txt = Image.fromarray(img) # get a font fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 50) # get a drawing context d = ImageDraw.Draw(img_txt) # draw text, half opacity d.text((10, 256), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 512), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) if img.shape[0] > 832: d.text((10, 832), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 1088), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) idx = caption.find(' ', 60) if idx == -1: d.text((256, 10), caption, font=fnt, fill=(255, 255, 255, 255)) else: cap1 = caption[:idx] cap2 = caption[idx+1:] d.text((256, 10), cap1, font=fnt, fill=(255, 255, 255, 255)) d.text((256, 60), cap2, font=fnt, fill=(255, 255, 255, 255)) return img_txt
Example #17
Source File: util.py From bnn with MIT License | 6 votes |
def debug_img(img, bitmap, logistic_output): # create a debug image with three columns; 1) original RGB. 2) black/white # bitmap of labels 3) black/white bitmap of predictions (with centroids coloured # red. h, w, _channels = bitmap.shape canvas = Image.new('RGB', (w*3, h), (50, 50, 50)) # original input image on left img = zero_centered_array_to_pil_image(img) img = img.resize((w, h)) canvas.paste(img, (0, 0)) # label bitmap in center canvas.paste(bitmap_to_pil_image(bitmap), (w, 0)) # logistic output on right canvas.paste(bitmap_to_pil_image(logistic_output), (w*2, 0)) # draw red dots on right hand side image corresponding to # final thresholded prediction draw = ImageDraw.Draw(canvas) for y, x in centroids_of_connected_components(logistic_output): draw.rectangle((w*2+x,y,w*2+x,y), fill='red') # finally draw blue lines between the three to delimit boundaries draw.line([w,0,w,h], fill='blue') draw.line([2*w,0,2*w,h], fill='blue') draw.line([3*w,0,3*w,h], fill='blue') # done return canvas
Example #18
Source File: OP_1_Connection.py From OP_Manager with MIT License | 5 votes |
def unmount_OP_1(): if getMountPath("OP1") != "": unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((30, 25), "Ejecting!", font=getFont(), fill='white') displayImage(unmountDisplay) unmountdevice(config["OP_1_Mounted_Dir"]) config["OP_1_Mounted_Dir"] = "" config["USB_Mount_Path"] = "" unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((30, 25), "Ejected", font=getFont(), fill='white') displayImage(unmountDisplay) time.sleep(1) return True elif os.path.isdir(config["OP_Z_Mounted_Dir"]): unmountdevice(config["OP_Z_Mounted_Dir"]) unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((15, 25), "Ejected", font=getFont(), fill='white') displayImage(unmountDisplay) time.sleep(1) return True else: unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((15, 25), "No Device to Eject", font=getFont(), fill='white') displayImage(unmountDisplay) time.sleep(1) return False # ============= OP1 Helper tools =================
Example #19
Source File: test_instance_seg.py From seamseg with BSD 3-Clause "New" or "Revised" License | 5 votes |
def save_prediction_image(raw_pred, img_info, out_dir, colors, num_stuff, threshold): bbx_pred, cls_pred, obj_pred, msk_pred = raw_pred img = Image.open(img_info["abs_path"]) draw = ImageDraw.Draw(img) # 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") # Rescale bounding boxes scale_factor = [os / bs for os, bs in zip(img_info["original_size"], img_info["batch_size"])] bbx_pred[:, [0, 2]] = bbx_pred[:, [0, 2]] * scale_factor[0] bbx_pred[:, [1, 3]] = bbx_pred[:, [1, 3]] * scale_factor[1] # Expand masks bbx_inv = invert_roi_bbx(bbx_pred, list(msk_pred.shape[-2:]), list(img_info["original_size"])) bbx_idx = torch.arange(0, msk_pred.size(0), dtype=torch.long) msk_pred = roi_sampling( msk_pred.cpu().unsqueeze(1).sigmoid(), bbx_inv.cpu(), bbx_idx, list(img_info["original_size"]), padding="zero") msk_pred = msk_pred.squeeze(1) > 0.5 for bbx_pred_i, cls_pred_i, obj_pred_i, msk_pred_i in zip(bbx_pred, cls_pred, obj_pred, msk_pred): color = colors[cls_pred_i.item() + num_stuff] if obj_pred_i.item() > threshold: msk = Image.fromarray(msk_pred_i.numpy() * 192) draw.bitmap((0, 0), msk, tuple(color)) draw.rectangle(( bbx_pred_i[1].item(), bbx_pred_i[0].item(), bbx_pred_i[3].item(), bbx_pred_i[2].item(), ), outline=tuple(color), width=3) img.convert(mode="RGB").save(out_path)
Example #20
Source File: util.py From bnn with MIT License | 5 votes |
def red_dots(rgb, centroids): img = zero_centered_array_to_pil_image(rgb) canvas = ImageDraw.Draw(img) for y, x in centroids: # recall: x/y flipped between db & pil canvas.rectangle((x-2,y-2,x+2,y+2), fill='red') return img
Example #21
Source File: gradient.py From wallgen with MIT License | 5 votes |
def NbyNGradient(side): base_color = "#00ffff" img = Image.new("RGB", (side,side), base_color) draw = ImageDraw.Draw(img) n_boxes = 5 boxes_size = side//n_boxes xmin, xmax = 0, boxes_size ymin, ymax = 0, boxes_size for i in range(n_boxes): for j in range(n_boxes): r, g, b = [randint(0, 255),randint(0, 255), randint(0, 255)] dr = (randint(0, 255) - r)/boxes_size dg = (randint(0, 255) - g)/boxes_size db = (randint(0, 255) - b)/boxes_size for k in range(xmin, xmax): draw.line([k, ymin, k, ymax], fill=(int(r), int(g), int(b))) r += dr g += dg b += db xmin += boxes_size xmax += boxes_size xmin = 0 xmax = boxes_size ymin += boxes_size ymax += boxes_size img = img.filter(ImageFilter.GaussianBlur(radius=boxes_size//n_boxes)) return img
Example #22
Source File: vis_utils.py From CornerNet-Lite-Pytorch with BSD 3-Clause "New" or "Revised" License | 5 votes |
def change_cv2_draw(image,strs,local,sizes,colour): cv2img = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) pilimg = Image.fromarray(cv2img) draw = ImageDraw.Draw(pilimg) font = ImageFont.truetype("./core/font_lib/Microsoft-Yahei-UI-Light.ttc",sizes,encoding='utf-8') draw.text(local,strs,colour,font=font) image = cv2.cvtColor(np.array(pilimg),cv2.COLOR_RGB2BGR) return image
Example #23
Source File: label_ui.py From bnn with MIT License | 5 votes |
def display_new_image(self): img_name = self.files[self.file_idx] # Display image (with filename added) title = img_name + " " + str(self.file_idx) + " of " + str(len(self.files)-1) img = Image.open(self.img_dir + "/" + img_name) canvas = ImageDraw.Draw(img) canvas.text((0,0), title, fill='black') self.tk_img = ImageTk.PhotoImage(img) self.canvas.create_image(0,0, image=self.tk_img, anchor=tk.NW) # Look up any existing bees in DB for this image. existing_labels = self.label_db.get_labels(img_name) for x, y in existing_labels: self.add_bee_at(x, y)
Example #24
Source File: interactive.py From rpi_epd2in7 with MIT License | 5 votes |
def main(): print("initializing...") epd = EPD() epd.init() image = Image.new('1', (epd.width, epd.height), 255) draw = ImageDraw.Draw(image) font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 18) draw.text((0, 5), 'Interactive demo', font=font, fill=0) font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 16) epd.display_frame(image) loc = 25 full_update = False print("Ready.") try: while True: text = input("> ") if loc > epd.height - 10: loc = 0 image = Image.new('1', (epd.width, epd.height), 255) draw = ImageDraw.Draw(image) full_update = True draw.text((5, loc), text, font=font, fill=0) if full_update: print("Doing a full update...") epd.display_frame(image) full_update = False else: print("...") epd.display_partial_frame(image, 0, loc, 20, epd.width, fast=True) loc += 20 except KeyboardInterrupt: epd.sleep() print("Bye!") raise
Example #25
Source File: Midi.py From OP_Manager with MIT License | 5 votes |
def _showParamAdjust(self, title="", message=""): self.in_Midi_tool_screen_flag = True image = Image.new('1', (128, 64)) draw = ImageDraw.Draw(image) draw.rectangle(((0, 0), (128, 64)), 'black') draw.rectangle(((0, 0), (128, 10)), 'white') # Title draw.text((0, 0), str(title), fill='black', font=getFont()) if "\n" in message: draw.text((30, 20), str(message), fill='white', font=getFont()) else: draw.text((30, 30), str(message), fill='white', font=getFont()) displayImage(image) time.sleep(1) self.in_Midi_tool_screen_flag = False
Example #26
Source File: visualization_utils.py From vehicle_counting_tensorflow with MIT License | 5 votes |
def draw_keypoints_on_image(image, keypoints, color='red', radius=2, use_normalized_coordinates=True): """Draws keypoints on an image. Args: image: a PIL.Image object. keypoints: a numpy array with shape [num_keypoints, 2]. color: color to draw the keypoints with. Default is red. radius: keypoint radius. Default value is 2. use_normalized_coordinates: if True (default), treat keypoint values as relative to the image. Otherwise treat them as absolute. """ draw = ImageDraw.Draw(image) im_width, im_height = image.size keypoints_x = [k[1] for k in keypoints] keypoints_y = [k[0] for k in keypoints] if use_normalized_coordinates: keypoints_x = tuple([im_width * x for x in keypoints_x]) keypoints_y = tuple([im_height * y for y in keypoints_y]) for keypoint_x, keypoint_y in zip(keypoints_x, keypoints_y): draw.ellipse([(keypoint_x - radius, keypoint_y - radius), (keypoint_x + radius, keypoint_y + radius)], outline=color, fill=color)
Example #27
Source File: visualization_utils.py From vehicle_counting_tensorflow with MIT License | 5 votes |
def draw_keypoints_on_image(image, keypoints, color='red', radius=2, use_normalized_coordinates=True): """Draws keypoints on an image. Args: image: a PIL.Image object. keypoints: a numpy array with shape [num_keypoints, 2]. color: color to draw the keypoints with. Default is red. radius: keypoint radius. Default value is 2. use_normalized_coordinates: if True (default), treat keypoint values as relative to the image. Otherwise treat them as absolute. """ draw = ImageDraw.Draw(image) im_width, im_height = image.size keypoints_x = [k[1] for k in keypoints] keypoints_y = [k[0] for k in keypoints] if use_normalized_coordinates: keypoints_x = tuple([im_width * x for x in keypoints_x]) keypoints_y = tuple([im_height * y for y in keypoints_y]) for keypoint_x, keypoint_y in zip(keypoints_x, keypoints_y): draw.ellipse([(keypoint_x - radius, keypoint_y - radius), (keypoint_x + radius, keypoint_y + radius)], outline=color, fill=color)
Example #28
Source File: pi-timolo.py From pi-timolo with MIT License | 5 votes |
def writeTextToImage(imagename, datetoprint, daymode): # function to write date/time stamp directly on top or bottom of images. if showTextWhite: FOREGROUND = ( 255, 255, 255 ) # rgb settings for white text foreground textColour = "White" else: FOREGROUND = ( 0, 0, 0 ) # rgb settings for black text foreground textColour = "Black" if showTextWhiteNight and ( not daymode): FOREGROUND = ( 255, 255, 255 ) # rgb settings for black text foreground textColour = "White" # centre text and compensate for graphics text being wider x = int((imageWidth/2) - (len(imagename)*2)) if showTextBottom: y = (imageHeight - 50) # show text at bottom of image else: y = 10 # show text at top of image TEXT = imageNamePrefix + datetoprint font_path = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf' font = ImageFont.truetype(font_path, showTextFontSize, encoding='unic') text = TEXT.decode('utf-8') # Read exif data since ImageDraw does not save this metadata img = Image.open(imagename) metadata = pyexiv2.ImageMetadata(imagename) metadata.read() draw = ImageDraw.Draw(img) # draw.text((x, y),"Sample Text",(r,g,b)) draw.text(( x, y ), text, FOREGROUND, font=font) img.save(imagename) metadata.write() # Write previously saved exif data to image file logging.info("Added %s Text [ %s ]", textColour, datetoprint) logging.info("%s" % imagename) #-----------------------------------------------------------------------------------------------
Example #29
Source File: Midi.py From OP_Manager with MIT License | 5 votes |
def _showCurrentConnectedDevice(self): if not self.in_Midi_tool_screen_flag: image = Image.new('1', (128, 64)) image.paste(Image.open(workDir + "/Assets/Img/Midi.png").convert("1")) draw = ImageDraw.Draw(image) if batteryConfig["enable"]: # Battery Level in percentage # draw.text((105, 0), readCapacity(), fill='black', font=self.smallFont) # Battery Level Icon icon = Image.open(os.path.join(workDir, getBatteryImagePath(readCapacity()))).convert("L") inverted_image = ImageOps.invert(icon) image.paste(inverted_image, (117, 0)) if self.in_out_device_selector_flag == 1: # Top Device Highlighted draw.rectangle(((15, 5), (120, 15)), 'white') draw.text((20, 5), str(self._strip_Midi_Name(self.currentInDevice, maxLen=16)), fill='black', font=getFont()) else: draw.text((20, 5), str(self._strip_Midi_Name(self.currentInDevice, maxLen=16)), fill='white', font=getFont()) if self.in_out_device_selector_flag == -1: # Bottom Device Highlighted draw.rectangle(((15, 50), (120, 60)), 'white') draw.text((20, 50), str(self._strip_Midi_Name(self.currentOutDevice, maxLen=16)), fill='black', font=getFont()) else: draw.text((20, 50), str(self._strip_Midi_Name(self.currentOutDevice, maxLen=16)), fill='white', font=getFont()) displayImage(image)
Example #30
Source File: file_util.py From OP_Manager with MIT License | 5 votes |
def fileTransferHelper(srclist, dest): """ Pass in list of paths to file, and copy to root destination It will create patch's parent folder if not already exist in the destination folder For example: fileTransferHelper(["..../OP1_File_Organizer/NotUsed/..../patch.aif"], dest = "/..../synth") :param srclist: ["pwd/1.aif", "pwd/2.aif", "pwd/3.aif",....., "pwd/n.aif"] :param dest: Root of the synth and drum destination folder :return: NA """ for i in srclist: srcParentFolderName = abspath(join(i, pardir)).split("/")[-1:][0] srcBaseName = basename(i) distParentFolderName = dest + "/" + str(srcParentFolderName) print(distParentFolderName) forcedir(distParentFolderName) image = Image.new('1', (128, 64)) if workDir in srclist[0]: # Local to OP1 image.paste(Image.open(workDir + "/Assets/Img/UploadPatches.png").convert("1")) else: # OP1 to Local image.paste(Image.open(workDir + "/Assets/Img/DownloadPatches.png").convert("1")) draw = ImageDraw.Draw(image) draw.text((20, 63), srcBaseName, font=GPIO_Init.getFont(), fill="white") GPIO_Init.displayImage(image) print(i, distParentFolderName + "/" + srcBaseName) shutil.copy2(i, distParentFolderName + "/" + srcBaseName) GPIO_Init.displayPng(workDir + "/Assets/Img/Done.png") GPIO_Init.getAnyKeyEvent() # Press any key to proceed return