Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
images to pptx using annotation
import argparse
from pptx import Presentation
from pptx.util import Mm,Pt
import pptx
import os
import csv
import json
from PIL import Image # uses pillow
def autokey(x):
x = os.path.splitext(x)[0]
a = x.split("_",1)
if len(a) == 1:
return (a[0],0)
else:
return (a[0],int(a[1]))
def loadlabels(x,field="id"):
r = dict();
dr = csv.DictReader(open(x,"rb"))
for row in dr:
r[row[field]] = row
return r
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('path')
parser.add_argument('-o',"--output")
parser.add_argument('-l',"--labels")
args = parser.parse_args()
if args.labels:
ll = loadlabels(args.labels,"image")
else:
ll = {}
prs = Presentation()
fp = args.path
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
subtitle = slide.placeholders[1]
title.text = "Injectors Scans\nLab Camera, 1280x1024"
subtitle.text = "SSSA\n1st December, 2017"
knownsize = None
allsamesize = True
lpt = Pt(2.5)
done = False
bullet_slide_layout = prs.slide_layouts[1]
for x in sorted(os.listdir(fp),key=autokey):
if x.endswith(".png") or x.endswith(".jpg"):
slide = prs.slides.add_slide(bullet_slide_layout)
if knownsize is None:
im = Image.open(os.path.join(fp,x))
size = im.size
if allsamesize:
knownsize = size
else:
size = knownsize
w,h = size
r = float(w)/h # ratio
if args.labels:
id = x
print "id",id
else:
id = x[0:-4]
la = ll.get(id.lower())
title_shape = slide.shapes.title
body_shape = slide.shapes.placeholders[1]
title_shape.text = id
if body_shape.width < body_shape.height:
ow = body_shape.width
oh = ow/r
else:
oh = body_shape.height
ow = r*oh
l,t = body_shape.left, body_shape.top
pic = slide.shapes.add_picture(os.path.join(fp,x),l,t,width=ow,height=oh)
if la is not None:
pl = json.loads(la["polygon"])
if pl is not None:
lv = float(l)
tv = float(t)
s = (ow/w,oh/h)
print "polygon",pl,"scaling",ow/w,oh/h,ow
wb = slide.shapes.build_freeform(lv,tv,1.0)
wb.move_to((lv+s[0]*pl[0][0]),(tv+s[1]*pl[0][1]))
ss = [((lv+s[0]*a[0]),(tv+s[1]*a[1])) for a in pl[1:]]
wb.add_line_segments(ss)
done = True
s = wb.convert_to_shape()
s.line.width = lpt
s.fill.background()
print "as ",ss
else:
print "no polygon for",id.lower(),la["polygon"]
else:
print "unknown ",id.lower(),"in",ll.keys()
prs.save(args.output)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment