Skip to content

Instantly share code, notes, and snippets.

@gerwin3
Created July 22, 2017 10:41
Show Gist options
  • Save gerwin3/a3c131a1503d4205b2276e76fc04bc7f to your computer and use it in GitHub Desktop.
Save gerwin3/a3c131a1503d4205b2276e76fc04bc7f to your computer and use it in GitHub Desktop.
Python - Drawing True North line on equirectangular picture based on GPano:PoseHeadingDegrees
#
# Dependencies:
# - pip install Pillow (easy_install Pillow works as well)
#
import os
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw, ImageFont
def get_xmp_heading(fname):
xmpstart = '<x:xmpmeta'
xmpend = '</x:xmpmeta>'
binary_encoding = 'latin-1'
open_mode = 'r'
gpano_heading_tag = '{http://ns.google.com/photos/1.0/panorama/}PoseHeadingDegrees'
with open(fname, open_mode, encoding=binary_encoding) as f:
contents = str(f.read())
# extract xmp data
xmpdata = contents[contents.find(xmpstart):contents.find(xmpend) + len(xmpend)]
xmp = ET.fromstring(xmpdata)
# find GPano:PoseHeadingDegrees tag in subtree of XMP
# data recusively and take the first result
gpano_heading = next(xmp.iter(gpano_heading_tag)).text
return float(gpano_heading)
def watermark_north(fname, degrees, fname2 = None):
save_format = 'PNG'
if fname2 is None:
_, extension = os.path.splitext(fname)
fname2 = filename.replace(extension, '-e' + extension)
image1 = Image.open(fname).convert('RGBA')
w = image1.size[0]
h = image1.size[1]
# calculate offset x, the amount of pixels converted
# from the number of degrees
offset = (degrees / 360) * w
# calculate actual x coordinate of true north line
x2 = (w / 2) - offset
if x2 < 0:
# if x2 is negative, wrap around width of image
x2 = w + x2
# draw true north line on image
draw = ImageDraw.Draw(image1)
draw.line([(x2, 0), (x2, h)], fill=128, width=8)
# print degrees for debugging
draw.text((10, 10), str(degrees), font=ImageFont.truetype('arial.ttf', 100), fill=255)
del draw
image1.save(fname2, save_format)
filename = "input.jpg"
degrees = get_xmp_heading(filename)
watermark_north(filename, degrees)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment