#!/bin/bash

source ~/shgen/mm_cameras.sh

#This is the case when the official fiducials are not fully shown in the images. This could happen for example when the lightbulb placed on the fiducials was broken or too dim. This caused the fiducial mark to be missing in the negative. In this case, I've used the pseudofiducials, triangles in the middle part of the edges of the photograph. 
#
#To calculate the pseudofiducials, we use an image as reference. We need to define the pixel size (0.02 mm in this case) and the pseudofiducial coordinates, in pixels, starting from the left edge and increasing clockwise. This creates a xml file with the pseudofiducial coordinates, used by MicMac
create_cam_amsdma_4fid_template $(cal_fid_from_px 0.02 1005.649 5944.503 6781.542 147.243 12575.063 5929.585 6797.768 11717.049)

#Once the pseudofiducial is created, we use a template for searching the pseudofiducials. In this case the template (2-8535.tif) is the same as the file used to calculate the pseudofiducials
create_px_4fid_template 2-8535.tif 1005.649 5944.503 6781.542 147.243 12575.063 5929.585 6797.768 11717.049

#Gradual search for pseudofiducials in the rest of the images
for thr in 0.9 0.8 0.7
do
    for win in 10 20 50 100 200 500
    do
        mm3d Kugelhupf ".*.tif" Ori-InterneScan/MeasuresIm-2-8536.tif.xml SearchIncertitude=$win Threshold=$thr
    done
done

#Image cropping
ls *.tif \
| awk '{print "mm3d ReSampFid "$1" 0.02"}' \
| parallel -j32

#Optionally we also add a black border of 90x90px to avoid using the edges of the images in the photogrammetric processing
ls OIS*.tif \
| awk '{print "convert "$1 " -crop +90+90 -crop -90-90 "$1"_crp.tif"}' \
| parallel -j16

rename 's/.tif_crp.tif/_crp.tif/g' *_crp.tif
rename 's/OIS-Reech_//' *_crp.tif
rm OIS*.tif
