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
python类Draw()的实例源码
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 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 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__(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 __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 __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 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()