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)
python类Draw()的实例源码
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
clusters.py 文件源码
项目:Programming-Collective-Intelligence
作者: clyyuanzi
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
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
birds_skip_thought_demo.py 文件源码
项目:how_to_convert_text_to_images
作者: llSourcell
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
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 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 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 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