def make_page(infile, outfile, text = "", text2 = ""): '''takes the inputfilename, outputfilename and text to put it in at the bottom''' font = 'Aller_Rg.ttf' #some random font, just fine one that is legible enough color = (50, 50, 50) # color of the text box page = Image.open(infile) # opening original image width, original_height = page.size # size of original image temp = ImageText((1000, 500), background=(255, 255, 255, 200)) # +20 y offset writer leaves that much space at the top height = temp.write_text_box((0, 0), text, box_width=width, font_filename=font, font_size=16, color=color)[1] + 20 textbox = temp.image.crop((0, 0, width, height)) #crop text #making a large temp Image text object to put the text in. temp = ImageText((1000, 500), background=(255, 255, 255, 200)) # +20 y offset writer leaves that much space at the top height2 = temp.write_text_box((0, 0), text2, box_width=width, font_filename=font, font_size=16, color=color)[1] + 20 textbox2 = temp.image.crop((0, 0, width, height)) #crop textbox output = Image.new("RGBA", (width, original_height + height + height2), (120, 20, 20)) # make new blank image with computed dimensions output.paste(textbox2, (0,0)) output.paste(page, (0,height2)) # paste original output.paste(textbox, (0, original_height + height2)) # paste textbox output.save(outfile) # save file
def write_description_item(card, text_whole): lines = text_whole.split('|') color = (0, 0, 0) font = 'resources/lucida-sans/LucidaSansRegular.ttf' img = ImageText((475, 160), background=(255, 255, 255, 0)) # 200 = alpha size = 22 if len(lines[3]) > 100 else 25 img.write_text_box((0, 0), lines[3], place='center', box_width=475, font_filename=font, font_size=25, color=color) card.paste(img.image, (185, 635), img.image) size = 22 if len(lines[1]) > 100 else 25 img = ImageText((420, 150), background=(255, 255, 255, 0)) # 200 = alpha img.write_text_box((0, 0), lines[1], place='center', box_width=420, font_filename=font, font_size=size, color=(255, 255, 255)) card.paste(img.image, (180, 850), img.image)
def textBoxBuilder(text, height, width, bufferOffsetH, buffer, font, fontSize): imgTxt = ImageText(buffer, background=(255, 255, 255, 0)) imgTxtShadow = ImageText(buffer, background=(0, 0, 0, 0)) imgTxtWhiteShadow = ImageText(buffer, background=(80, 80, 80, 0)) color = (255, 255, 255) textHeight = imgTxt.write_text_box((0, 0), text, int(width - (width / 10)), font_filename=font, font_size=fontSize, color=color, place='center') imgTxtShadow.write_text_box((0, 0), text, int(width - (width / 10)), font_filename=font, font_size=fontSize, color=(0, 0, 50), place='center') imgTxtWhiteShadow.write_text_box((0, 0), text, int(width - (width / 10)), font_filename=font, font_size=fontSize, color=(80, 80, 80), place='center') textHeight = height - ((textHeight[1]) + bufferOffsetH) if textHeight < 0: textHeight = bufferOffsetH #logging.info("textHeight"+str(textHeight)) return textHeight, imgTxt, imgTxtShadow, imgTxtWhiteShadow
def write_exp_boss(card, exp): color = (255, 255, 255) text = exp + ' XP' font = 'resources/dos/dos.ttf' img = ImageText((220, 100), background=(255, 255, 255, 0)) img.write_text_box((0, 0), text, place='center', box_width=220, font_filename=font, font_size=50, color=color) shadow = ImageText((220, 100), background=(255, 255, 255, 0)) shadow.write_text_box((0, 0), text, place='center', box_width=220, font_filename=font, font_size=50, color=(0, 0, 0)) shadow.image = shadow.image.resize((230, 110), Image.ANTIALIAS) shadow.image = shadow.image.filter(ImageFilter.BLUR) shadow.image = shadow.image.filter(ImageFilter.BLUR) card.paste(shadow.image, (90, 895), shadow.image) card.paste(img.image, (90, 900), img.image)
def generate(self): # 1. paste image on image self.backgroundImage.paste(self.profileImage, self.blockPosition) # 2. put text on image position = (self.blockPosition[0], self.blockPosition[1] + self.blockWidth) for paragraph in self.lines: image_text = ImageText( (self.blockWidth, self.imageHeight - self.blockPosition[1])) (x, y) = image_text.write_text_box( (0, 0), paragraph.get_text(self.replacements), self.blockWidth, font_filename=paragraph.font, font_size=paragraph.size, color=paragraph.color, place='justify') self.backgroundImage.paste(image_text.image, position, image_text.image) position = (position[0], position[1] + y + paragraph.skip) return self.backgroundImage
def quoteGen(data): text = data['QUOTE'] author = data['AUTHOR'] a = time.strftime('%r\n%d/%m/%Y') img = ImageText("bg-images/rsz_photo-1517816743773-6e0fd518b4a6.jpg", background=(255, 255, 255, 200)) #You don't need to specify text size: can specify max_width or max_height # and tell write_text to fill the text in this space, so it'll compute font # size automatically #write_text will return (width, height) of the wrote text img.write_text((525, 600), a, font_filename=font_3, font_size=20, max_height=150, color=color) if len(text) >= 130 and len(text) <= 250: img.write_text_box((100, 200), text, box_width=400, font_filename=font, font_size=25, color=color, place='center') img.write_text((300, 500), 'Author : ' + author, font_filename=font, font_size=19, max_height=150, color=color) img.save('sample-imagetext.png') elif len(text) > 0 and len(text) < 130: img.write_text_box((100, 200), text, box_width=350, font_filename=font, font_size=25, color=color, place='center') img.write_text((250, 400), 'Author : ' + author, font_filename=font_2, font_size=15, max_height=150, color=color) img.save('sample-imagetext.png')
def overlay(msg, in_path, out_path): img = Image.open(in_path).convert("RGBA") img = img.resize(get_size(img.size)) w, h = img.width, img.height r_height = max(h // 8, 26) h_mid = 2 * h // 3 f_size = int(r_height * 0.6) imgText = ImageText(img.size) box_size = imgText.write_text_box( (0, h_mid), msg, box_width=int(w * 0.95), font_filename="LiberationSans-Regular.ttf", font_size=f_size, color=(255, 255, 255, 200), place="center", ) imgText = ImageText(img.size) imgText.write_text_box( (0, h_mid - box_size[1] // 2), msg, box_width=int(w * 0.95), font_filename="LiberationSans-Regular.ttf", font_size=f_size, color=(255, 255, 255, 200), place="center", ) r_height = box_size[1] + f_size * 0.6 shape = [(0, h_mid - r_height // 2), (w, h_mid + r_height // 2)] overlay = Image.new("RGBA", img.size, (255, 255, 255, 0)) overlayDraw = ImageDraw.Draw(overlay) overlayDraw.rectangle(shape, fill=(0, 0, 0, 128)) out = Image.alpha_composite(img, overlay) out = Image.alpha_composite(out, imgText.image) out.convert("RGB").save(out_path, "JPEG")
def write_title_boss(card, title, subtitle): color = (255, 255, 255) font = 'resources/dos/dos.ttf' img = ImageText((690, 160), background=(255, 255, 255, 0)) # 200 = alpha img.write_text_box((0, 0), title, place='center', box_width=690, font_filename=font, font_size=45, color=color) card.paste(img.image, (80, 55), img.image) img = ImageText((690, 80), background=(255, 255, 255, 0)) # 200 = alpha img.write_text_box((0, 0), subtitle, place='center', box_width=690, font_filename=font, font_size=25, color=color) card.paste(img.image, (80, 120), img.image)
def write_title_spell(card, title): color = (0, 0, 0) font = 'resources/dos/dos.ttf' img = ImageText((540, 75), background=(255, 255, 255, 0)) # 200 = alpha img.write_text_box((0, 0), title, place='center', box_width=540, font_filename=font, font_size=40, color=color) card.paste(img.image, (136, 150), img.image)
def gen_img(title, channel, views, time): with open('common.txt') as f: common = f.read().splitlines() args = [] for word in title.lower().split(' '): word = re.sub(r'[^a-z0-9]', '', word) if (len(word) <= 2 or word in common): continue args.append(word) fetch(args) im = Image.open('thumb.jpg') draw = ImageDraw.Draw(im) im = im.convert('RGB') im = im.resize((640, 360)) draw = ImageDraw.Draw(im) draw.rectangle([550, 310, 630, 350], fill='black') fnt = ImageFont.truetype('Arial Bold', 27) draw.text((555, 315), time, font=fnt, fill='white') im.save('thumb.jpg') im = Image.open('out.png') draw = ImageDraw.Draw(im) draw.rectangle([0, 0, 1250, 380], fill='#F1F1F1') draw.rectangle([10, 10, 640, 360], fill='white') thumb = Image.open('thumb.jpg') im.paste(thumb, (10, 10)) im.save('out.png') txt = ImageText('out.png') _, y = txt.write_text_box((670, -40), title, box_width=550, font_filename='Arial', font_size=55, color='black') txt.save('out.png') fnt = ImageFont.truetype('Arial', 40) im = Image.open('out.png') draw = ImageDraw.Draw(im) draw.text((675, y + 30), channel, font=fnt, fill='grey') draw.text((675, y + 85), views, font=fnt, fill='grey') im.save('out.png') print('Image generated!')
def createImage(w, h, partImg): global tmpdirpath img = Image.open(partImg, 'r') global img_w, img_h img_w, img_h = img.size pad_h = h // 7 # background = Image.new('RGBA', (w, h), (255, 255, 255, 255)) background = ImageText((w, h), background=(255, 255, 255, 255)) bg_w, bg_h = background.image.size offset = ((bg_w - img_w) // 2, pad_h) background.image.paste(img, offset) return background
def custom(request): if request.method == 'POST': bgcolor = (0,0,0) if request.POST['color'] == 'color2': bgcolor = (255,0,0, 255) elif request.POST['color'] == 'color3': bgcolor = (0,255,0, 255) elif request.POST['color'] == 'color4': bgcolor = (0,0,255, 255) color = (255,255,255) text = request.POST['text'] font = 'arial.ttf' img = ImageText((1280, 720), background=bgcolor) img.write_text_box((200, 200), text, box_width=880, font_filename=font, font_size=24, color=color, place='center') audio = Document(docfile = request.FILES['audio']) audio.save() audioBase = os.path.splitext(os.path.basename(audio.docfile.name))[0] newFile = '/media/output/' + audioBase + '.mp4' img.save('./media/input/' + audioBase + '_img.png') # ff = ffmpy.FFmpeg( # global_options='-loop 1', # inputs=OrderedDict([('./media/input/' + audioBase + '_img.png', None), ('./media/' + audio.docfile.name, None)]), # outputs={'.' + newFile: '-c:v libx264 -c:a aac -shortest'} # ) # ff.run() merge.delay('./media/input/' + audioBase + '_img.png', './media/' + audio.docfile.name, '.' + newFile) request.session['newFile'] = newFile request.session['newFileName'] = audioBase + '.mp4' return HttpResponseRedirect('/myapp/uploads/') else: # tax.delay() # tax.delay() # add.delay(7,8) # add.delay(7,8) # merge.delay('python1.png', 'custom.wav', 'output.mp4') # add.delay(7,8) # add.delay(7,8) return render(request, 'custom_input.html')
def write_description_hero(card, text): color = (0, 0, 0) font = 'resources/lucida-sans/LucidaSansRegular.ttf' img = ImageText((565, 170), background=(255, 255, 255, 0)) # 200 = alpha size = 22 if len(text) > 200 else 25 img.write_text_box((0, 0), text.replace("\n", ":"), place='center', box_width=565, font_filename=font, font_size=size, color=color) card.paste(img.image, (123, 710), img.image)
def write_description_spell(card, text): color = (0, 0, 0) font = 'resources/lucida-sans/LucidaSansRegular.ttf' img = ImageText((470, 200), background=(255, 255, 255, 0)) # 200 = alpha size = 25 if len(text) > 100 else 30 img.write_text_box((0, 0), text, place='center', box_width=470, font_filename=font, font_size=size, color=color) card.paste(img.image, (174, 675), img.image)
def write_title_item(card, title): color = (0, 0, 0) font = 'resources/dos/dos.ttf' size = 40 if len(title) < 15 else 30 img = ImageText((440, 80), background=(255, 255, 255, 0)) # 200 = alpha img.write_text_box((0, 0), title, place='center', box_width=440, font_filename=font, font_size=size, color=color) card.paste(img.image, (255, 90), img.image)
def getEntryHeight(entry,lastWidth,font_size_multipler=1): height = 0 font_var = 0 dummyImg = ImageText((IMGWIDTH,IMGHEIGHT), background=background) if(entry[1]=="lip"): height+=newLine elif(entry[1]=="TITLE"): font_var=15 height+=newLine elif(entry[1]=="USER"): font_var=-15 height+=newLine height+=dummyImg.write_text_box((0,0,lastWidth), entry[0], box_width=IMGWIDTH-(border*2), font_filename=font, font_size=font_size_multipler*font_size+font_var, color=color)[1] return height
def write_heart(card, number): color = (255, 255, 255) font = 'resources/dos/dos.ttf' img = ImageText((75, 115), background=(255, 255, 255, 0)) # 200 = alpha img.write_text_box((0, 0), number, place='center', box_width=75, font_filename=font, font_size=60, color=color) if int(number) < 0: card.paste(img.image, (140, 893), img.image) else: card.paste(img.image, (143, 893), img.image)
def write_title_hero(card, title, subtitle): subt_formatted = subtitle.lower().replace(" ", "_") subtitle_pic = Image.open("./resources/text_" + subt_formatted + ".png") x, y = subtitle_pic.size card.paste(subtitle_pic, (380 - x / 2, 182), subtitle_pic) color = (0, 0, 0) font = 'resources/dos/dos.ttf' img = ImageText((405, 75), background=(255, 255, 255, 0)) # 200 = alpha img.write_text_box((0, 0), title, place='center', box_width=405, font_filename=font, font_size=40, color=color) card.paste(img.image, (380 - 200, 93), img.image)
def makeStatic(text): global words_per_minute file="static" new = ImageFont.truetype(font, 3*font_size).getsize("g")[1] #first, get the height that would make this vertically centered height = getEntryHeight((text,"p"),0,3) overlay_height = (IMGHEIGHT-height)/2 height = (IMGHEIGHT-height)/2-new/2 #actually make the post img = ImageText(bg_img, background=background,overlay=overlay,border=border,overlay_height=overlay_height) img.write_text_box((border, height), text, box_width=IMGWIDTH-(border*2), font_filename=font, font_size=3*font_size, color=color,place="center") path_img = "../../tmp/images/{}.png".format(file) img.save(path_img) path_voice= "../../tmp/sounds/{}.mp4".format(file) call(['say','-v','Daniel','-r',"{}".format(word_per_minute),'-o',path_voice,"Thank you, next!"]) makeVideo(path_img,path_voice,"../../tmp/{}.mp4".format(file))
def generate_icon(deck, text, color=None): key_image_format = deck.key_image_format() width, height = (key_image_format['width'], key_image_format['height']) depth = key_image_format['depth'] font = "verdana.ttf" fgcolor = (255,255,255) bgcolor = (0, 0, 0, 255) # We're upscaling the image here, hence 2* icon = Image.new("RGBA", (width*2,height*2), color=bgcolor) if color: r,g,b = (color) innerColor = [r,g,b] outerColor = [0, 0, 0] #Color at the corners gradient = Image.new('RGBA', icon.size, color=0) for y in range(icon.height): for x in range(icon.width): #Find the distance to the center distanceToCenter = math.sqrt((x - icon.width/2) ** 2 + (y - icon.height/2) ** 2) #Make it on a scale from 0 to 1 distanceToCenter = float(distanceToCenter) / (math.sqrt(2) * icon.width/2) #Calculate r, g, and b values r = outerColor[0] * distanceToCenter + innerColor[0] * (1 - distanceToCenter) g = outerColor[1] * distanceToCenter + innerColor[1] * (1 - distanceToCenter) b = outerColor[2] * distanceToCenter + innerColor[2] * (1 - distanceToCenter) #Place the pixel gradient.putpixel((x, y), (int(r), int(g), int(b))) icon = gradient txtIm = ImageText(icon.size) txtIm.write_text_box((0,0), text, box_width=width*2, font_filename=font, font_size=26, color=bgcolor, place='center') txtImEx = txtIm.export() bb = ImageOps.mirror(Image.alpha_composite(icon,txtImEx).convert("RGB")) # We upscaled before and now we downscale the image - looks much nicer like that, with antialiasing bb.thumbnail((width,height), Image.ANTIALIAS) return bb.tobytes()
def create(quote): inky_display = InkyWHAT("black") inky_display.set_border(inky_display.WHITE) # From https://gist.github.com/jasondilworth56/27764ae8ed2327a34ceebb06e75c30ea from PIL import ImageFont, ImageDraw, Image text = quote[0] author = quote[1] title = quote[2] #font = "/usr/share/fonts/truetype/freefont/FreeMono.ttf" font = "/usr/share/fonts/truetype/freefont/FreeSans.ttf" #font = "/home/pi/.fonts/Roboto-Bold.ttf" #font = "/home/pi/.fonts/Bitter-Regular.otf" #font = "/home/pi/.fonts/ufonts.com_rockwell.ttf" #font = "/home/pi/.fonts/Bookerly/Bookerly-Regular.ttf" #font = "/home/pi/.fonts/static/PlayfairDisplay-Regular.ttf" #font = "/home/pi/.fonts/PlayfairDisplay-VariableFont_wght.ttf" font = "/home/pi/.fonts/FredokaOne-Regular.ttf" #font = "/home/pi/.fonts/AmaticSC-Regular.ttf" img = ImageText((400, 300), background=(255, 255, 255)) img.fill_text_box((20, 20), text, box_width=340, box_height=250, font_filename=font) meta_line = author + ', ' + title #img.write_text( (10, inky_display.HEIGHT - 20), meta_line, font_filename=font) #img.fill_text_box((30, inky_display.HEIGHT - 40), meta_line, box_width=320, box_height=30, font_filename=font) img.write_text_box((30, inky_display.HEIGHT - 30), meta_line, box_width=320, font_filename=font, font_size=12, place='right') filename = '/home/pi/src/coten/images/coten.png' img.save(filename) img = Image.open(filename) img = img.quantize() inky_display.set_image(img) inky_display.set_border(inky_display.WHITE) inky_display.show()
def makeThumbnail(imgFile,episodeNum): #note: thumbnails should conform to same height/width size as video try: imgFile = imgFile.replace(" ","") path_img = "../static/thumbs/{}.jpg".format(imgFile) img = ImageText(path_img) size = img.size new = ImageFont.truetype(font, 5*font_size).getsize("g")[1] #newline size text = "Ep. #{}".format(episodeNum) tw = ImageFont.truetype(font, 5*font_size).getsize(text)[0]#text width th = new #text height over = Image.new("RGBA", (tw,th), color=(0,0,0,200)) #create overlay of correct size w = int((size[0]-tw)/2) #horizontally centered width h = int((size[1]-th)/2) #vertically centered height img.image.paste(over,(w,h), over) #add full size overlay img.write_text_box((0,h),text,box_width=size[0]-50,font_filename=font, font_size=5*font_size,color = (255,51,0),place="center") img.save("../../tmp/images/thumbnail.jpg") except Exception as e: print(e) pass
def makeTitle(text,voiceText,name): global words_per_minute file="title" new = ImageFont.truetype(font, 3*font_size).getsize("g")[1] #first, get the height that would make this vertically centered height = getEntryHeight((text,"p"),0,3) overlay_height = (IMGHEIGHT-height)/2 height = (IMGHEIGHT-height)/2-new/2 #actually make the post img = ImageText(bg_img, background=background,overlay=overlay,border=border,overlay_height=overlay_height) img.write_text_box((border, height), text, box_width=IMGWIDTH-(border*2), font_filename=font, font_size=3*font_size, color=color,place="center") path_img = "../../tmp/images/{}.png".format(file) path_voice= "../../tmp/sounds/{}.mp4".format(file) img.save(path_img) text = convertForVoice(voiceText) call(['say','-v','Daniel','-r',"{}".format(word_per_minute),'-o',path_voice,text]) makeVideo(path_img,path_voice,"../../tmp/{}.mp4".format(file)) f = open("../../out/{}.txt".format(name),"a+") f.write("file ../tmp/title.mp4\n") f.close()
def add_colored_text(text, output, image=None): main_color = (255,255,255) second_color = (255,0,0) padding_x = 10 padding_y = 10 margin_x = 0 margin_y = 0 words_to_highlight = ["reddit", "day"] words = text.split(" ") xy = (margin_x, margin_y) size = (800, 600) img = ImageText(size) font = "resources/font_tumbnail_abeezee.otf" font_size = 31 for word in words: if word.lower() in words_to_highlight: color = second_color else: color = main_color offset = img.write_text(xy, word, font, font_size=font_size, color=color) xy = (xy[0] + offset[0] + padding_x, xy[1]) if xy[0] > size[0] / 2: xy = (margin_x, offset[1] + padding_y) img.save(output)
#!/usr/bin/env python # coding: utf-8 # You need PIL <http://www.pythonware.com/products/pil/> to run this script # Download unifont.ttf from <http://unifoundry.com/unifont.html> (or use # any TTF you have) # Copyright 2011 Álvaro Justen [alvarojusten at gmail dot com] # License: GPL <http://www.gnu.org/copyleft/gpl.html> from image_utils import ImageText color = (50, 50, 50) text = 'Python is a cool programming language. You should learn it!' font = 'unifont.ttf' img = ImageText((800, 600), background=(255, 255, 255, 200)) # 200 = alpha #write_text_box will split the text in many lines, based on box_width #`place` can be 'left' (default), 'right', 'center' or 'justify' #write_text_box will return (box_width, box_calculed_height) so you can #know the size of the wrote text img.write_text_box((300, 50), text, box_width=200, font_filename=font, font_size=15, color=color) img.write_text_box((300, 125), text, box_width=200, font_filename=font, font_size=15,
def root(resource): route = request.args.get('route') lang = request.args.get('lang') if lang != "he": lang = "en" result = get_resource(resource) if route == "embed": result = format_resource_for_view(result, lang) return render_template("embed.j2", ob=result) else: platform = request.args.get('platform') if platform is None: platform = "facebook" text_color = (121, 121, 121) font_file = "TaameyFrankCLM-Medium.ttf" if lang == "he" else "Amiri-Regular.ttf" category_color_line_color = category_colors[ result["resource_category"]] font_size = platform_settings[platform]["font_size"] image_width = platform_settings[platform]["image_width"] image_height = platform_settings[platform]["image_height"] margin = platform_settings[platform]["margin"] category_color_line_width = platform_settings[platform][ "category_color_line_width"] additional_line_spacing = platform_settings[platform][ "additional_line_spacing_he"] if lang == "he" else platform_settings[ platform]["additional_line_spacing_en"] sefaria_branding = platform_settings[platform]["sefaria_branding"] branding_height = platform_settings[platform]["branding_height"] img = ImageText((image_width, image_height), background=(255, 255, 255, 255)) text = result["HebrewText"] if lang == "he" else result["EnglishText"] title = result["HebrewSectionReference"] if lang == "he" else result[ "EnglishSectionReference"] title = smart_truncate(title, length=30, suffix="...") text = ' '.join(text) text = cleanup_and_format_text(text, lang) if len(text) == 0: abort(204) if lang == "he": img.write_text_box((margin, -font_size * .5 + branding_height), text, box_width=image_width - 2 * margin, font_filename=font_file, font_size=font_size, color=text_color, place='justify', RTL=True, additional_line_spacing=additional_line_spacing, image_height=image_height) else: img.write_text_box((margin, -font_size + branding_height), text, box_width=image_width - 2 * margin, font_filename=font_file, font_size=font_size, color=text_color, place='justify', RTL=False, additional_line_spacing=additional_line_spacing, image_height=image_height) img.draw.line((0, category_color_line_width / 2, image_width, category_color_line_width / 2), fill=category_color_line_color, width=category_color_line_width) if (sefaria_branding): # Add Title Header font = ImageFont.truetype( os.path.dirname(os.path.realpath(__file__)) + "/static/fonts/" + font_file, font_size) img.draw.line( (0, branding_height / 2 + category_color_line_width, image_width, branding_height / 2 + category_color_line_width), fill=(247, 248, 248, 255), width=branding_height) w, h = img.draw.textsize(title, font=font) img.draw.text( ((image_width - w) / 2, (((branding_height / 2) + category_color_line_width)) - (h / 2)), cleanup_and_format_text(title, lang), fill=(35, 31, 32, 255), font=font) # Add footer footer = Image.open( os.path.dirname(os.path.realpath(__file__)) + "/static/img/footer.png") img.paste(footer, (0, image_height - 116)) # add borders img.draw.line( (0, category_color_line_width + branding_height, image_width, category_color_line_width + branding_height), fill=(204, 204, 204, 255), width=2) img.draw.line( (0, image_height - 117, image_width, image_height - 117), fill=(204, 204, 204, 255), width=2) img_io = StringIO() img.save(img_io, format="png") img_io.seek(0) return send_file(img_io, mimetype='image/png')
prediction = model.predict( diff) #sess.run(logits, feed_dict={x: diff}) # print (prediction) # d = dict(Counter(prediction)) # s = sorted(d.items(), key=lambda x: x[1]) # s.reverse() # print (s) # # prediction = [convert_to_oneHot(i) for i in prediction] # # print (prediction) # prediction = [t[0] for t in s] pred = np.argmax(prediction) text = "" color = (50, 50, 50) font = "arial.ttf" #'unifont.ttf' img = ImageText(Image.fromarray(frame)) if prediction[0][pred] > 0.5: predict = decode([pred]) print(str(predict) + " " + str(prediction[0][pred])) text = str(predict[0]) # print(prediction[0][pred]) # print(pred) else: print("Predicting...") text = "Predicting..." # img.write_text_box((300, 125), text, box_width=200, font_filename=font, # font_size=15, color=color, place='right') # # cv2.imshow('frame+prediction', cv2.cvtColor(np.array(img.image), cv2.COLOR_RGB2BGR)) # img.image.show()
def getHeights(textList,justThis=False,start_height=0): #returns number of images and height of last image global font_size global border img = ImageText(bg_img, background=background,overlay=overlay,border=border,overlay_height=IMGHEIGHT-border-border) height = border+(newLine/2) #since height seems to be relative to bottom of text if start_height!=0 and start_height>height: height=start_height overall = "" last_width = border firstBreak = True imageNumber = 0 for entry in textList: if justThis==True and entry[1]=="START_KID": return (imageNumber,height-border) if entry[1]=="START_KID": new_post = True height+=newLine border+=200 last_width = border continue if entry[1]=="END_KID": border-=200 last_width = border height+=newLine continue if entry[0]=="\n": continue if entry[1]=='BREAK': #print("Newline cuz break") height+=newLine last_width = border firstBreak = True continue if height+getEntryHeight(entry,last_width)>IMGHEIGHT-border: if justThis==True: return (imageNumber,height-border) imageNumber +=1 img = ImageText(bg_img, background=background,overlay=overlay,border=border,overlay_height=IMGHEIGHT-border-border) height = border+(newLine/2) last_width = border if entry[1]=="lip": if firstBreak==False: #print("Newline cuz list") height+=newLine last_width = border+15 overall+=entry[0] firstBreak=False else: overall+=entry[0] if entry[1]=="TITLE": endCoord = img.write_text_box((border, height,border), entry[0], box_width=IMGWIDTH-(border*2), font_filename=font, font_size=font_size+5, color=color) height = endCoord[1]+newLine last_width = border elif entry[1]=="USER": endCoord = img.write_text_box((border, height,border), entry[0], box_width=IMGWIDTH-(border*2), font_filename=font, font_size=font_size-15, color=color) height = endCoord[1]+newLine last_width = border else: endCoord = img.write_text_box((border, height,last_width), entry[0], box_width=IMGWIDTH-(border*2), font_filename=font, font_size=font_size, color=color) height = endCoord[1] last_width = endCoord[0] #print(last_width) if last_width>=IMGWIDTH-(border*2) or last_width<border: last_width = border height+=newLine return (imageNumber,height-border)
def kml2gevr(kml, output_dir, desiredHeight, bgColor, textColor): global font points = [] # get the point data from the kml file try: entry = getPoint(kml.Document.Placemark) if ('lon' in entry): points.append(entry) except: # Assume exception is due to multiple placemarks in the file # kml file contains multiple points for child in kml.Document.Folder.Placemark: entry = getPoint(child) if ('lon' in entry): points.append(entry) # get elevation from google maps script_dir = os.path.dirname(__file__) keyfile = open(os.path.join(script_dir, "googleapi.key"), 'r') key = keyfile.read().strip() client = googlemaps.Client(key) googleQuery = [(entry['lat'], entry['lon']) for entry in points] elevations = client.elevation(googleQuery) for i, elev in enumerate(elevations): points[i]['elev'] = elev['elevation'] # create the image files for entry in points: image = ImageText((1512, 950), background=bgColor) # (w, height) = image.write_text( ( 'center', 75) , entry['name'], # font_filename=font, font_size='fill', max_width=1400, # color=textColor) image.write_text_box(((1512 - 600) / 2.0, 110), entry['desc'], box_width=725, font_filename=font, font_size=72, color=textColor, place='center') newFile = tempfile.NamedTemporaryFile(suffix=".jpg", dir=output_dir, delete=False) newFile.close() image.save(newFile.name) entry['filename'] = newFile.name # now open that file back up and write an XMP containing the google protocol buffer to it gevrplace = gevrplace_pb2.GEVRPlace() temp = gevrplace.summary.location.extend([entry['name'], ""]) gevrplace.summary.copyright = "Imagery ©2016 Google, Data SIO, NOAA, U.S. Navy, NGA, GEBCO, Google, IBCAO, INEGI, Landsat" gevrplace.summary.unknown1 = 438 gevrplace.summary.unknown2 = 0 gevrplace.summary.unknown3 = 756 gevrplace.summary.unknown4 = 850 gevrplace.places.savedPlace.Title = entry['name'] gevrplace.places.savedPlace.SubTitle = entry['desc'] gevrplace.places.savedPlace.location.latLong.lat = entry['lat'] gevrplace.places.savedPlace.location.latLong.lon = entry['lon'] gevrplace.places.savedPlace.location.latLong.earthRadius = -6371010.0 gevrplace.places.savedPlace.location.picParams.roll = 0.0280364837203 weirdAltitude = (-entry['elev'] - 6371010) / desiredHeight gevrplace.places.savedPlace.location.picParams.weirdAltitude = weirdAltitude gevrplace.places.savedPlace.location.picParams.pitch = 0.00692561878283 gevrplace.places.savedPlace.location.heading = entry['heading'] gevrplace.places.savedPlace.location.viewMode = gevrplace_pb2.GEVRPlace.Places.Place.Location.EARTH_BELOW gevrplace.places.savedPlace.location.elevation = desiredHeight gevrplace.places.savedPlace.location.unknown3 = gevrplace_pb2.GEVRPlace.Places.Place.Location.UNKNOWN0 gevrplace.places.savedPlace.time.year = 2015 gevrplace.places.savedPlace.time.month = 8 gevrplace.places.savedPlace.time.day = 25 gevrplace.places.savedPlace.time.hour = 5 gevrplace.places.savedPlace.time.minute = 53 gevrplace.places.savedPlace.time.second = 23 ENCODED = base64.b64encode( gevrplace.SerializeToString()).decode().rstrip("=") xmpfile = XMPFiles(file_path=newFile.name, open_forupdate=True, open_usesmarthandler=True) xmp = xmpfile.get_xmp() xmp.register_namespace("http://ns.google.com/photos/1.0/earthvr/", "EarthVR") xmp.set_property(xmp.get_namespace_for_prefix("EarthVR"), "SerializedMetadata", ENCODED) xmp.set_property(xmp.get_namespace_for_prefix("EarthVR"), "Version", '1.0') xmpfile.put_xmp(xmp) xmpfile.close_file() return points
ret, frame = cap.read() if ret == True: if str(current_frame - 1) in data: current_frame -= 1 if str(current_frame) in data: img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) im = Image.fromarray(img) for fr in data[str(current_frame)]: #print("test") font = cv2.FONT_HERSHEY_SIMPLEX bottomLeftCornerOfText = (fr["bottomleft"]["x"], fr["bottomleft"]["y"]) fontScale = 1 fontColor = (0, 0, 0) lineType = 2 im = ImageText(im) # 200 = alpha #write_text_box will split the text in many lines, based on box_width #`place` can be 'left' (default), 'right', 'center' or 'justify' #write_text_box will return (box_width, box_calculed_height) so you can #know the size of the wrote text print(bottomLeftCornerOfText) im.write_text_box(bottomLeftCornerOfText, fr["line"], box_width=fr["bottomright"]["x"] - fr["bottomleft"]["x"], font_filename=font, font_size=15, color=font_color) #draw = ImageDraw.Draw (im) #draw.text ( bottomLeftCornerOfText, fr["line"], font=unicode_font, fill=font_color )