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
python类Draw()的实例源码
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 _showUnavailable(self, width, height, message="STATS UNAVAILABLE"):
import PIL.Image as Image
import PIL.ImageDraw as ImageDraw
import StringIO
size = (int(width), int(height))
im = Image.new('RGB', size, 'white')
draw = ImageDraw.Draw(im)
red = (255,0,0)
text_pos = (size[0]/2,size[1]/2)
text = message
draw.text(text_pos, text, fill=red)
del draw
output = StringIO.StringIO()
im.save(output, 'PNG')
del im
response = output.getvalue()
output.close()
return response
def cover_generator(src, starting, ending):
urllib.request.urlretrieve(src, "cover.jpg")
img = Image.open("cover.jpg")
msg = str(starting) + "-" + str(ending)
draw = ImageDraw.Draw(img)
thefont = ImageFont.truetype("arial.ttf", 75)
#Get's the average complementary color of the picutre
W, H = (400, 600)
img2 = img.resize((1, 1))
redc = 255 - img2.getpixel((0, 0))[0]
greebc = 255 - img2.getpixel((0, 0))[1]
bluec = 255 - img2.getpixel((0, 0))[2]
complementary = (redc, greebc, bluec)
w, h = draw.textsize(msg, font=thefont)
#Allig's and writes the text
draw.text(((W - w) / 2, 2), msg, complementary, font = thefont)
img.save("cover.jpg")
def make_icon(self, input="./roomba.png", output="./roomba_mod.png"):
#utility function to make roomba icon from generic roomba icon
if not HAVE_PIL: #drawing library loaded?
self.log.error("PIL module not loaded")
return None
try:
roomba = Image.open(input).convert('RGBA')
roomba = roomba.rotate(90, expand=False)
roomba = self.make_transparent(roomba)
draw_wedge = ImageDraw.Draw(roomba)
draw_wedge.pieslice(
[(5,0),(roomba.size[0]-5,roomba.size[1])],
175, 185, fill="red", outline="red")
roomba.save(output, "PNG")
return roomba
except Exception as e:
self.log.error("ERROR: %s" % e)
return None
def draw_vacuum_lines(self, image, old_x_y, x_y, theta, colour="lawngreen"):
'''
draw lines on image from old_x_y to x_y reepresenting vacuum coverage,
taking into account angle theta (roomba angle).
'''
lines = ImageDraw.Draw(image)
if x_y != old_x_y:
self.log.info("MAP: drawing line: %s, %s" % (old_x_y, x_y))
lines.line([old_x_y, x_y], fill=colour,
width=self.roomba_icon.size[0] // 2)
#draw circle over roomba vacuum area to give smooth edges.
arcbox = [x_y[0]-self.roomba_icon.size[0] // 4,
x_y[1]-self.roomba_icon.size[0] // 4,
x_y[0]+self.roomba_icon.size[0] // 4,
x_y[1]+self.roomba_icon.size[0] // 4]
lines.ellipse(arcbox, fill=colour)
def make_icon(self, input="./roomba.png", output="./roomba_mod.png"):
#utility function to make roomba icon from generic roomba icon
if not HAVE_PIL: #drawing library loaded?
self.log.error("PIL module not loaded")
return None
try:
roomba = Image.open(input).convert('RGBA')
roomba = roomba.rotate(90, expand=False)
roomba = self.make_transparent(roomba)
draw_wedge = ImageDraw.Draw(roomba)
draw_wedge.pieslice(
[(5,0),(roomba.size[0]-5,roomba.size[1])],
175, 185, fill="red", outline="red")
roomba.save(output, "PNG")
return roomba
except Exception as e:
self.log.error("ERROR: %s" % e)
return None
def draw_text(self, image, display_text, fnt, pos=(0,0),
colour=(0,0,255,255), rotate=False):
#draw text - (WARNING old versions of PIL have huge memory leak here!)
if display_text is None: return
self.log.info("MAP: writing text: pos: %s, text: %s"
% (pos, display_text))
if rotate:
txt = Image.new('RGBA', (fnt.getsize(display_text)),
self.transparent)
text = ImageDraw.Draw(txt)
# draw text rotated 180 degrees...
text.text((0,0), display_text, font=fnt, fill=colour)
image.paste(txt.rotate(180-self.angle, expand=True), pos)
else:
text = ImageDraw.Draw(image)
text.text(pos, display_text, font=fnt, fill=colour)
def draw_doge_meme(from_dir, to_dir, font_path, phrases):
"""
Draw a doge meme, given an image path and text to draw on it.
Args:
from_dir (str): Directory of template doge image.
to_dir (str): Path where to store result, including file name and extension.
font_path (str): Directory of font to use.
phrases (list[str]): Doge phrases to draw onto image.
"""
image = Image.open(from_dir)
texts = []
for phrase in phrases:
new_text = make_drawn_text(
image,
phrase,
font_path,
texts
)
texts.append(new_text)
for text in texts:
text.draw(image)
image.save(to_dir)
def road_draw(image, highway):
im = Image.fromarray(image.astype('uint8'))
draw = ImageDraw.Draw(im)
fnt = ImageFont.truetype('FreeMono/FreeMonoBold.ttf', 40)
shape = image.shape
if highway:
draw.text((65, 10), "Highway",
font=fnt, fill=(255, 255, 0, 255))
draw.ellipse([10, 10, 55, 55], fill=(255, 255, 0, 255),
outline=(255, 255, 0, 255))
else:
draw.text((65, 10), "small road",
font=fnt, fill=(255, 0, 0, 255))
draw.ellipse([10, 10, 55, 55], fill=(255, 0, 0, 255),
outline=(255, 0, 0, 255))
return np.array(im).astype('float32')
def draw_bounding_boxes(celeb_objs, file):
'''
Draws bounding boxes around all faces in inputted file determined by celeb_objs
'''
colors = []
im = Image.open(file)
draw = ImageDraw.Draw(im)
for i in range(len(celeb_objs)):
color = rectangle_colors[i % len(rectangle_colors)]
colors.append(color)
coords = get_coords_from_ratios(celeb_objs[i].to_dict()['BoundingBox'], im.width, im.height)
draw_width_rectangle(draw, coords, color, rectangle_width)
del draw
file.seek(0)
im.save(file, 'PNG')
return colors
def updateScreen(self, canvas):
""" update the image with a new canvas"""
w = canvas.width
h = canvas.height
img = Image.new('RGB', (w, h))
drw = ImageDraw.Draw(img)
for x in xrange(w):
for y in xrange(h):
col = canvas.getPixel(x, y)
drw.point((x,y), fill=(int(col[0]*255), int(col[1]*255), int(col[2]*255)))
scl = img.resize( (87, 324), resample=Image.BILINEAR )
self.lampSrc.paste(scl, (55,227))
self.lampImg = ImageTk.PhotoImage(self.lampSrc)
self.backgroundLabel.config(image=self.lampImg)
capture_imgs_remote_driving_cozmo.py 文件源码
项目:CozmoSelfDriveToyUsingCNN
作者: benjafire
项目源码
文件源码
阅读 35
收藏 0
点赞 0
评论 0
def apply(self, image, scale):
d = ImageDraw.Draw(image)
bounds = [3, 0, image.width, image.height]
def print_line(text_line):
text = cozmo.annotate.ImageText(text_line, position=cozmo.annotate.TOP_LEFT, color='lightblue')
text.render(d, bounds)
TEXT_HEIGHT = 11
bounds[1] += TEXT_HEIGHT
robot = self.world.robot
# Display the Pose info for the robot
pose = robot.pose
print_line('Pose: Pos = <%.1f, %.1f, %.1f>' % pose.position.x_y_z)
print_line('Pose: Rot quat = <%.1f, %.1f, %.1f, %.1f>' % pose.rotation.q0_q1_q2_q3)
print_line('Pose: angle_z = %.1f' % pose.rotation.angle_z.degrees)
print_line('Pose: origin_id: %s' % pose.origin_id)
# Display the Accelerometer and Gyro data for the robot
print_line('Accelmtr: <%.1f, %.1f, %.1f>' % robot.accelerometer.x_y_z)
print_line('Gyro: <%.1f, %.1f, %.1f>' % robot.gyro.x_y_z)
def GenerateImage(text, output_path, bgcolor):
print "Generating Image for the key: " + text
# Create an image with a bg colour and gradient.
img = image_util.GenerateRandomKeyImageBackground(MAX_W, MAX_H, bgcolor)
draw = ImageDraw.Draw(img)
# TODO: Store the font file locally
font = ImageFont.truetype("Georgia.ttf", FONT_SIZE)
# Get coordinates for drawing text
w, h = draw.textsize(text, font=font)
x = (MAX_W - w) / 2
y = (MAX_H - h) / 2
# Now add text to the image.
# Adding shadows first.
draw.text((x - SHADOW_WIDTH, y), text, font=font, fill=SHADOW_COLOR)
draw.text((x + SHADOW_WIDTH, y), text, font=font, fill=SHADOW_COLOR)
draw.text((x, y - SHADOW_WIDTH), text, font=font, fill=SHADOW_COLOR)
draw.text((x, y + SHADOW_WIDTH), text, font=font, fill=SHADOW_COLOR)
# Adding text in white.
draw.text((x, y), text, fill=TEXT_COLOR, font=font)
img.save(output_path)
def GenerateKeyImage(text, output_path, bgcolor):
TEXT_COLOR = "white"
img = Image.new('RGB', imgsize, bgcolor)
draw = ImageDraw.Draw(img)
# TODO: Store the font file locally
font = ImageFont.truetype("Georgia.ttf", FONT_SIZE)
# Get coordinates for drawing text
w, h = draw.textsize(text, font=font)
x = (MAX_W - w) / 2
y = (MAX_H - h) / 2
# Now add text to the image.
# Adding shadows first.
draw.text((x - SHADOW_WIDTH, y), text, font=font, fill=SHADOW_COLOR)
draw.text((x + SHADOW_WIDTH, y), text, font=font, fill=SHADOW_COLOR)
draw.text((x, y - SHADOW_WIDTH), text, font=font, fill=SHADOW_COLOR)
draw.text((x, y + SHADOW_WIDTH), text, font=font, fill=SHADOW_COLOR)
# Adding text in white.
draw.text((x, y), text, fill=TEXT_COLOR, font=font)
img.save(output_path)
def test_image(self):
img = Image.new('RGB', (32, 16))
draw = ImageDraw.Draw(img)
draw.rectangle([0, 0, 7, 15], fill=(255, 0, 0))
pic = webp.WebPPicture.from_pil(img)
config = webp.WebPConfig.new(lossless=True)
buf = pic.encode(config).buffer()
with TemporaryDirectory() as tmpdir:
file_name = os.path.join(tmpdir, 'image.webp')
with open(file_name, 'wb') as f:
f.write(buf)
with open(file_name, 'rb') as f:
webp_data = webp.WebPData.from_buffer(f.read())
arr = webp_data.decode(color_mode=webp.WebPColorMode.RGB)
expected = np.asarray(img, dtype=np.uint8)
np.testing.assert_array_equal(arr, expected)
def test_anim_simple_resample(self):
width = 256
height = 64
img1 = Image.new('RGB', (width, height))
draw = ImageDraw.Draw(img1)
draw.rectangle([0, 0, width-1, height-1], fill=(0, 0, 255))
draw.rectangle([0, 0, (width/4-1), height-1], fill=(255, 0, 0))
img2 = Image.new('RGB', (width, height))
draw = ImageDraw.Draw(img2)
draw.rectangle([0, 0, width-1, height-1], fill=(0, 0, 255))
draw.rectangle([0, 0, (width/4-1), height-1], fill=(0, 255, 0))
imgs = [img1, img1, img2, img2]
with TemporaryDirectory() as tmpdir:
file_name = os.path.join(tmpdir, 'anim.webp')
webp.save_images(imgs, file_name, fps=4, lossless=True)
dec_imgs = webp.load_images(file_name, 'RGBA', fps=4)
self.assertEqual(len(dec_imgs), 4)
def test_image_simple(self):
width = 256
height = 64
img = Image.new('RGB', (width, height))
draw = ImageDraw.Draw(img)
draw.rectangle([0, 0, width-1, height-1], fill=(0, 0, 255))
draw.rectangle([0, 0, (width/4-1), height-1], fill=(255, 0, 0))
with TemporaryDirectory() as tmpdir:
file_name = os.path.join(tmpdir, 'image.webp')
webp.save_image(img, file_name, lossless=True)
dec_img = webp.load_image(file_name, 'RGB')
actual = np.asarray(dec_img, dtype=np.uint8)
expected = np.asarray(img, dtype=np.uint8)
np.testing.assert_array_equal(actual, expected)
def gen_image(msg, fname, top = True):
t_pos = (10, 100)
if top:
t_pos = (10, 10)
font = ImageFont.truetype("Arial.ttf",42)
#img = Image.new("RGBA", (500,180),(255,255,255))
rand_array = numpy.random.rand(90, 500, 3) * 255
white_array = numpy.random.rand(90, 500, 3) * 0
if top:
full_array = numpy.vstack((rand_array, white_array))
else:
full_array = numpy.vstack((white_array, rand_array))
img = Image.fromarray(full_array.astype('uint8')).convert('RGB')
draw = ImageDraw.Draw(img)
draw.text(t_pos, msg, (255,255,255), font=font)
draw = ImageDraw.Draw(img)
img.save(fname)
N_dim_cubes_color.py 文件源码
项目:N_Dimensional_Cubes_python
作者: Daniel-The-Coder
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def Draw(lst, n):
global color
global draw
global dim
# print(lst)
# print(lst[0][0])
# print(str(lst[0][0]).isdigit())
if (str(lst[0][0])).isdigit() or (str((-1) * lst[0][0]).isdigit()):
# line(lst[0][0],lst[0][1],lst[1][0],lst[1][1])
draw.line(((lst[0][0] + dim[0] + 150, lst[0][1] + dim[2] + 150),
(lst[1][0] + dim[0] + 150, lst[1][1] + dim[2] + 150)), fill=color, width=1)
else:
print(n)
Draw(lst[0], n - 1)
Draw(lst[1], n - 1)
# t.pencolor(colors[n%6])
color = colors[n % 6]
lst1, lst2 = list(flatten(lst[0])), list(flatten(lst[1]))
for i in range(0, len(lst1), 2):
# line(lst1[i],lst1[i+1],lst2[i],lst2[i+1])
draw.line(((lst1[i] + dim[0] + 150, lst1[i + 1] + dim[2] + 150),
(lst2[i] + dim[0] + 150, lst2[i + 1] + dim[2] + 150)), fill=color, width=1)