Adding captions to images with Python

So I wanted to add captions to a set of images and wrote some lines of Python. Python has some cool image libraries so the job was real easy. Have never used Python before except to write some kindergarten-level programs, so this may not be the best way to code the thing. But it does the job.

	import Image, ImageDraw, ImageFont, os

	pathz="/home/thameera/ws/img_caption/pics"
	if os.path.exists(pathz) and os.path.isdir(pathz):
		for name in os.listdir(pathz):
			print name
			fullname=pathz+'/'+name
			im = Image.open(fullname)
			namez=name[:-4]
			d = ImageDraw.Draw(im)
			f = ImageFont.truetype("Arial.ttf", 16)
			d.text((4,0), namez, font=f)
			im.save(fullname)

	else:
		print "Directory not found"
 

It scans the given images directory and adds the file name sans extension as a caption, as shown below:


Original:will.i.am_1.jpg
   
After adding the caption

5 responses on “Adding captions to images with Python

Leave a Reply

Your email address will not be published. Required fields are marked *