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类new()的实例源码
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 whitespace(image, size, whitespace=False, whitespace_color=None, **kwargs):
if not whitespace:
return image
if whitespace_color is None:
whitespace_color = FILER_WHITESPACE_COLOR
if whitespace_color is None:
whitespace_color = '#fff'
old_image = image
source_x, source_y = image.size
target_x, target_y = size
image = Image.new('RGBA', (target_x, target_y), whitespace_color)
if source_x < target_x and source_y < target_y: # whitespace all around
image.paste(old_image, (
(target_x - source_x) / 2, (target_y - source_y) / 2))
elif source_x < target_x: # whitespace on top and bottom only
image.paste(old_image, ((target_x - source_x) / 2, 0))
elif source_y < target_y: # whitespace on sides only
image.paste(old_image, (0, (target_y - source_y) / 2))
else: # no whitespace needed
image = old_image
return image
def processOutputLine(self, line):
line = line[:-1]
#print "[DemuxTask]", line
MSG_NEW_FILE = "---> new File: "
MSG_PROGRESS = "[PROGRESS] "
MSG_NEW_MP2 = "++> Mpg Audio: PID 0x"
MSG_NEW_AC3 = "++> AC3/DTS Audio: PID 0x"
if line.startswith(MSG_NEW_FILE):
file = line[len(MSG_NEW_FILE):]
if file[0] == "'":
file = file[1:-1]
self.haveNewFile(file)
elif line.startswith(MSG_PROGRESS):
progress = line[len(MSG_PROGRESS):]
self.haveProgress(progress)
elif line.startswith(MSG_NEW_MP2) or line.startswith(MSG_NEW_AC3):
try:
self.currentPID = str(int(line.split(': PID 0x',1)[1].split(' ',1)[0],16))
except ValueError:
print "[DemuxTask] ERROR: couldn't detect Audio PID (projectx too old?)"
def apply_watermark(im, mark, position, opacity=1):
"""Adds a watermark to an image."""
if opacity < 1:
mark = reduce_opacity(mark, opacity)
if im.mode != 'RGBA':
im = im.convert('RGBA')
# create a transparent layer the size of the image and draw the
# watermark in that layer.
layer = Image.new('RGBA', im.size, (0, 0, 0, 0))
if position == 'tile':
for y in range(0, im.size[1], mark.size[1]):
for x in range(0, im.size[0], mark.size[0]):
layer.paste(mark, (x, y))
elif position == 'scale':
# scale, but preserve the aspect ratio
ratio = min(
float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
w = int(mark.size[0] * ratio)
h = int(mark.size[1] * ratio)
mark = mark.resize((w, h))
layer.paste(mark, (round((im.size[0] - w) / 2), round((im.size[1] - h) / 2)))
else:
layer.paste(mark, position)
# composite the watermark with the layer
return Image.composite(layer, im, layer)
def processOutputLine(self, line):
line = line[:-1]
#print "[DemuxTask]", line
MSG_NEW_FILE = "---> new File: "
MSG_PROGRESS = "[PROGRESS] "
MSG_NEW_MP2 = "++> Mpg Audio: PID 0x"
MSG_NEW_AC3 = "++> AC3/DTS Audio: PID 0x"
if line.startswith(MSG_NEW_FILE):
file = line[len(MSG_NEW_FILE):]
if file[0] == "'":
file = file[1:-1]
self.haveNewFile(file)
elif line.startswith(MSG_PROGRESS):
progress = line[len(MSG_PROGRESS):]
self.haveProgress(progress)
elif line.startswith(MSG_NEW_MP2) or line.startswith(MSG_NEW_AC3):
try:
self.currentPID = str(int(line.split(': PID 0x',1)[1].split(' ',1)[0],16))
except ValueError:
print "[DemuxTask] ERROR: couldn't detect Audio PID (projectx too old?)"
def did_load(self):
toolImagenames = {'Dot':'dots', 'Undo':'undo', 'New':'new', 'Save':'save',
'Prev':'preview', 'Zoom':'zoom', 'Load':'load', 'Grd':'grid',
'Lin':'lines', 'Exit': 'exit', 'Lvl': 'zoomlevel', 'Dith': 'dither_off',
'Char':'charinfo', 'Pan': 'pan', 'Bru1':'brush_1_on', 'Bru2':'brush_2',
'Bru6':'brush_6', 'BruC':'brush_char', 'Redo':'redo',
'MirX':'flipx', 'MirY':'flipy', 'Pan':'pan', 'PPos':'preview_position',
'Sel':'selection','Up':'offset_up','Down':'offset_down','Left':'offset_left'
,'Right':'offset_right','Prg':'prg','Koa':'koala'}
#counter = 0
for subby in self.subviews[0].subviews:
#print "subview " + str(counter) + ": " + subby.title
#counter += 1
fileName = 'icons/tool_' + toolImagenames[subby.title] + '_64.png'
subby.background_image = ui.Image.named(fileName)
subby.title = ""
# Automatically assigns functions to toolbar buttons with same name
def eval_black_white(self):
new = Image.new("RGB", (140, 75))
pix = new.load()
orgpix = self.img.load()
thresh = 4
for x in range(new.size[0]):
for y in range(new.size[1]):
rgb = orgpix[x, y]
r, g, b = rgb
pix[x, y] = (255, 255, 255)
if r > max(b, g) + thresh:
pix[x, y] = (0, 0, 0)
if g < min(r, b):
pix[x, y] = (0, 0, 0)
if g > max(r, b) + thresh:
pix[x, y] = (0, 0, 0)
if b > max(r, g) + thresh:
pix[x, y] = (0, 0, 0)
self.img = new
self.pixels = self.img.load()
def processOutputLine(self, line):
line = line[:-1]
#print "[DemuxTask]", line
MSG_NEW_FILE = "---> new File: "
MSG_PROGRESS = "[PROGRESS] "
MSG_NEW_MP2 = "++> Mpg Audio: PID 0x"
MSG_NEW_AC3 = "++> AC3/DTS Audio: PID 0x"
if line.startswith(MSG_NEW_FILE):
file = line[len(MSG_NEW_FILE):]
if file[0] == "'":
file = file[1:-1]
self.haveNewFile(file)
elif line.startswith(MSG_PROGRESS):
progress = line[len(MSG_PROGRESS):]
self.haveProgress(progress)
elif line.startswith(MSG_NEW_MP2) or line.startswith(MSG_NEW_AC3):
try:
self.currentPID = str(int(line.split(': PID 0x',1)[1].split(' ',1)[0],16))
except ValueError:
print "[DemuxTask] ERROR: couldn't detect Audio PID (projectx too old?)"
def test_bw(self):
image = Image.new('RGB', (800, 600))
processed = processors.colorspace(image, bw=True)
self.assertEqual(processed.mode, 'L')
image = Image.new('RGBA', (800, 600))
processed = processors.colorspace(image, bw=True)
self.assertEqual(processed.mode, 'LA')
image = Image.new('L', (800, 600))
processed = processors.colorspace(image, bw=True)
self.assertEqual(processed.mode, 'L')
image = Image.new('LA', (800, 600))
processed = processors.colorspace(image, bw=True)
self.assertEqual(processed.mode, 'LA')
def whitespace(image, size, whitespace=False, whitespace_color=None, **kwargs):
if not whitespace:
return image
if whitespace_color is None:
whitespace_color = FILER_WHITESPACE_COLOR
if whitespace_color is None:
whitespace_color = '#fff'
old_image = image
source_x, source_y = image.size
target_x, target_y = size
image = Image.new('RGBA', (target_x, target_y), whitespace_color)
if source_x < target_x and source_y < target_y: # whitespace all around
image.paste(old_image, (
(target_x - source_x) / 2, (target_y - source_y) / 2))
elif source_x < target_x: # whitespace on top and bottom only
image.paste(old_image, ((target_x - source_x) / 2, 0))
elif source_y < target_y: # whitespace on sides only
image.paste(old_image, (0, (target_y - source_y) / 2))
else: # no whitespace needed
image = old_image
return image
def create_wallpaper(screen, urls, size=(100, 100), randomise=False):
if randomise:
random.shuffle(urls)
wallpaper = Image.new("RGB", screen, "blue")
width = int(math.ceil(float(screen[0]) / size[0]))
height = int(math.ceil(float(screen[1]) / size[1]))
offset = [0,0]
for i in xrange(height):
y = size[1] * i
for j in xrange(width):
x = size[0] * j
photo = load_photo(urls.pop())
if photo.size != size:
photo = photo.resize(size, Image.BICUBIC)
wallpaper.paste(photo, (x, y))
del photo
return wallpaper
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 mark(self, path, position=POSITION_BOTTOM_RIGHT):
'''????????'''
try:
img = Image.open(path)
except IOError:
return None
if img.size[0] < self._mosaic.size[0]:
print 'width', img.size[0], self._mosaic.size[0]
return None
if img.size[1] < self._mosaic.size[1]:
print 'height', img.size[1], self._mosaic.size[1]
return None
img_area = img.size[0] * img.size[1]
mosaic_area = self._mosaic.size[0] * self._mosaic.size[1]
ratio = 4
if img_area < mosaic_area * ratio:
return None
self._locate(img, position)
layer = Image.new('RGBA', img.size, (0, 0, 0, 0))
layer.paste(self._mosaic, self.box)
return Image.composite(layer, img, layer)
def generate_clouds(self):
y = self.cloud_height
while self.cloud_height < self.bounds.h * 2:
q = min(self.climb, DIFFICULTY_Q)
min_dist = int(MAX_CLOUD_DIST * q / DIFFICULTY_Q)
max_dist = int(MAX_CLOUD_DIST / 2 + min_dist / 2)
self.cloud_height += random.randint(min_dist, max_dist)
rect = Rect(random.random() * (self.bounds.w - 150),
self.cloud_height, 0, 0)
cloud = Cloud(rect, self)
if random.random() < ENEMY_DENSITY:
#generate new enemy
rect = Rect(0, 0, 64, 64)
rect.center(cloud.frame.center())
rect.y = cloud.frame.top() - 15
enemy = Enemy(rect, self)
enemy.velocity = cloud.velocity
def end_game(self):
self.game_state = GAME_DEAD
self.player.velocity = Point(0, 0)
death_loc = self.player.frame.center()
death_loc.y = max(death_loc.y, 80)
self.player.die()
del self.player
self.player = None
score = int(self.climb / 10)
if self.high_scores.is_high_score(player_name, score):
self.smoke_special.frame.center(death_loc)
self.smoke_special.configure(frame_count=0, is_done=False)
#console.hud_alert('New high score!') # for debugging purposes
run_in_thread(high_score_sounds)
fmt = 'Congratulations {}:\nYou have a new high score!'
self.high_score_msg = fmt.format(player_name)
else:
self.smoke_normal.frame.center(death_loc)
self.smoke_normal.configure(frame_count=0, is_done=False)
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 __fixup(self, im1):
# convert image to suitable mode
if isinstance(im1, _Operand):
# argument was an image.
if im1.im.mode in ("1", "L"):
return im1.im.convert("I")
elif im1.im.mode in ("I", "F"):
return im1.im
else:
raise ValueError, "unsupported mode: %s" % im1.im.mode
else:
# argument was a constant
if _isconstant(im1) and self.im.mode in ("1", "L", "I"):
return Image.new("I", self.im.size, im1)
else:
return Image.new("F", self.im.size, im1)
def invert(image):
"Invert a channel"
image.load()
return image._new(image.im.chop_invert())
##
# Compare images, and return lighter pixel value
# (max(image1, image2)).
# <p>
# Compares the two images, pixel by pixel, and returns a new image
# containing the lighter values.
#
# @param image1 First image.
# @param image1 Second image.
# @return An image object.
def lighter(image1, image2):
"Select the lighter pixels from each image"
image1.load()
image2.load()
return image1._new(image1.im.chop_lighter(image2.im))
##
# Compare images, and return darker pixel value
# (min(image1, image2)).
# <p>
# Compares the two images, pixel by pixel, and returns a new image
# containing the darker values.
#
# @param image1 First image.
# @param image1 Second image.
# @return An image object.
def _pilbitmap_check():
global _pilbitmap_ok
if _pilbitmap_ok is None:
try:
im = Image.new("1", (1,1))
Tkinter.BitmapImage(data="PIL:%d" % im.im.id)
_pilbitmap_ok = 1
except Tkinter.TclError:
_pilbitmap_ok = 0
return _pilbitmap_ok
# --------------------------------------------------------------------
# PhotoImage
##
# Creates a Tkinter-compatible photo image. This can be used
# everywhere Tkinter expects an image object. If the image is an RGBA
# image, pixels having alpha 0 are treated as transparent.
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
项目源码
文件源码
阅读 22
收藏 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 image_saver(config, imageName='webgobbler.bmp', generateSingleImage=False):
''' Continuously generate new images (using the assembler_superpose) and save them
into a file.
config (an applicationConfig object) : the program configuration
imageName (string): name of image to save (eg."toto.jpeg","dudu.png"...)
generateSingleImage (bool): If True, will generate a single image.
'''
log = logging.getLogger('image_saver')
a = assembler_superpose(pool=imagePool(config=config), config=config)
a.start()
try:
while True:
log.info("Generating a new image to %s" % imageName)
a.superposeB() # Evolve current image
a.saveImageTo(imageName)
if generateSingleImage:
break
log.info("Will generate a new image in %d seconds." %
config["program.every"])
time.sleep(config["program.every"])
finally:
a.shutdown()
a.join()
def eval_black_white(self):
new = Image.new("RGB", (140, 75))
pix = new.load()
orgpix = self.img.load()
thresh = 4
for x in range(new.size[0]):
for y in range(new.size[1]):
rgb = orgpix[x, y]
r, g, b = rgb
pix[x, y] = (255, 255, 255)
if r > max(b, g) + thresh:
pix[x, y] = (0, 0, 0)
if g < min(r, b):
pix[x, y] = (0, 0, 0)
if g > max(r, b) + thresh:
pix[x, y] = (0, 0, 0)
if b > max(r, g) + thresh:
pix[x, y] = (0, 0, 0)
self.img = new
self.pixels = self.img.load()
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 termPrintln(self, text):
if(self.terminalCursor>9):
self.terminalCursor = 0
self.terminalBuffer = [""]*20
self.refresh()
self.termPrint(text)
self.terminalCursor += 1
## Print new text in place of current line (Low Refresh Rate)
# @param self The object pointer.
# @param text The text to print to the screen.
# @remark
# To use this function in your program:
# @code
# ...
# screen.termReplaceLastLine("Replaced!")
# @endcode
def __fixup(self, im1):
# convert image to suitable mode
if isinstance(im1, _Operand):
# argument was an image.
if im1.im.mode in ("1", "L"):
return im1.im.convert("I")
elif im1.im.mode in ("I", "F"):
return im1.im
else:
raise ValueError, "unsupported mode: %s" % im1.im.mode
else:
# argument was a constant
if _isconstant(im1) and self.im.mode in ("1", "L", "I"):
return Image.new("I", self.im.size, im1)
else:
return Image.new("F", self.im.size, im1)
def invert(image):
"Invert a channel"
image.load()
return image._new(image.im.chop_invert())
##
# Compare images, and return lighter pixel value
# (max(image1, image2)).
# <p>
# Compares the two images, pixel by pixel, and returns a new image
# containing the lighter values.
#
# @param image1 First image.
# @param image1 Second image.
# @return An image object.
def lighter(image1, image2):
"Select the lighter pixels from each image"
image1.load()
image2.load()
return image1._new(image1.im.chop_lighter(image2.im))
##
# Compare images, and return darker pixel value
# (min(image1, image2)).
# <p>
# Compares the two images, pixel by pixel, and returns a new image
# containing the darker values.
#
# @param image1 First image.
# @param image1 Second image.
# @return An image object.