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)
python类Draw()的实例源码
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 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
extract_font (NIST).py 文件源码
项目:Handwriting-Recognition
作者: samkit-jain
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
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")
extract_font (TTF).py 文件源码
项目:Handwriting-Recognition
作者: samkit-jain
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
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
automatedFrenchPress.py 文件源码
项目:estefannieExplainsItAll
作者: estefanniegg
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
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()
automatedFrenchPress.py 文件源码
项目:estefannieExplainsItAll
作者: estefanniegg
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
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()
automatedFrenchPress.py 文件源码
项目:estefannieExplainsItAll
作者: estefanniegg
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
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()
automatedFrenchPress.py 文件源码
项目:estefannieExplainsItAll
作者: estefanniegg
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
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