我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PIL.ImageDraw.Draw()。
def generate_img(output="", theme={}, text="", resolution=(1920,1080)): # img = Image.open(backdrop) img = Image.new("RGB", resolution, theme["background"]) W, H = img.size logo = Image.open(DEFAULT_DIR+"/assets/logo.png") colorized_img = ImageOps.colorize(logo.convert("L"), theme["text"], theme["background"]) size = int((W/100)*17) logo_newsize = colorized_img.resize((size, size), Image.ANTIALIAS) img.paste(logo_newsize, (int((W-size)/2), int((H-size)/2))) draw = ImageDraw.Draw(img) base_font_pixle = int((56/1920)*resolution[0]) font = ImageFont.truetype("DejaVuSansMono.ttf", base_font_pixle) w, h = font.getsize(text) text_draw(draw, text, base_font_pixle, img.size, theme) img.save(output, quality=100)
def makeglyphs(): for i in range(0, len(C)): im = Image.new("RGB", (100, 110)) dr = ImageDraw.Draw(im) font = ImageFont.truetype(os.path.join(os.path.dirname(__file__),"fonts/Impact.ttf"), 124) dr.text((0, -25), C[i], (255, 255, 255), font=font) fwx = firstwhitex(im) im = Image.new("RGB", (100, 110)) dr = ImageDraw.Draw(im) font = ImageFont.truetype(os.path.join(os.path.dirname(__file__),"fonts/Impact.ttf"), 124) dr.text((-fwx, -26), C[i], (255, 255, 255), font=font) cimgs.append(im) # make threshold image
def draw2d(data,labels,jpeg='mds2d.jpg'): img=Image.new('RGB',(2000,2000),(255,255,255)) draw=ImageDraw.Draw(img) for i in range(len(data)): x=(data[i][0]+0.5)*1000 y=(data[i][1]+0.5)*1000 draw.text((x,y),labels[i],(0,0,0)) img.save(jpeg,'JPEG')
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
def __init__(self, master, text, foreground="black", truetype_font=None, font_path=None, family=None, size=None, **kwargs): if truetype_font is None: if font_path is None: raise ValueError("Font path can't be None") # Initialize font truetype_font = ImageFont.truetype(font_path, size) width, height = truetype_font.getsize(text) image = Image.new("RGBA", (width, height), color=(0,0,0,0)) draw = ImageDraw.Draw(image) draw.text((0, 0), text, font=truetype_font, fill=foreground) self._photoimage = ImageTk.PhotoImage(image) Label.__init__(self, master, image=self._photoimage, **kwargs)
def drawChars(charset, font, char_size): src_font = ImageFont.truetype(font, 150) canvas = Image.new("RGB", (char_size*21, char_size*19), (255, 255, 255)) # 42 -> 21 x_pos = 0 y_pos = 0 for c in charset: e = draw_single_char(c, src_font, char_size, x_offset=50, y_offset=20) canvas.paste(e, (x_pos * char_size, y_pos * char_size)) x_pos = x_pos + 1 if x_pos >= 21: # 42 -> 21 x_pos = 0 y_pos = y_pos + 1 draw = ImageDraw.Draw(canvas) for i in range(20): # 41 -> 20 draw.line([((i+1)*char_size,0), ((i+1)*char_size, char_size*19)], fill = (0, 0, 0), width=5) for i in range(18): draw.line([(0, (i+1)*char_size), (char_size*21, (i+1)*char_size)], fill = (0, 0, 0), width=5) # 42 -> 21 canvas.save("399_image.png")
def avatar_gen_img(self): font_size = int(self.size / 10 * 8) pic_size = self.size an, is_letter = self.avatar_name() font = self.zh_font_file_name if is_letter: font = self.en_font_file_name font_size = int(self.size / 10 * 11) font_file = os.path.abspath(os.path.join(self.font_dir, font)) pygame.init() f = pygame.font.Font(font_file, font_size) is_light=self.is_light_color(self.avatar_background_color()) rtext = f.render(an.upper(), True, (0,0,0) if is_light else (255, 255, 255)) # pygame.image.save(rtext, '%s.png' % an) mode = 'RGBA' astr = pygame.image.tostring(rtext, 'RGBA') circle = Image.new("RGBA", (self.size, self.size)) word = Image.frombytes(mode, f.size(an), astr) word_x = int((pic_size - word.size[0]) / 2) word_y = int(word_x * 0.9) if is_letter: word_y = int((pic_size - word.size[1]) / 2) draw = ImageDraw.Draw(circle) draw.ellipse((0, 0, self.size , self.size ), fill=self.avatar_background_color(), outline=self.avatar_background_color()) draw.point((100, 100), 'red') r, g, b, a = word.split() circle.paste(word, (word_x, word_y), a) sharpness = ImageEnhance.Sharpness(circle) # circle = sharpness.enhance(7.0) # im.show() # circle.show() # print(circle) return circle
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
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
def new_image(self, **kwargs): back_color = kwargs.get("fill_color", "white") fill_color = kwargs.get("back_color", "black") if fill_color.lower() != "black" or back_color.lower() != "white": if back_color.lower() == "transparent": mode = "RGBA" back_color = None else: mode = "RGB" else: mode = "1" img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color) self.fill_color = fill_color self._idr = ImageDraw.Draw(img) return img
def thres(pil_Image): """ Thresholding the image """ w, h = pil_Image.size thim = Image.new("RGB", (w, h)) thdr = ImageDraw.Draw(thim) PX = pil_Image.load() # make threshold image for x in range(0, w): for y in range(0, h): r, g, b = PX[x, y][:3] hsv = rgb2hsv(r, g, b) if hsv[2] > 0.9 and hsv[1] < 0.1: thdr.point([x, y], fill=(0, 0, 0)) else: thdr.point([x, y], fill=(255, 255, 255)) thim.show() return thim
def demo(drm, start): """simple partial update demo - draw random shapes""" # Use a monochrome image to force 0/1 values image = Image.new('1', drm.image.size) # prepare for drawing draw = ImageDraw.Draw(image) width, height = drm.image.size font = ImageFont.truetype(FONT_FILE, FONT_SIZE) counter = start & 0xffff while True: draw.rectangle((0, 0, width, height), fill='black', outline='black') draw.text((0, 0), '{c:04X}'.format(c=counter), fill='white', font=font) counter = (counter + 1) & 0xffff # display image on the panel image.convert('RGBX') drm.image.paste(image) drm.flush() # main
def make_image(text, fontsize=45, output_file='tmp.png', fontname='HamletOrNot.ttf'): """Make an image out of a poem""" # Get font font = ImageFont.truetype(fontname, fontsize * factor) # Compute height num_lines = (1 + text.strip().count('\n')) height = num_lines * font.getsize(text[:10])[1] / factor + 2 * pad # Compute width font_length = max(font.getsize(line)[0] for line in text.split('\n')) width = font_length / factor + 2 * pad # Create big image and draw text image = Image.new("RGBA", (width * factor, height * factor), (241, 241, 212)) draw = ImageDraw.Draw(image) draw.text((pad * factor, pad * factor), text, (0, 0, 0), font=font) # Resize with antialiasing img_resized = image.resize((width, height), Image.ANTIALIAS) # Save to file img_resized.save(output_file)
def blackout(image_result_content, players): '''Given a scoreboard image as bytes and players array, return the a blacked-out scoreboard.''' scoreboard = Image.open(BytesIO(image_result_content)).convert("RGB") draw = ImageDraw.Draw(scoreboard) if "yes" in players: # this shouldn't happen. if it does, let's just not censor anything if players[0] == "no": # is_me is no, so censor draw.polygon([(719, 101), (719, 123), (849, 119), (849, 97)], fill="black") if players[1] == "no": draw.polygon([(721, 151), (721, 173), (851, 169), (851, 147)], fill="black") if players[2] == "no": draw.polygon([(723, 201), (723, 223), (853, 219), (853, 197)], fill="black") if players[3] == "no": draw.polygon([(725, 251), (725, 273), (855, 269), (855, 247)], fill="black") if players[4] == "no": draw.polygon([(725, 379), (725, 401), (855, 406), (855, 384)], fill="black") if players[5] == "no": draw.polygon([(723, 429), (723, 451), (853, 456), (853, 434)], fill="black") if players[6] == "no": draw.polygon([(721, 479), (721, 501), (851, 506), (851, 484)], fill="black") if players[7] == "no": draw.polygon([(719, 529), (719, 551), (849, 556), (849, 534)], fill="black") else: # no "me" - this shouldn't happen. if it does, let's just not censor anything in case pass return scoreboard
def drawSimpleSegment(self): #Drawing module im_Width, im_Height = self.pred_size prediction_image = Image.new("RGB", (im_Width, im_Height) ,(0,0,0)) prediction_imageDraw = ImageDraw.Draw(prediction_image) #BASE all image segmentation for i in range(im_Width): for j in range(im_Height): #get matrix element class(0-149) px_Class = self.predicted_classes[j][i] #assign color from .mat list put_Px_Color = tuple(self.class_colors['colors'][px_Class]) #drawing prediction_imageDraw.point((i,j), fill=put_Px_Color) #Resize to original size and save self.coef, self.h_pad, self.w_pad = self.calculateResize() FullHdOutImage = self.resizeToOutput(prediction_image, self.coef, self.h_pad, self.w_pad) FullHdOutImage = Image.blend(FullHdOutImage, self.im, 0.5) return FullHdOutImage
def main(): global should_draw start = time.time() print('Gathering Data') path, prompt, scores, votes, twowers, twower_count, top_number, elim_number = parse_args() print('Processing Scores') scores = process_votes(votes, scores, path) if should_draw: print('Drawing Image') base = Image.new('RGBA',(1368,1368),color=(255,255,255)) drawer = ImageDraw.Draw(base) prompt, base, drawer, header_height = draw_header(prompt, base, drawer,scores) scores = draw_rankings(scores,top_number,elim_number,twower_count,base,drawer,header_height,twowers) base.save('./twows/{}/results.png'.format(path)) print('Recording Data') write_csv(scores,path) write_history(path) end = time.time() print('Time taken {} seconds'.format(end-start))
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())
def draw_one(imgarr, z_arr): # Note that this clipping makes the visualisation somewhat # misleading, as it incorrectly suggests objects occlude one # another. clipped = np.clip(imgarr.data.cpu().numpy(), 0, 1) img = arr2img(clipped).convert('RGB') draw = ImageDraw.Draw(img) for k, z in enumerate(z_arr): # It would be better to use z_pres to change the opacity of # the bounding boxes, but I couldn't make that work with PIL. # Instead this darkens the color, and skips boxes altogether # when z_pres==0. if z.pres > 0: (x, y), w, h = bounding_box(z, imgarr.size(0)) color = tuple(map(lambda c: int(c * z.pres), colors(k))) draw.rectangle([x, y, x + w, y + h], outline=color) is_relaxed = any(z.pres != math.floor(z.pres) for z in z_arr) fmtstr = '{:.1f}' if is_relaxed else '{:.0f}' draw.text((0, 0), fmtstr.format(sum(z.pres for z in z_arr)), fill='white') return img2arr(img)
def add_label_outline(self, label, outline): """ Save the given label to file. Argument label can be a color or a string Argument outline is list of pairs of (x, y) coordinates of a polygon If the length of outline is less than 2, this does nothing. """ if isinstance(label, str): label = next(c for c, nm in self.names.items() if nm == label) assert(isinstance(label, tuple) and len(label) == 4) # Colors are tuples of 4 ints if len(outline) < 2: return # Already done. im = Image.open(self.current_label) # Draw the polygon draw = ImageDraw.Draw(im) draw.polygon(outline, fill=label) del draw im.save(self.current_label)
def general_image(self, image_format='PNG'): fm_width = self.cleaned_data['width'] fm_height = self.cleaned_data['height'] key = '{}.{}.{}'.format(fm_width, fm_height, image_format) content = cache.get(key) if content is None: image = Image.new('RGB', (fm_width, fm_height), color=122) draw = ImageDraw.Draw(image) text = '{}x{}'.format(fm_width, fm_height) text_width, text_height = draw.textsize(text) if text_width < fm_width and text_height < fm_height: text_top = (fm_height - text_height) // 2 text_left = (fm_width - text_width) // 2 draw.text((text_top, text_left), text, fill=(255, 255, 255)) content = BytesIO() image.save(content, image_format) content.seek(0) cache.set(key, content, 60 * 60) return content
def draw_anchor_batch(pred_dict, image): """ Draw anchors used in the batch for RPN. """ anchors = pred_dict['all_anchors'] targets = pred_dict['rpn_prediction']['rpn_cls_target'] in_batch_idx = targets >= 0 anchors = anchors[in_batch_idx] targets = targets[in_batch_idx] image_pil, draw = get_image_draw(image) for anchor, target in zip(anchors, targets): if target == 1: draw.rectangle( list(anchor), fill=(20, 200, 10, 15), outline=(20, 200, 10, 30)) else: draw.rectangle( list(anchor), fill=(200, 10, 170, 10), outline=(200, 10, 170, 30)) return image_pil
def get_mask(self, fill=1, outline=0): """ Get a mask that is nonzero within the object. :param fill: A color to use on the object's interior :param outline: A color to use on the object's edge (single pixel) :return: A 2D numpy array of uint8 """ if self.type in (TYPE_POLYGON, TYPE_BOUNDING_BOX): (top, left, bottom, right) = self.polygon.bounds() w = right-left h = bottom-top mask = Image.new("I", (w, h)) d = ImageDraw.Draw(mask) d.polygon([(px-left, py-top) for (px, py) in self.polygon.points], fill=fill, outline=outline) del d return np.asarray(mask) else: assert False, "Unhandled Type"
def __init__(self, annotation, nrows=512, ncols=None): super(SingleLayerLabels, self).__init__() self.annotation = annotation assert annotation.imagesize.nrows is not None, "Must know the image size first (see update_image_size)" self.aspect = annotation.imagesize.ncols/float(annotation.imagesize.nrows) self.y_scale = nrows / float(annotation.imagesize.nrows) self.nrows = nrows if ncols is None: self.x_scale = self.y_scale self.ncols = int(self.x_scale*annotation.imagesize.ncols) else: self.x_scale = ncols / float(annotation.imagesize.ncols) self.ncols = ncols self.image = Image.new('L', (self.ncols, self.nrows), LABEL_NEGATIVE) self.artist = ImageDraw.Draw(self.image)
def drawHelper(currentDrawer, parameters=False): global currentPage # Draw a black filled box to clear the image. draw.rectangle((0,0,width,height), outline=0, fill=0) # Call the current drawer if parameters is not False: currentDrawer(parameters) else: currentDrawer() # Display image. disp.image(image) disp.display() currentPage += 1
def update(self, data): map = self.matrix_map size = self._pixelSize img = Image.new("RGB", (self.width * size, self.height * size), None) draw = ImageDraw.Draw(img) for x in range(self.width): for y in range(self.height): if map: i = map[y][x] else: i = x rgb = tuple(data[i * 3:i * 3 + 3]) draw.rectangle([x * size, y * size, x * size + size - 1, y * size + size - 1], rgb, rgb) self._images.append(img) # use ImageMagick to combine and make the gif # convert -delay 25 -loop 0 *.png 0.gif
def get(self): text = self.request.get('t') if len(text) > 200 or len(text.split()) > 20: text = u'? ??? ????????!' res = vzhuh_formatter((u'????, ' + text).upper()) img = Image.open('vzhuh.jpeg') draw = ImageDraw.Draw(img) shift = SHIFT_Y for i in range(len(res['lines'])): font = ImageFont.truetype('Impact.ttf', size=res['font_sizes'][i]) draw.text((SHIFT_X, shift), res['lines'][i], (0,0,0), font=font) shift += res['font_sizes'][i] # Convert a PIL image to a suitable return format. output = StringIO.StringIO() img.save(output, format="jpeg") text_layer = output.getvalue() output.close() self.response.headers['Content-Type'] = 'image/jpeg' self.response.write(text_layer)
def _paint_line_number_bg(self, im): """ Paint the line number background on the image. """ if not self.line_numbers: return if self.line_number_fg is None: return draw = ImageDraw.Draw(im) recth = im.size[-1] rectw = self.image_pad + self.line_number_width - self.line_number_pad draw.rectangle([(0, 0), (rectw, recth)], fill=self.line_number_bg) draw.line([(rectw, 0), (rectw, recth)], fill=self.line_number_fg) del draw
def _showUnavailable(self, width, height, message="STATS UNAVAILABLE"): import PIL.Image as Image import PIL.ImageDraw as ImageDraw import StringIO size = (int(width), int(height)) im = Image.new('RGB', size, 'white') draw = ImageDraw.Draw(im) red = (255,0,0) text_pos = (size[0]/2,size[1]/2) text = message draw.text(text_pos, text, fill=red) del draw output = StringIO.StringIO() im.save(output, 'PNG') del im response = output.getvalue() output.close() return response
def cover_generator(src, starting, ending): urllib.request.urlretrieve(src, "cover.jpg") img = Image.open("cover.jpg") msg = str(starting) + "-" + str(ending) draw = ImageDraw.Draw(img) thefont = ImageFont.truetype("arial.ttf", 75) #Get's the average complementary color of the picutre W, H = (400, 600) img2 = img.resize((1, 1)) redc = 255 - img2.getpixel((0, 0))[0] greebc = 255 - img2.getpixel((0, 0))[1] bluec = 255 - img2.getpixel((0, 0))[2] complementary = (redc, greebc, bluec) w, h = draw.textsize(msg, font=thefont) #Allig's and writes the text draw.text(((W - w) / 2, 2), msg, complementary, font = thefont) img.save("cover.jpg")
def make_icon(self, input="./roomba.png", output="./roomba_mod.png"): #utility function to make roomba icon from generic roomba icon if not HAVE_PIL: #drawing library loaded? self.log.error("PIL module not loaded") return None try: roomba = Image.open(input).convert('RGBA') roomba = roomba.rotate(90, expand=False) roomba = self.make_transparent(roomba) draw_wedge = ImageDraw.Draw(roomba) draw_wedge.pieslice( [(5,0),(roomba.size[0]-5,roomba.size[1])], 175, 185, fill="red", outline="red") roomba.save(output, "PNG") return roomba except Exception as e: self.log.error("ERROR: %s" % e) return None
def draw_vacuum_lines(self, image, old_x_y, x_y, theta, colour="lawngreen"): ''' draw lines on image from old_x_y to x_y reepresenting vacuum coverage, taking into account angle theta (roomba angle). ''' lines = ImageDraw.Draw(image) if x_y != old_x_y: self.log.info("MAP: drawing line: %s, %s" % (old_x_y, x_y)) lines.line([old_x_y, x_y], fill=colour, width=self.roomba_icon.size[0] // 2) #draw circle over roomba vacuum area to give smooth edges. arcbox = [x_y[0]-self.roomba_icon.size[0] // 4, x_y[1]-self.roomba_icon.size[0] // 4, x_y[0]+self.roomba_icon.size[0] // 4, x_y[1]+self.roomba_icon.size[0] // 4] lines.ellipse(arcbox, fill=colour)
def draw_text(self, image, display_text, fnt, pos=(0,0), colour=(0,0,255,255), rotate=False): #draw text - (WARNING old versions of PIL have huge memory leak here!) if display_text is None: return self.log.info("MAP: writing text: pos: %s, text: %s" % (pos, display_text)) if rotate: txt = Image.new('RGBA', (fnt.getsize(display_text)), self.transparent) text = ImageDraw.Draw(txt) # draw text rotated 180 degrees... text.text((0,0), display_text, font=fnt, fill=colour) image.paste(txt.rotate(180-self.angle, expand=True), pos) else: text = ImageDraw.Draw(image) text.text(pos, display_text, font=fnt, fill=colour)
def draw_doge_meme(from_dir, to_dir, font_path, phrases): """ Draw a doge meme, given an image path and text to draw on it. Args: from_dir (str): Directory of template doge image. to_dir (str): Path where to store result, including file name and extension. font_path (str): Directory of font to use. phrases (list[str]): Doge phrases to draw onto image. """ image = Image.open(from_dir) texts = [] for phrase in phrases: new_text = make_drawn_text( image, phrase, font_path, texts ) texts.append(new_text) for text in texts: text.draw(image) image.save(to_dir)
def road_draw(image, highway): im = Image.fromarray(image.astype('uint8')) draw = ImageDraw.Draw(im) fnt = ImageFont.truetype('FreeMono/FreeMonoBold.ttf', 40) shape = image.shape if highway: draw.text((65, 10), "Highway", font=fnt, fill=(255, 255, 0, 255)) draw.ellipse([10, 10, 55, 55], fill=(255, 255, 0, 255), outline=(255, 255, 0, 255)) else: draw.text((65, 10), "small road", font=fnt, fill=(255, 0, 0, 255)) draw.ellipse([10, 10, 55, 55], fill=(255, 0, 0, 255), outline=(255, 0, 0, 255)) return np.array(im).astype('float32')
def draw_bounding_boxes(celeb_objs, file): ''' Draws bounding boxes around all faces in inputted file determined by celeb_objs ''' colors = [] im = Image.open(file) draw = ImageDraw.Draw(im) for i in range(len(celeb_objs)): color = rectangle_colors[i % len(rectangle_colors)] colors.append(color) coords = get_coords_from_ratios(celeb_objs[i].to_dict()['BoundingBox'], im.width, im.height) draw_width_rectangle(draw, coords, color, rectangle_width) del draw file.seek(0) im.save(file, 'PNG') return colors
def updateScreen(self, canvas): """ update the image with a new canvas""" w = canvas.width h = canvas.height img = Image.new('RGB', (w, h)) drw = ImageDraw.Draw(img) for x in xrange(w): for y in xrange(h): col = canvas.getPixel(x, y) drw.point((x,y), fill=(int(col[0]*255), int(col[1]*255), int(col[2]*255))) scl = img.resize( (87, 324), resample=Image.BILINEAR ) self.lampSrc.paste(scl, (55,227)) self.lampImg = ImageTk.PhotoImage(self.lampSrc) self.backgroundLabel.config(image=self.lampImg)
def apply(self, image, scale): d = ImageDraw.Draw(image) bounds = [3, 0, image.width, image.height] def print_line(text_line): text = cozmo.annotate.ImageText(text_line, position=cozmo.annotate.TOP_LEFT, color='lightblue') text.render(d, bounds) TEXT_HEIGHT = 11 bounds[1] += TEXT_HEIGHT robot = self.world.robot # Display the Pose info for the robot pose = robot.pose print_line('Pose: Pos = <%.1f, %.1f, %.1f>' % pose.position.x_y_z) print_line('Pose: Rot quat = <%.1f, %.1f, %.1f, %.1f>' % pose.rotation.q0_q1_q2_q3) print_line('Pose: angle_z = %.1f' % pose.rotation.angle_z.degrees) print_line('Pose: origin_id: %s' % pose.origin_id) # Display the Accelerometer and Gyro data for the robot print_line('Accelmtr: <%.1f, %.1f, %.1f>' % robot.accelerometer.x_y_z) print_line('Gyro: <%.1f, %.1f, %.1f>' % robot.gyro.x_y_z)
def GenerateImage(text, output_path, bgcolor): print "Generating Image for the key: " + text # Create an image with a bg colour and gradient. img = image_util.GenerateRandomKeyImageBackground(MAX_W, MAX_H, bgcolor) draw = ImageDraw.Draw(img) # TODO: Store the font file locally font = ImageFont.truetype("Georgia.ttf", FONT_SIZE) # Get coordinates for drawing text w, h = draw.textsize(text, font=font) x = (MAX_W - w) / 2 y = (MAX_H - h) / 2 # Now add text to the image. # Adding shadows first. draw.text((x - SHADOW_WIDTH, y), text, font=font, fill=SHADOW_COLOR) draw.text((x + SHADOW_WIDTH, y), text, font=font, fill=SHADOW_COLOR) draw.text((x, y - SHADOW_WIDTH), text, font=font, fill=SHADOW_COLOR) draw.text((x, y + SHADOW_WIDTH), text, font=font, fill=SHADOW_COLOR) # Adding text in white. draw.text((x, y), text, fill=TEXT_COLOR, font=font) img.save(output_path)
def GenerateKeyImage(text, output_path, bgcolor): TEXT_COLOR = "white" img = Image.new('RGB', imgsize, bgcolor) draw = ImageDraw.Draw(img) # TODO: Store the font file locally font = ImageFont.truetype("Georgia.ttf", FONT_SIZE) # Get coordinates for drawing text w, h = draw.textsize(text, font=font) x = (MAX_W - w) / 2 y = (MAX_H - h) / 2 # Now add text to the image. # Adding shadows first. draw.text((x - SHADOW_WIDTH, y), text, font=font, fill=SHADOW_COLOR) draw.text((x + SHADOW_WIDTH, y), text, font=font, fill=SHADOW_COLOR) draw.text((x, y - SHADOW_WIDTH), text, font=font, fill=SHADOW_COLOR) draw.text((x, y + SHADOW_WIDTH), text, font=font, fill=SHADOW_COLOR) # Adding text in white. draw.text((x, y), text, fill=TEXT_COLOR, font=font) img.save(output_path)
def test_image(self): img = Image.new('RGB', (32, 16)) draw = ImageDraw.Draw(img) draw.rectangle([0, 0, 7, 15], fill=(255, 0, 0)) pic = webp.WebPPicture.from_pil(img) config = webp.WebPConfig.new(lossless=True) buf = pic.encode(config).buffer() with TemporaryDirectory() as tmpdir: file_name = os.path.join(tmpdir, 'image.webp') with open(file_name, 'wb') as f: f.write(buf) with open(file_name, 'rb') as f: webp_data = webp.WebPData.from_buffer(f.read()) arr = webp_data.decode(color_mode=webp.WebPColorMode.RGB) expected = np.asarray(img, dtype=np.uint8) np.testing.assert_array_equal(arr, expected)
def test_anim_simple_resample(self): width = 256 height = 64 img1 = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(img1) draw.rectangle([0, 0, width-1, height-1], fill=(0, 0, 255)) draw.rectangle([0, 0, (width/4-1), height-1], fill=(255, 0, 0)) img2 = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(img2) draw.rectangle([0, 0, width-1, height-1], fill=(0, 0, 255)) draw.rectangle([0, 0, (width/4-1), height-1], fill=(0, 255, 0)) imgs = [img1, img1, img2, img2] with TemporaryDirectory() as tmpdir: file_name = os.path.join(tmpdir, 'anim.webp') webp.save_images(imgs, file_name, fps=4, lossless=True) dec_imgs = webp.load_images(file_name, 'RGBA', fps=4) self.assertEqual(len(dec_imgs), 4)
def test_image_simple(self): width = 256 height = 64 img = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(img) draw.rectangle([0, 0, width-1, height-1], fill=(0, 0, 255)) draw.rectangle([0, 0, (width/4-1), height-1], fill=(255, 0, 0)) with TemporaryDirectory() as tmpdir: file_name = os.path.join(tmpdir, 'image.webp') webp.save_image(img, file_name, lossless=True) dec_img = webp.load_image(file_name, 'RGB') actual = np.asarray(dec_img, dtype=np.uint8) expected = np.asarray(img, dtype=np.uint8) np.testing.assert_array_equal(actual, expected)
def gen_image(msg, fname, top = True): t_pos = (10, 100) if top: t_pos = (10, 10) font = ImageFont.truetype("Arial.ttf",42) #img = Image.new("RGBA", (500,180),(255,255,255)) rand_array = numpy.random.rand(90, 500, 3) * 255 white_array = numpy.random.rand(90, 500, 3) * 0 if top: full_array = numpy.vstack((rand_array, white_array)) else: full_array = numpy.vstack((white_array, rand_array)) img = Image.fromarray(full_array.astype('uint8')).convert('RGB') draw = ImageDraw.Draw(img) draw.text(t_pos, msg, (255,255,255), font=font) draw = ImageDraw.Draw(img) img.save(fname)
def Draw(lst, n): global color global draw global dim # print(lst) # print(lst[0][0]) # print(str(lst[0][0]).isdigit()) if (str(lst[0][0])).isdigit() or (str((-1) * lst[0][0]).isdigit()): # line(lst[0][0],lst[0][1],lst[1][0],lst[1][1]) draw.line(((lst[0][0] + dim[0] + 150, lst[0][1] + dim[2] + 150), (lst[1][0] + dim[0] + 150, lst[1][1] + dim[2] + 150)), fill=color, width=1) else: print(n) Draw(lst[0], n - 1) Draw(lst[1], n - 1) # t.pencolor(colors[n%6]) color = colors[n % 6] lst1, lst2 = list(flatten(lst[0])), list(flatten(lst[1])) for i in range(0, len(lst1), 2): # line(lst1[i],lst1[i+1],lst2[i],lst2[i+1]) draw.line(((lst1[i] + dim[0] + 150, lst1[i + 1] + dim[2] + 150), (lst2[i] + dim[0] + 150, lst2[i + 1] + dim[2] + 150)), fill=color, width=1)