我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ImageDraw.Draw()。
def gen_captcha(text, fnt, fnt_sz, file_name, fmt='JPEG'): """Generate a captcha image""" # randomly select the foreground color fgcolor = random.randint(0,0xffff00) # make the background color the opposite of fgcolor bgcolor = fgcolor ^ 0xffffff # create a font object font = ImageFont.truetype(fnt,fnt_sz) # determine dimensions of the text dim = font.getsize(text) # create a new image slightly larger that the text im = Image.new('RGB', (dim[0]+5,dim[1]+5), bgcolor) d = ImageDraw.Draw(im) x, y = im.size r = random.randint # draw 100 random colored boxes on the background for num in range(100): d.rectangle((r(0,x),r(0,y),r(0,x),r(0,y)),fill=r(0,0xffffff)) # add the text to the image d.text((3,3), text, font=font, fill=fgcolor) im = im.filter(ImageFilter.EDGE_ENHANCE_MORE) # save the image to a file im.save(file_name, format=fmt)
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 simpleDraw(text,width=100,height=40,bgcolor=(255,255,255)): '''????''' #?????? image = Image.new('RGB',(width,height),bgcolor) #???? font = ImageFont.truetype('FreeSans.ttf',30) #???? fontcolor = (0,0,0) #??draw???draw???????? draw = ImageDraw.Draw(image) #???,(0,0)????? draw.text((0,0),'1234',font=font,fill=fontcolor) #??draw del draw #?????? image.save('1234_1.jpeg')
def init_set(): global canvas_width, canvas_height, white, black, red, master, size, user_close, image1, draw, w, b canvas_width = 560 canvas_height = 560 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) master = Tk() master.title("Draw digit") size = 28, 28 user_close = 0 image1 = Image.new("RGB", (canvas_width, canvas_height), black) draw = ImageDraw.Draw(image1) w = Canvas(master, width=canvas_width, height=canvas_height + 20) b = Button(master, text="Predict", command=call_predict) # Callback function when the user clicks on "Predict" button
def extractFunction(font_loc): white = (255, 255, 255) # use a truetype font font = ImageFont.truetype(font_loc, 280) im = Image.new("RGB", (280, 280), white) draw = ImageDraw.Draw(im) for code in range(ord('a'), ord('z') + 1): w, h = draw.textsize(chr(code), font=font) im = Image.new("RGB", (w, h), white) draw = ImageDraw.Draw(im) draw.text((0, 0), chr(code), font=font, fill="#000000") convert_im(code, im) #im.save(chr(code) + str(time.time()) + ".png") for code in range(ord('A'), ord('Z') + 1): w, h = draw.textsize(chr(code), font=font) im = Image.new("RGB", (w, h), white) draw = ImageDraw.Draw(im) draw.text((0, 0), chr(code), font=font, fill="#000000") convert_im(code, im) #im.save(chr(code) + str(time.time()) + ".png")
def __init__(self): self._image = pilImage.new('RGB', (X, Y), colors[white]) self._draw = ImageDraw.Draw(self._image) for font in 'Tahoma Verdana Arial Helvetica'.split(): try: font = ImageFont.truetype(font + '.ttf', 12) except (AttributeError, IOError): font = None if font: break else: try: font = ImageFont.load_default() except (AttributeError, IOError): font = None self._font = font
def drawHostnameTitle(): size = 30 maxWidth = 320-50-50-5-5 # screen width is 320, each arrow is 50px wide, 5px margin if newMessageExists() or updateNeeded(): maxWidth -= 44 getTextSize = ImageDraw.Draw(scrn.disp.buffer).textsize font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", size) width, height = getTextSize(deviceName, font=font) while (width > maxWidth): size -= 1 font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", size) width, height = getTextSize(deviceName, font=font) scrn.fillRect(55, 0, maxWidth, 50, fill=(0,0,0), display=False) if (newMessageExists() or updateNeeded()) and width > 135: scrn.drawAutoText(deviceName, 60, (50-height)/2-5, fill=(0,255,255), size=size, display=False) else: scrn.drawAutoText(deviceName, 0, (50-height)/2-5, fill=(0,255,255), size=size, display=False, align="center")
def clearScreen(self, display = True): self.disp.clear() if(display): self.disp.display() ## Draw a rectangle on the screen (rotated to screen) # @param self The object pointer. # @param x The upper left x coordinate of the rectangle. # @param y The upper left y coordinate of the rectangle. # @param width The width of the rectangle. # @param height The height of the rectangle. # @param fill The color of inside of the rectangle. Optional, defaults to white. # @param outline The color of the outer edge of the rectangle. Optional, defaults to no outline. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.fillRect(100, 100, 75, 75, fill = (255,0,0), outline = (0,0,0)) # @endcode
def fillCircle(self, x, y, radius, fill = (255,255,255), display = True): draw = self.disp.draw() actx = self.screenXFromImageCoords(x,y) acty = self.screenYFromImageCoords(x,y) draw.ellipse((actx-radius,acty-radius,actx+radius,acty+radius), fill = fill) if(display): self.disp.display() ## Draw a circle on the screen (rotated to screen) # @param self The object pointer. # @param x The center x coordinate of the circle. # @param y The center y coordinate of the circle. # @param radius The radius of the circle. # @param fill The color of the inside of the circle. Optional, defaults to None # @param outline The color of the outer edge of the circle. Optional, defaults to Black # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # red circle with blue outline: # screen.drawCircle(100, 100, 15, fill = (255,0,0), outline=(0,0,255)) # @endcode
def drawCircle(self, x, y, radius, fill = None, outline = (0,0,0), display = True): draw = self.disp.draw() actx = self.screenXFromImageCoords(x,y) acty = self.screenYFromImageCoords(x,y) draw.ellipse((actx-radius,acty-radius,actx+radius,acty+radius), fill=fill, outline=outline) if(display): self.disp.display() ## Draw a bitmap image on the screen (.png files rcommended) # @param self The object pointer. # @param x The upper left x coordinate of the image. # @param y The upper left y coordinate of the image. # @param width The width of the image. # @param height The width of the image. # @param path The image file path. Optional, defaults to the popup background image. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.screen.fillBmp(30, 0, 240, 240, path = os.path.join(currentdir, "dog.png")) # @endcode
def refreshLine(self, lineNum, display = True): if(self.currentMode == self.PS_MODE_TERMINAL): self.drawAutoText(self.terminalBuffer[lineNum], 10, lineNum*20 + 40, (255,255,255), display = display) ## Draw a labeled button on the screen (INTERNAL USE ONLY) # @param self The object pointer. # @param x The upper left x coordinate of the rectangle. # @param y The upper left y coordinate of the rectangle. # @param width The width of the button. # @param height The height of the button. # @param prefix The button images filename prefix. Optional, defaults to "btns_" # @param text The button label. Defaults to "OK" # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @param align The alignment for the button's text label. # @param image An optional image to be included on the button, should be 32x32. # @param imageX The x-coordinate of the optional image icon. # @param imageY The y-coordinate of the optional image icon.
def drawLine(self, x1, y1, x2, y2, width = 0, fill = (255,255,255), display = True): draw = self.disp.draw() actx1 = self.screenXFromImageCoords(x1,y1) acty1 = self.screenYFromImageCoords(x1,y1) actx2 = self.screenXFromImageCoords(x2,y2) acty2 = self.screenYFromImageCoords(x2,y2) draw.line((actx1,acty1,actx2,acty2), fill = fill, width = width) if(display): self.disp.display() ## Draw a polyline on the screen (rotated to screen) # @param self The object pointer. # @param endpoints [x1, y1, x2, y2...] The x and y coordinates of each endpoint of the polyline. # @param width The width of the polyline. Optional, defaults to 0. # @param fill The color of polyline. Optional, defaults to white. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.drawLine([50, 50, 100, 50, 100, 100], width = 0, fill = (255,0,0)) # @endcode
def pil_render(data,height,width,fname="bs.png"): import Image, ImageDraw img = Image.new("RGB",(width,height),(255,255,255)) draw = ImageDraw.Draw(img) for y in range(height): for x in range(width): if data[y][x]: draw.point((x,y),(0,0,0)) img.save(fname,"PNG") return
def pil_render_lines(lines,height=300,width=300,fname="bs.png"): import Image,ImageDraw img = Image.new("RGB",(width,height),(255,255,255)) draw = ImageDraw.Draw(img) for line in lines: draw.line(line,(0,0,0)) img.save(fname,"PNG") #os.system("display %s" % fname) # use ImageMagick to display return
def displayCalibrationMsg(): textImage = Image.new('1', (width,height)) draw = ImageDraw.Draw(textImage) draw.text((x, top), 'Hello World!', font=smallFont, fill=255) draw.text((x, top + 25), 'Calibrating...', font=smallFont, fill=255) disp.image(textImage) disp.display()
def displayReadyToBrew(): textImage = Image.new('1', (width,height)) draw = ImageDraw.Draw(textImage) draw.text((x, top), 'Ready', font=smallFont, fill=255) draw.text((x, top + 25), 'to brew.', font=smallFont, fill=255) disp.image(textImage) disp.display()
def displayTimer(): currentTime = time.time() - start h, rem = divmod(currentTime, 3600) m, s = divmod(rem, 60) textImage = Image.new('1', (width,height)) draw = ImageDraw.Draw(textImage) draw.rectangle((0,0,width,height), outline=0, fill=0) draw.text((x, top),"{:0>2}:{:02.0f}".format(int(m), s), font=font, fill=255) disp.image(textImage) disp.display()
def displayPressing(): textImage = Image.new('1', (width,height)) draw = ImageDraw.Draw(textImage) draw.text((x, top), 'Pressing...', font=smallFont, fill=255) disp.image(textImage) disp.display()
def draw_label(self, image, label): img_shape = np.shape(image) mask = label[:, :, 0] locations = np.where(mask > 0) img = Image.fromarray(image) drawobj = ImageDraw.Draw(img) #print mask for [i, j] in zip(locations[0], locations[1]): l = label[i][j][:] yolo_box = l[1:5] x = yolo_box[0] y = yolo_box[1] w = yolo_box[2] h = yolo_box[3] width = w*img_shape[1] height = h*img_shape[0] xmin = int(x*img_shape[1] - 0.5*width) ymin = int(y*img_shape[0] - 0.5*height) xmax = int(xmin+width) ymax = int(ymin+height) drawobj.rectangle([xmin, ymin, xmax, ymax], outline="blue") drawobj.point([0.5*(xmin+xmax), 0.5*(ymin+ymax)]) for k in range(0, 7): drawobj.line([448/7.0*k, 0, 448/7.0*k, 448]) drawobj.line([0, 448 / 7.0 * k, 448, 448 / 7.0 * k]) #print label[i][j] img.show()
def case1(): h = 60 w = h * 4 image = Image.new('RGB', (w, h), (255, 255, 0)) fonts = ImageFont.truetype("arial.ttf", 36) draw = ImageDraw.Draw(image) for x in range(w): for y in range(h): draw.point((x, y), fill=rndcolor()) for t in range(4): # draw.text((60*t+10,10),rndchar(),font=fonts,fill=rndcolor2()) draw.text((60 * t + 10, 10), rndchar(), font=fonts, fill=rndcolor2()) image = image.filter(ImageFilter.BLUR) image.save("data/1.jpg", 'jpeg')
def draw_text_with_halo(img, position, text, font, col, halo_col): halo = Image.new('RGBA', img.size, (0, 0, 0, 0)) ImageDraw.Draw(halo).text(position, text, font = font, fill = halo_col) blurred_halo = halo.filter(ImageFilter.BLUR) ImageDraw.Draw(blurred_halo).text(position, text, font = font, fill = col) return Image.composite(img, blurred_halo, ImageChops.invert(blurred_halo))
def render_action_to_png(step, action): import Image, ImageDraw img = Image.new('RGB', (50, 50), (50, 50, 50)) canvas = ImageDraw.Draw(img) lx, ly = int(25+(action[0][0]*25)), int(25+(action[0][1]*25)) canvas.line((25,25, lx,ly), fill="black") img.save("/tmp/action_%03d.png" % step)
def literally_show(self, airport_code): display = Matrix16x8.Matrix16x8() display.begin() display.set_brightness(4) font = ImageFont.truetype(os.path.join(os.path.dirname(__file__), 'thintel/Thintel.ttf'), 15) if len(airport_code) == 4: image = Image.new('1', (21, 8)) draw = ImageDraw.Draw(image) blankimage = Image.new('1', (16, 8)) blankdraw = ImageDraw.Draw(blankimage) blankdraw.text((0, 0), '', fill=255) for i in xrange(58): n = 5 - abs((i % 12) - 5) draw.text((0, 0), airport_code, font=font, fill=255) display.set_image(blankimage) display.write_display() display.set_image(image.crop((n, 0, n + 16, 8))) display.write_display() sleep( 0.5 if i > 0 else 3) elif len(airport_code) == 3 or len(airport_code) == 0: image = Image.new('1', (16, 8)) draw = ImageDraw.Draw(image) draw.text((0, 0), airport_code, font=font, fill=255) display.set_image(image) display.write_display()
def _create_hmap(self, matrix): size = (len(matrix[0]) * self.bsize, len(matrix) * self.bsize) red_lightness = self._get_lightness([ x for i in xrange(len(matrix)) for x in matrix[i] if x >= 0 ]) green_lightness = self._get_lightness([ x for i in xrange(len(matrix)) for x in matrix[i] if x < 0 ]) im = Image.new('RGBA', size, 'white') draw = ImageDraw.Draw(im) for row in xrange(len(matrix)): for col in xrange(len(matrix[row])): if matrix[row][col] < 0: colour = (0,int(abs(matrix[row][col]) * green_lightness),0) else: colour = (int(matrix[row][col] * red_lightness),0,0) col_size = col * self.bsize row_size = row * self.bsize bcol_size = self.bsize + col_size brow_size = self.bsize + row_size draw.polygon([(col_size, row_size), (bcol_size, row_size), (bcol_size, brow_size), (col_size, brow_size)], outline='black', fill=colour) return im
def _draw_rectangle(self, img, xy): """Draw a black rectangle. @param img: PIL Image object @param xy: Coordinates as refined in PIL rectangle() doc @return: Image with black rectangle """ dr = ImageDraw.Draw(img) dr.rectangle(xy, fill="black", outline="black") return img
def equal(self, img1, img2, skip_area=None): """Compares two screenshots using Root-Mean-Square Difference (RMS). @param img1: screenshot to compare. @param img2: screenshot to compare. @return: equal status. """ if not HAVE_PIL: return None # Trick to avoid getting a lot of screen shots only because the time in the windows # clock is changed. # We draw a black rectangle on the coordinates where the clock is locates, and then # run the comparison. # NOTE: the coordinates are changing with VM screen resolution. if skip_area: # Copying objects to draw in another object. img1 = img1.copy() img2 = img2.copy() # Draw a rectangle to cover windows clock. for img in (img1, img2): self._draw_rectangle(img, skip_area) # To get a measure of how similar two images are, we use # root-mean-square (RMS). If the images are exactly identical, # this value is zero. diff = ImageChops.difference(img1, img2) h = diff.histogram() sq = (value * ((idx % 256)**2) for idx, value in enumerate(h)) sum_of_squares = sum(sq) rms = math.sqrt(sum_of_squares/float(img1.size[0] * img1.size[1])) # Might need to tweak the threshold. return rms < 8
def render(self, stream, value): im = self.im.copy() im2 = self.im.copy() x = 0 r_i = sum(ord(c) for c in value) # ???????????????? for c in value: fgimg = Image.new('RGBA', self.size, self.font_color) charimg = Image.new('L', self.font.getsize(c), '#000000') draw = ImageDraw.Draw(charimg) draw.text((0, 0), c, font=self.font, fill='#ffffff') r = (int(time()) / 1000 + ord(c) + r_i) % 40 - 20 # ??????????????? charimg = charimg.rotate(r, expand=1, resample=Image.BICUBIC) charimg = charimg.crop(charimg.getbbox()) maskimg = Image.new('L', self.size) y = (im2.size[1] - charimg.size[1]) / 2 maskimg.paste(charimg, (x, y, charimg.size[0] + x, charimg.size[1] + y)) im2 = Image.composite(fgimg, im2, maskimg) x += charimg.size[0] - 5 # - X??? # ??????? x ?? center = (im.size[0] - x) / 2 im.paste(im2, (center, 0, im2.size[0]+center, im2.size[1])) im.save(stream, self.image_type)
def create_image(mode='RGB', size=(800, 600)): image = Image.new(mode, size, (255, 255, 255)) draw = ImageDraw.Draw(image) x_bit, y_bit = size[0] // 10, size[1] // 10 draw.rectangle((x_bit, y_bit * 2, x_bit * 7, y_bit * 3), 'red') draw.rectangle((x_bit * 2, y_bit, x_bit * 3, y_bit * 8), 'red') return image
def cloud_maker(cls): image_size = (220, 140) img = Image.new('RGBA', image_size) draw = ImageDraw.Draw(img) cls.draw_cloud(draw) del draw return cls.crop_image(img)
def __init__(self, image, size=None, color=None): if not hasattr(image, "im"): image = Image.new(image, size, color) self.draw = ImageDraw.Draw(image) self.image = image self.transform = None
def new_image(self, **kwargs): img = Image.new("1", (self.pixel_size, self.pixel_size), "white") self._idr = ImageDraw.Draw(img) return img
def oled(bir,iki,ucst=""): # Draw a black filled box to clear the image. draw.rectangle((0,0,width,height), outline=0, fill=0) draw.text((x, top),str(bir), font=font1, fill=255) draw.text((x, top+20),str(iki), font=font2, fill=255) draw.text((x, top+40),str(ucst), font=font2, fill=255) disp.image(image) disp.display()
def draw_image(pic_name, boxes, namelist_file): name_list = get_names_from_file(namelist_file) color_list = get_color_from_file('ink.color') im = Image.open(pic_name) draw = ImageDraw.Draw(im) lena = mpimg.imread(pic_name) height, width = lena.shape[:2] for box in boxes: x = box.rect.corner.x y = box.rect.corner.y w = box.rect.width h = box.rect.height left = (x - w / 2) * width right = (x + w / 2) * width top = (y - h / 2) * height bot = (y + h / 2) * height if left < 0: left = 0 if right > width - 1: right = width - 1 if top < 0: top = 0 if bot > height - 1: bot = height - 1 category = name_list[box.category] color = color_list[box.category % color_list.__len__()] draw.line((left, top, right, top), fill=color, width=5) draw.line((right, top, right, bot), fill=color, width=5) draw.line((left, top, left, bot), fill=color, width=5) draw.line((left, bot, right, bot), fill=color, width=5) font_size = 20 my_font = ImageFont.truetype("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-M.ttf", size=font_size) draw.text([left + 5, top], category, font=my_font, fill=color) im.show()
def drawText(cimg, txt, posxy, fz): ttFont0 = ImageFont.truetype(fontfile, fz) im = Image.fromarray(cimg, 'RGB') drawable = ImageDraw.Draw(im) drawable.text ((posxy[0], posxy[1]), txt, fill=(0, 255, 0), font=ttFont0) npimg = np.asarray(im) return npimg
def drawText_Color(cimg, txt, posxy, fz, color): ttFont0 = ImageFont.truetype(fontfile, fz) im = Image.fromarray(cimg, 'RGB') drawable = ImageDraw.Draw(im) drawable.text((posxy[0], posxy[1]), txt, fill=color, font=ttFont0) npimg = np.asarray(im) return npimg
def drawText_BKG(cimg, txt, posxy, fz, bkglen): ttFont0 = ImageFont.truetype(fontfile, fz) im = Image.fromarray(cimg, 'RGB') drawable = ImageDraw.Draw(im) drawable.polygon(((posxy[0], posxy[1]), \ (posxy[0]+bkglen, posxy[1]), \ (posxy[0]+bkglen, posxy[1]+fz), \ (posxy[0], posxy[1]+fz)), fill=(255, 255, 255)) drawable.text ((posxy[0], posxy[1]), txt, fill=(0, 0, 255), font=ttFont0) npimg = np.asarray(im) return npimg
def getMode(self): return self.currentMode ## Draw a rectangle with rounded edges on the screen (rotated to screen) # @param self The object pointer. # @param x The upper left x coordinate of the rectangle. # @param y The upper left y coordinate of the rectangle. # @param width The width of the rectangle. # @param height The height of the rectangle. # @param radius The arc of the rectangle corners. # @param fill The color of the inside of the rectangle. Optional, defaults to white. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True.
def draw_rotated_text(self, image, text, position, angle, font, fill=(255,255,255), display = True): draw = ImageDraw.Draw(image) width, height = draw.textsize(text, font=font) textimage = Image.new('RGBA', (width, height), (0,0,0,0)) textdraw = ImageDraw.Draw(textimage) textdraw.text((0,0), text, font=font, fill=fill) if angle == - 90: textimage = textimage.transpose(Image.ROTATE_270) if angle == -180: textimage = textimage.transpose(Image.ROTATE_180) if angle == -270: textimage = textimage.transpose(Image.ROTATE_90) image.paste(textimage, position, textimage) if(display): self.disp.display() ## Determines the width of the screen based on rotation (Experienced users) # @param self The object pointer.
def drawDisplay(self, name, display = True): self.drawAutoText(name, 0, 5, fill = (0,255,255), size = 30, display = display, align="center") ## Draw forward and back arrows on the screen # @param self The object pointer. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True.
def getImage(self, value, height = 50, extension = "PNG"): """ Get an image with PIL library value code barre value height height in pixel of the bar code extension image file extension""" import Image, ImageFont, ImageDraw from string import lower, upper # Create a missing font file decodeFontFile(courB08_pil ,"courB08.pil") decodeFontFile(courB08_pbm ,"courB08.pbm") # Get the bar code list bits = self.makeCode(value) # Get thee bar code with the checksum added code = "" for digit in self.EAN13: code += "%d"%digit # Create a new image position = 8 im = Image.new("1",(len(bits)+position,height)) # Load font font = ImageFont.load("courB08.pil") # Create drawer draw = ImageDraw.Draw(im) # Erase image draw.rectangle(((0,0),(im.size[0],im.size[1])),fill=256) # Draw first part of number draw.text((0, height-9), code[0], font=font, fill=0) # Draw first part of number draw.text((position+7, height-9), code[1:7], font=font, fill=0) # Draw second part of number draw.text((len(bits)/2+6+position, height-9), code[7:], font=font, fill=0) # Draw the bar codes for bit in range(len(bits)): # Draw normal bar if bits[bit] == '1': draw.rectangle(((bit+position,0),(bit+position,height-10)),fill=0) # Draw long bar elif bits[bit] == 'L': draw.rectangle(((bit+position,0),(bit+position,height-3)),fill=0) # Save the result image im.save(code+"."+lower(extension), upper(extension))
def generate_letter(contrast_energy = .01, #michelson contrast energy noise = 30., bg_luminance = 128., letter = "a", letter_size = 400): N = 300 #size of image in pixels #first figure out what is the ink-area of the letter font = ImageFont.truetype("Data/arial.ttf", letter_size) #we copy the .ttf file to the local directory to avoid problems im_temp = Image.new("1", (1,1), 0) draw = ImageDraw.Draw(im_temp) #now we can draw on this sz = draw.textsize(letter, font=font) #this tells us the size of the letter im_temp = Image.new("1", sz, 0) #this is a temporary binary image created solely for the purpose of computing #the ink-area of the letter draw = ImageDraw.Draw(im_temp) #now we can draw on this draw.text((0,0), letter, font=font, fill=1) pix = im_temp.load() #pix is now an addressable array of pixel values area_in_pixels = 0. for row in xrange(sz[0]): for col in xrange(sz[1]): area_in_pixels += pix[row,col] #since contrast_energy = contrast^2 * pixel_area contrast = (contrast_energy/area_in_pixels)**0.5 fg_luminance = bg_luminance*(1+contrast)/(1-contrast) print area_in_pixels print contrast print fg_luminance im = Image.new("L", (N,N), bg_luminance) #im is now a NxN luminance image with luminance set to bg_luminance draw = ImageDraw.Draw(im) #now we can draw on this draw.text(((N-sz[0])/2, (N-sz[1])/2), letter, font=font, fill=fg_luminance) #this centers the letter if noise > 0: pix = im.load() #pix is now an addressable array of pixel values rd = numpy.random.normal(scale=noise, size=(N,N)) for row in xrange(N): for col in xrange(N): pix[row,col] += rd[row,col] im.show()
def __init__(self, clust_data, labels = None, bsize = 10, tree_space = 200): self.space = tree_space colours = ['blue', 'green', 'red', 'cyan', 'magenta', 'brown', 'orange'] self.colour_map = self._init_colours(colours, [ x.cluster_id for x in clust_data.datapoints ]) if labels is None: labels = [ clust_data.datapoints[x].sample_id for x in clust_data.reorder_indices ] try: self.font = ImageFont.load('courR08.pil') #Copyright (c) 1987 Adobe Systems, Inc., Portions Copyright 1988 Digital Equipment Corp. except IOError: self.font = None if len(clust_data.consensus_matrix) != len(labels): raise ValueError, "Number of columns and column label arrays have different lengths!" Hmap.__init__(self, clust_data.consensus_matrix, bsize = bsize) #Creates image in self.im if HMAP_ENABLED if self.im is not None: old_draw = ImageDraw.Draw(self.im) self.max_textsize = 0 for label in labels: self.max_textsize = max(self.max_textsize, old_draw.textsize(label, font=self.font)[0]) del old_draw #Keep GC from keeping the old image around if clust_data.tree is None: self.space = self.max_textsize + 5 #Prepare newsize = (self.im.size[1] + self.space, self.im.size[0]) #To hold our rotated copy and some text im = Image.new('RGBA', newsize, 'white') #Trick to make vertical text when we're done, and add tree space im.paste(self.im.rotate(-90), (0, 0, self.im.size[1], self.im.size[0])) self.im = im self.draw = ImageDraw.Draw(self.im) #Actual work self._add_cluster_labels(labels) if clust_data.tree is not None: self._draw_dendogram(clust_data.tree) #Finish self.im = self.im.rotate(90)
def predict(self,image): im = Image.open(image) im = im.resize((self.IMAGE_WIDTH,self.IMAGE_HEIGHT)) imgMat = np.array(im) res = self.sess.run(self.fc_19, feed_dict = {self.x : [imgMat]}) res = np.reshape(res,[7,7,30]) boxes = [] print "i,j,c,p,confidence,x,y,w,h'" for i in range(7): for j in range(7): c = np.argmax(res[i][j][:20]) if(res[i][j][c] > 0.5): score_th = 0.5 responsible_box = 0 if res[i][j][28] < res[i][j][29]: responsible_box = 1 if res[i][j][28 + responsible_box] > score_th: w = res[i][j][22 + 4 * responsible_box] h = res[i][j][23 + 4 * responsible_box] size_threshold = 0.05 if w > size_threshold and h > size_threshold: boxes.append([i,j,c,res[i][j][c],res[i][j][28+responsible_box], res[i][j][20 + 4 * responsible_box],res[i][j][21 + 4 * responsible_box], res[i][j][22 + 4 * responsible_box],res[i][j][23 + 4 * responsible_box]]) print boxes draw = ImageDraw.Draw(im) for box in boxes : w = box[7] * self.IMAGE_WIDTH / 2 h = box[8] * self.IMAGE_HEIGHT / 2 print 'w = ', w, ' h = ', h lx = (box[0] + box[5]) * self.GRID_SIZE - w ly = (box[1] + box[6]) * self.GRID_SIZE - h tx = (box[0] + box[5]) * self.GRID_SIZE + w ty = (box[1] + box[6]) * self.GRID_SIZE + h print(lx,ly,tx,ty) draw.rectangle((lx,ly,tx,ty)) content = self.classes[box[2]] + ' p = ' + str(box[3]) draw.text((lx, ly), content, fill=(255, 255, 255)) im.show()