#   exportUndistordPhoto.py
#
#   Original file by Pierre Drap, Pierre.Drap@gmail.com
#   CNRS, LIS laboratory, Aix-Marseille University, France
#   December 14th 2018
#   Photoscan 1.4.0
#
#
#   Please feel free to use, share and modify this file
#
#  Exportingal the n orthophoto  named from 0.jpg to (n-1).jpg according to the order in the photoscan camera list
#  It work with the active chunk
#  The scrip ask you to choose a folder in which the undistorded photo will be stored
#
#  Caution: currently this script produce orthophto assuming square pixel and setting the principal point at the center
#     
#  if you use these images for example to make a bridge between Photoscan and Reality Capture
#  it is better to follow this procedure:
#
#    - export undistorded image using this script from the active chunk
#    - go in camera calibration 
#           - cancel distortion (all parameters in Photoscan) of the sensors 
#           - set cx and cy to 0
#    - export camera : file / export / camera in Bundler (*.out) format cameras in Bundler format
#
#



import PhotoScan
from math import* 
import datetime
import sys
import os.path

#============================================================
#//////////////////////////////////////////////////////////
# Main function
def main():
	print("Beginning of the script.")
	doc = PhotoScan.app.document
	chunk = doc.chunk
	ncam =0;
	path = PhotoScan.app.getExistingDirectory("Select a folder to save undistorted image ")
	for camera in chunk.cameras:
		print("camera label "+camera.label)
		print("camera num   "+str (ncam))
		name = path+"/"+str (ncam)+".jpg"
		ncam =  ncam+1
		for plane in camera.planes:
			img = plane.image()
			calib = plane.sensor.calibration
			imgu = img.undistort(calib, True, True)
			print("          name "+name)
			imgu.save(name)
	print("End of the script.")
	
#=============================================
#/////////////////////////////////////////////
# Start
if __name__ == "__main__":
	main()