-
Notifications
You must be signed in to change notification settings - Fork 1
/
linear-tiff
executable file
·1217 lines (965 loc) · 35.4 KB
/
linear-tiff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# *******************************************************
#
# linear-tiff
#
# Author: Carsten Witt <[email protected]>
# Homepage: <https://github.com/tomkyle/negatives-linear-tiff>
#
# LibRaw
# https://www.libraw.org
#
# LibRaw stems from David Coffin's dcraw:
# http://cybercom.net/~dcoffin/dcraw/
# http://cybercom.net/~dcoffin/dcraw/dcraw.1.html
#
# ImageMagick:
# http://www.imagemagick.org/script/mogrify.php
# http://www.imagemagick.org/script/convert.php
#
# GNU Parallel:
# https://www.gnu.org/software/parallel/
#
# *******************************************************
# Runtime Environment
set -o errexit
set -o nounset
set -o pipefail
# set -o xtrace
# Internal Field Separator
readonly DEFAULT_IFS="${IFS}"
readonly SAFER_IFS=$'\n\t'
IFS="${SAFER_IFS}"
# Check on Requirements
function require {
command -v "${1}" >/dev/null 2>&1 || e_error "$(printf "Program '%s' required, but it's not installed" "${1}")"
}
# Default Exit or SIGINT(2) handler
function trapCleanupTempDir() {
tmp_dir_to_clean="${WORK_TMPDIR:-}"
if [ -d "${tmp_dir_to_clean}" ]; then
printf "\nRemove temporary directory %s ... " "${tmp_dir_to_clean}"
rm -Rf "${tmp_dir_to_clean}" && e_success
fi
echo;
}
trap trapCleanupTempDir EXIT SIGINT
# --------------------------------------
# Filesystem basics
# --------------------------------------
# Filesystem basics
readonly SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
readonly SCRIPT_NAME=$(basename "${0}")
# Consistent package location
readonly HOMEBREW_OPT_DIR=$(brew --prefix "$(basename "${0}")")
# Hack for development purposes
# HOMEBREW_OPT_DIR=$SCRIPT_DIR
# Prepare (but not create) a new temp directory
readonly WORK_TMPDIR=$(mktemp -du "${TMPDIR:-/tmp/}$(basename 0).XXXXXXXXXXXX") || { e_error "Failed to create temp directory name."; }
# Where to search
declare search_directory='.'
# What to search
# The regex shown here must be suitable for regex find'ing: -iregex '.*\.(nef|raw|cr2)'
declare search_files_iregex='.*\.(nef|raw|cr2)'
# --------------------------------------
# Global settings:
# --------------------------------------
# Dcraw / dcraw_emu output
#
# Default extension of dcraw's TIFF output
readonly DCRAW_DEFAULT_OUTPUT_EXTENSION="tiff"
# Default extension for sidecar files
# created by Raw converters.
declare rawfile_sidecar_file_extension="xmp"
# Parameters for calling dcraw.
declare -a dcraw_options_array=()
# Parameters for calling mogrify.
declare -a mogrify_shave_options_array=()
declare -a mogrify_orientation_options_array=()
declare -a mogrify_crop_options_array=()
declare -a mogrify_options_array=()
# This will fix missing metadata after dcraw_emu run
declare -a exiftool_options_array=(
"-overwrite_original"
"-quiet"
)
# This will fix missing metadata after dcraw_emu run
declare -a exiftool_fix_missing_metadata=(
"-mwg:Description="""
"-mwg:Creator="""
"-Artist<mwg:Creator"
"-Make<exif:Make"
"-Model<exif:model"
"-Software<exif:software"
)
# List of possible script arguments (getopts)
# Very much like getopts, expected short options should be appended to the
# string here. Any option followed by a ':' takes a required argument.
readonly OPTIONS_LIST="achdvf:m:o:r:w:"
# --------------------------------------
# dcraw / dcraw_emu defaults
# --------------------------------------
# Clip highlights method
#
# -H 0 Clip all highlights to solid white (default).
# -H 5 as a compromise
declare -i dcraw_highlights_value=5
# Bayer demosaicing algorithm dcraw should use
#
# Possible values:
# 0 - dcraw's -q 0; use high-speed, low-quality bilinear interpolation.
# 1 - dcraw's -q 1; Variable Number of Gradients (VNG) interpolation.
# 2 - dcraw's -q 2; Patterned Pixel Grouping (PPG) interpolation.
# 3 - dcraw's -q 3; Adaptive Homogeneity-Directed (AHD) interpolation.
#
# Leave blank when not needed.
# Developer Note: no -i flag here, since variable can not be checked for being null
declare dcraw_bayer_demosaic_algorithm=3
# dcraw's output colorspace
#
# 0 Raw color (unique to each camera)
# 1 sRGB D65 (default)
# 2 Adobe RGB (1998) D65
# 3 Wide Gamut RGB D65
# 4 Kodak ProPhoto RGB D65
# 5 XYZ
# 6 ACES
declare -i dcraw_output_colorspace=4
# Dcraw's image flipping
#
# Disable with 0
# Leave blank to flip automatically.
declare dcraw_flip_image=0
# Dcraw's White balance
#
# "w" White balance according to camera settings
# at the moment of the shot
declare dcraw_white_balance="w"
# --------------------------------------
# User settings:
# These settings can be set with command line arguments.
# --------------------------------------
# Verbous mode:
# Disabled per default; enable with -v flag
declare -i verbous_mode=0;
# Grayscale output image:
# Disabled per default (0)
# Set to 1 to enable or use -d flag
declare -i desaturate_colors=0
# Resize output image:
# Disabled per default (0)
# Use with -r <width>
# or set this value to any pixel width
declare -i resize_width=0
# Trigger extra-verbous debugging mode
# Disabled per default (0)
# Set to 1 to enable or use --debug option
declare -i debug_mode=0
# Mirror output image horizontally or vertically.
# Disabled per default ("")
# Use with "-f flip|flop|flipflop"
# or set value here.
declare mirror_output=""
# Where to store the output images.
# Default ist current work directory.
#declare output_directory="${PWD}"
declare output_directory=""
# Crop method. No crop if left empty.
declare -i crop_output=0
# Star Rating threshold:
# ignore any input file which rating lesser than this value.
# Default value here is -1 (all files will be processed).
#
# * Rating typically goes from 0 to 5 'stars'
# * Rejected images should have have -1 (really? to be approved).
#
# To omit rejected images, call script with "--rating 0"
declare -i rating_threshold=-1
# Output orientation:
# * 0: Disable
# * 1: Automatically orientate image, depending on EXIF values
declare -i output_orientation=0
# --------------------------------------
# Miscellaneous
# --------------------------------------
# Formatting stuff
readonly C_WHITE='\033[1;37m'
readonly C_RED='\033[0;31m'
readonly C_GREEN='\033[0;32m'
readonly C_BLUE='\033[1;34m'
readonly C_GRAY='\033[1;30m'
readonly C_ORANGE=$(tput setaf 3)
readonly NC='\033[0m' # No Color
# Informative files
readonly LICENSE_FILE="LICENSE"
readonly USAGE_FILE="USAGE"
readonly CREDITS_FILE="CREDITS"
# --------------------------------------
# Output and formatting functions
# --------------------------------------
# Error message and error exit, redirecting stdout to stderr
function e_error {
echo -e >&2 "${C_RED}Error: ${*}${NC}";
exit 1;
}
function e_info {
echo -e "${C_BLUE}${*}${NC}"
}
function e_warning {
echo -e "${C_ORANGE}Warning: ${*}${NC}"
}
function e_success () {
printf "${C_GREEN}✔ %s${NC}" "${*-}"
if [ $debug_mode -gt 0 ]; then
echo -e ""
fi
}
function e_result () {
echo -e "${C_GREEN}${*}${NC}"
}
function e_verbous () {
if [ $verbous_mode -gt 0 ]; then
printf "${C_GRAY}%s${NC}\n" "${*}"
fi
}
function e_debug () {
if [ $debug_mode -gt 0 ]; then
printf "${C_GRAY}%s${NC}" "${*}"
fi
}
# --------------------------------------
# Create Todo file
# --------------------------------------
function createTodoFile {
mkdir -p "${WORK_TMPDIR}"
TODO_TXT="${WORK_TMPDIR}/rawfiles-todo.txt"
touch "${TODO_TXT}"
echo "${TODO_TXT}"
}
# --------------------------------------
# Count lines in file
#
# Usage:
# countLinesInFile <file>
# --------------------------------------
function countLinesInFile {
wc -l < "${1}" | sed -e 's/^[ \t]*//'
}
# --------------------------------------
# catFirstFound
#
# Outputs given file in first matching location.
#
# Usage:
# catFirstFound <file>
#
# --------------------------------------
function catFirstFound {
local file_to_cat="${1}"
local lookup=("${HOMEBREW_OPT_DIR}" "${SCRIPT_DIR}")
for dir in "${lookup[@]}"; do
if [ -f "${dir}/${file_to_cat}" ]; then
cat "${dir}/${file_to_cat}" && return
fi;
done
false
}
# --------------------------------------
# findFiles
#
# Usage:
# findFiles iregex dir
# --------------------------------------
function findFiles {
local regex=${1}
local directory=${2}
find -E "${directory}" -maxdepth 1 -type f -iregex "${regex}"
}
# --------------------------------------
# _require_argument()
#
# Usage:
# _require_argument <option> <argument>
#
# If <argument> is blank or another option, print an error message
#
# This function is stolen from William Melody's bash-boilerplate
# <https://github.com/alphabetum/bash-boilerplate>
# --------------------------------------
_require_argument() {
# Set local variables from arguments.
#
# NOTE: 'local' is a non-POSIX bash feature and keeps the variable local to
# the block of code, as defined by curly braces. It's easiest to just think
# of them as local to a function.
local _option="${1:-}"
local _argument="${2:-}"
if [[ -z "${_argument}" ]] || [[ "${_argument}" =~ ^- ]]
then
e_error "$(printf "Option requires a argument: %s\n" "${_option}")"
fi
}
# ======================================
# runBatchMode
# ======================================
function runBatchMode {
# ---------------------------------------
# Requirements
# ---------------------------------------
# Homebrew requirements
require parallel
# System commands
require getconf
# Stores all function parameters for use with GNU Parallel
local -r FUNC_ARGUMENTS=("${@}")
# For statistic purposes
local start_time=$SECONDS
local -r CPUs=$(getconf _NPROCESSORS_ONLN)
# ---------------------------------------
# Find stuff to work on
# ---------------------------------------
local -r TODO_TXT=$(createTodoFile)
findFiles "${search_files_iregex}" "${search_directory}" > "${TODO_TXT}"
local -r number_of_images=$(countLinesInFile "${TODO_TXT}")
# ---------------------------------------
# Start parallel processing
# ---------------------------------------
if [ $verbous_mode -gt 0 ]; then
printf "Process these %s images:\n" "${number_of_images}"
# When few images to be processed, cat command should be plenty
[ "${number_of_images}" -le 6 ] && cat_or_column="cat" || cat_or_column="column"
printf "${C_GRAY}%s\n${NC}" "$(${cat_or_column} "${TODO_TXT}")"
echo;
fi
if [ $debug_mode -gt 0 ]; then
echo "This is what GNU Parallel does:"
e_debug "$(parallel --dry-run -a "${TODO_TXT}" "$0" "${FUNC_ARGUMENTS[@]}" "{}")"
echo;
echo;
fi
parallel -a "${TODO_TXT}" "$0" "${FUNC_ARGUMENTS[@]}" "{}"
# ---------------------------------------
# Outro
# ---------------------------------------
# Some stats
local -r ELAPSED_TIME=$((SECONDS - start_time))
printf "Some stats:\n"
printf "CPUs used: %s\n" "${CPUs}"
printf "Elapsed time: %smin %ssec\n" $((ELAPSED_TIME/60)) $((ELAPSED_TIME%60))
printf "Done: %s images\n" "${number_of_images}"
}
# ======================================
# convertRawPhotos
#
# Usage: convertRawPhotos rawfile [rawfiles ...]
# ======================================
function convertRawPhotos {
# --------------------------------------
# Requirements
# --------------------------------------
# Homebrew dependencies
#require dcraw
require dcraw_emu
require raw-identify
require mogrify
require exiftool
require color-profiles
# System commands
require getconf
require brew
require dirname
require basename
# Files to work on.
local -r INPUT_FILES=("${@}")
# ---------------------------------------
# Linear TIFF creation:
# Build dcraw parameters
# ---------------------------------------
buildDcrawOptions
if [ $verbous_mode -gt 0 ] && [ $debug_mode -eq 0 ]; then
echo "Create linear TIFF with:"
IFS="${DEFAULT_IFS}"
e_verbous "$(printf "dcraw_emu %s\n" "${dcraw_options_array[*]}")"
IFS="${SAFER_IFS}"
fi
# ---------------------------------------
# How to mangle dcraw's output TIFF:
# Build mogrify's options string.
# ---------------------------------------
buildMogrifyOptions
if [ $verbous_mode -gt 0 ] && [ $debug_mode -eq 0 ]; then
echo "Mangle dcraw_emu output with:"
IFS="${DEFAULT_IFS}"
e_verbous "$(printf "mogrify %s\n" "${mogrify_options_array[*]}")"
IFS="${SAFER_IFS}"
fi
# ---------------------------------------
# Create output directory if needed.
# ---------------------------------------
[ ! -z "${output_directory}" ] && mkdir -p "${output_directory[*]}"
# =============================================================
# The Loop: Process each file given
# =============================================================
for RAW_PHOTO in "${INPUT_FILES[@]}"
do
local image_start_time=$SECONDS
local image_elapsed_time
local rawconvert_start_time
local rawconvert_elapsed_time
# Screen readability hack
echo;
# ---------------------------------------
# Just in case $RAW_PHOTO is NOT a regular file
# ---------------------------------------
if [ ! -f "${RAW_PHOTO}" ]; then
e_warning "$(printf '%s is not a regular file. Ignoring.' "${RAW_PHOTO}")"
continue;
fi
local input_file_basename input_file_extension xmp_sidecar_file output_tiff rating rating_file
# ---------------------------------------
# Filename magic
# ---------------------------------------
input_file_extension="${RAW_PHOTO##*.}";
input_file_basename="${RAW_PHOTO%.$input_file_extension}"
input_file_basename="${input_file_basename##*/}" # remove trailing slash
# Build output filename as dcraw would do.
# If using dcraw_emu, the output file has the original extension between.
# DCRAW
# output_tiff="${input_file_basename}.${DCRAW_DEFAULT_OUTPUT_EXTENSION}"
# DCRAW_EMU
output_tiff="${input_file_basename}.${input_file_extension}.${DCRAW_DEFAULT_OUTPUT_EXTENSION}"
# The XMP sidecar file
xmp_sidecar_file="${input_file_basename}.${rawfile_sidecar_file_extension}"
# ---------------------------------------
# Star Rating filter
# ---------------------------------------
# Where to get rating from
[ -f "${xmp_sidecar_file}" ] \
&& rating_file="${xmp_sidecar_file}" \
|| rating_file="${RAW_PHOTO}"
# Check against threshold
rating="$(exiftool -s -s -s -Rating "${rating_file}")"
if [ "${rating}" -lt "${rating_threshold}" ]; then
e_info "$(printf '%s not rated enough stars. Ignoring.' "${RAW_PHOTO}")"
continue;
fi
# ---------------------------------------
# Show some image info
# ---------------------------------------
e_info "$(raw-identify "${RAW_PHOTO}")"
[ $verbous_mode -gt 0 ] && {
e_verbous "$(raw-identify -v "${RAW_PHOTO}")"
echo;
}
# ---------------------------------------
# Call dcraw / dcraw_emu
# ---------------------------------------
printf "Linear TIFF "
IFS="${DEFAULT_IFS}"
e_debug "$(printf "\ndcraw_emu %s %s " "${dcraw_options_array[*]}" "${RAW_PHOTO}")"
rawconvert_start_time=$SECONDS
dcraw_emu "${dcraw_options_array[@]}" "${RAW_PHOTO}" || {
e_warning "$(printf "Could not create linear tiff: %s" "${RAW_PHOTO}")"
continue
}
rawconvert_elapsed_time=$((SECONDS - rawconvert_start_time))
IFS="${SAFER_IFS}"
# Just in case dcraw / dcraw_emu has NOT written an output file:
if [ ! -f "${output_tiff}" ]; then
e_warning "$(printf "Hmmm. Expected dcraw_emu to have written '%s'; In fact, this file does not exist?\n" "${output_tiff}")"
continue
fi
e_success ""
# ---------------------------------------
# Repair missing metadata
# ---------------------------------------
printf "Meta tags "
if exiftool "${exiftool_options_array[@]}" "${exiftool_fix_missing_metadata[@]}" "${output_tiff}"; then
IFS="${DEFAULT_IFS}"
e_debug "$(printf "\nexiftool %s %s " "${exiftool_options_array[*]}" "${exiftool_fix_missing_metadata[*]}")"
IFS="${SAFER_IFS}"
e_success ""
else
e_warning "Fixing meta tags with exiftool failed."
fi
# ---------------------------------------
# Consider individual image crop settings
# ---------------------------------------
if [ $crop_output -gt 0 ]; then
printf "Prepare cropping "
buildMogrifyCropOptions "${RAW_PHOTO}" "${xmp_sidecar_file}" "${output_tiff}" && {
IFS="${DEFAULT_IFS}"
e_debug "$(printf "\n%s " "${mogrify_shave_options_array[*]}" "${mogrify_crop_options_array[*]}")"
IFS="${SAFER_IFS}"
}
e_success ""
fi
# ---------------------------------------
# Consider image orientation settings
# ---------------------------------------
if [ $output_orientation -gt 0 ]; then
printf "Prepare orientation "
buildMogrifyOrientationOptions "${RAW_PHOTO}" "${xmp_sidecar_file}" && {
IFS="${DEFAULT_IFS}"
e_debug "$(printf "\n%s " "${mogrify_orientation_options_array[*]}" )"
IFS="${SAFER_IFS}"
e_success ""
}
fi
# ---------------------------------------
# Handle output file
# ---------------------------------------
printf "Mangle output file "
IFS="${DEFAULT_IFS}"
e_debug "$(printf "\nmogrify %s %s %s %s " "${mogrify_shave_options_array[*]}" "${mogrify_crop_options_array[*]}" "${mogrify_orientation_options_array[*]}" "${mogrify_options_array[*]}")"
(mogrify "${mogrify_shave_options_array[@]}" "${mogrify_crop_options_array[@]}" "${mogrify_orientation_options_array[@]}" "${mogrify_options_array[@]}" "${output_tiff}") || {
e_warning "$(printf "Hmmm. Mogrifying failed somehow on %s\n" "${output_tiff}")"
continue
}
e_success ""
IFS="${SAFER_IFS}"
# Prepare result output
local result_file="${output_tiff}"
# ---------------------------------------
# Move output file to directory, if required
# ---------------------------------------
if [ ! -z "${output_directory}" ]; then
mv "${output_tiff}" "${output_directory}/"
result_file="${output_directory}/${output_tiff}"
fi
# ---------------------------------------
# Print result
# ---------------------------------------
printf "Result %s\n" "$(e_result "${result_file}")"
# ---------------------------------------
# Per-image stats
# ---------------------------------------
image_elapsed_time=$((SECONDS - image_start_time))
e_verbous "$(printf "Elapsed time: %smin %ssec\n" $((image_elapsed_time/60)) $((image_elapsed_time%60)))"
e_verbous "$(printf "Raw conversion: %smin %ssec\n" $((rawconvert_elapsed_time/60)) $((rawconvert_elapsed_time%60)))"
done
}
# ======================================
# buildDcrawOptions
# ======================================
function buildDcrawOptions {
# Add white balance setting
[ "${dcraw_white_balance}" = "w" ] && dcraw_options_array+=(-w)
# Add flip image setting
[ -n "${dcraw_flip_image}" ] && dcraw_options_array+=(-t ${dcraw_flip_image})
# How to handle highlights
[ $dcraw_highlights_value -gt 0 ] && dcraw_options_array+=(-H ${dcraw_highlights_value})
# Add demosaicing algorithm number
[ -n "${dcraw_bayer_demosaic_algorithm}" ] && dcraw_options_array+=(-q ${dcraw_bayer_demosaic_algorithm})
# Colorspace
dcraw_options_array+=(-o ${dcraw_output_colorspace})
# 16 bit linearity, same as "-6 -W -g 1 1".
dcraw_options_array+=(-4)
# Output TIFF instead of PPM. If disabling this,
# do not forget to redefine DCRAW_DEFAULT_OUTPUT_EXTENSION
dcraw_options_array+=(-T)
### This is tooo noisy....
# [ "${verbous_mode}" -gt 0 ] && dcraw_options="-v ${dcraw_options}"
}
# ======================================
# hasEmbeddedJpeg <input_file>
#
# Check if there is either JpgFromRaw or PreviewImage entry in exif data.
# Returns true/0 or false/1 otherwise
# ======================================
function hasEmbeddedJpeg {
local input_file="${1}"
has_embedded_jpg="$(exiftool -s -s -s -JpgFromRaw -PreviewImage "${input_file}")"
[ -n "${has_embedded_jpg}" ]
}
# ======================================
# buildMogrifyShaveOptions
#
# Create Shave parameter to eliminate the difference between
# RAW pixel size and the size displayed in Raw converters.
# Example: While the NEF file is 6016x4016 pixels,
# Adobe Camera Raw will display 6000x4000, according to the embedded JPG thumbnail.
#
# Usage: buildMogrifyShaveOptions <input_file> <output_file>
# ======================================
function buildMogrifyShaveOptions {
# Requirements
require exiftool
local input_file="${1}"
local output_file="${2}"
local output_width output_height;
local has_embedded_jpg thumbnail_width thumbnail_height;
local shave_horizontal shave_vertical;
# Grab dcraw/dcraw_emu's output image dimensions
output_width="$(exiftool -s -s -s -ImageWidth "${output_file}")"
output_height="$(exiftool -s -s -s -ImageHeight "${output_file}")"
# Try to calculate thumbnail dimensions from embedded JPG
thumbnail_width=$output_width
thumbnail_height=$output_height
hasEmbeddedJpeg "${input_file}" && {
local temp_thumbnail; temp_thumbnail=$(mktemp -u "${TMPDIR:-/tmp/}$(basename 0).XXXXXXXXXXXX") || { e_error "Failed to create temp file."; }
local filetype; filetype="$(exiftool -s -s -s -FileType "${input_file}")"
case "${filetype}" in
NEF)
exiftool -b -JpgFromRaw "${input_file}" > "${temp_thumbnail}"
;;
CR2)
exiftool -b -PreviewImage "${input_file}" > "${temp_thumbnail}"
;;
*)
;;
esac
thumbnail_width="$(exiftool -s -s -s -ImageWidth "${temp_thumbnail}")"
thumbnail_height="$(exiftool -s -s -s -ImageHeight "${temp_thumbnail}")"
}
# Calculate shaving
shave_horizontal=$(echo "(${output_width} - ${thumbnail_width}) / 2" | bc -l)
shave_vertical=$(echo "(${output_height} - ${thumbnail_height}) / 2" | bc -l)
# Prepare result
if [ -n "${shave_horizontal}" ] && [ -n "${shave_vertical}" ] ; then
shave_horizontal=$(LC_ALL=C printf "%.*f\n" 1 "${shave_horizontal}")
shave_vertical=$(LC_ALL=C printf "%.*f\n" 1 "${shave_vertical}")
mogrify_shave_options_array+=(-shave "${shave_horizontal}x${shave_vertical}")
fi;
}
# ======================================
# buildMogrifyCropOptions
# Usage: buildMogrifyCropOptions <input_file> <xmp_sidecar> <output_file>
# ======================================
function buildMogrifyCropOptions {
# Requirements
local input_file="${1}"
local xmp_file="${2}"
local output_file="${3}"
# -----------------------------------------
# Construct the crop parameters
# -----------------------------------------
# 1. Check if crop data is in either work_file or XMP sidecar
local work_file="${input_file}"
local has_crop;
has_crop="$(exiftool -s -s -s -HasCrop "${work_file}")"
if [ "${has_crop}" != "True" ] && [ -f "${xmp_file}" ]; then
has_crop="$(exiftool -s -s -s -HasCrop "${xmp_file}")"
if [ "${has_crop}" = "True" ]; then
work_file="${xmp_file}"
fi
fi
if [ "${has_crop}" != "True" ]; then
return 1
fi
# 2. Do calculations
if [ "${has_crop}" = "True" ]; then
local image_width image_height;
local CropTop CropBottom CropLeft CropRight;
local width_perc height_perc offset_horizontal offset_vertical;
# Grab original image dimensions
image_width="$(exiftool -s -s -s -ImageWidth "${input_file}")"
image_height="$(exiftool -s -s -s -ImageHeight "${input_file}")"
# Shave first...
buildMogrifyShaveOptions "${input_file}" "${output_file}"
# Fetch percentage
CropTop="$(exiftool -s -s -s -CropTop "${work_file}")"
CropBottom="$(exiftool -s -s -s -CropBottom "${work_file}")"
CropLeft="$(exiftool -s -s -s -CropLeft "${work_file}")"
CropRight="$(exiftool -s -s -s -CropRight "${work_file}")"
# Calc remaining width and height, after crop, in percentage.
width_perc=$(echo "($CropRight - $CropLeft) * 100" | bc -l)
width_perc=$(LC_ALL=C printf "%.*f\n" 1 "${width_perc}")
height_perc=$(echo "($CropBottom - $CropTop) * 100" | bc -l)
height_perc=$(LC_ALL=C printf "%.*f\n" 1 "${height_perc}")
# Calc offsets in pixel
offset_horizontal=$(echo "$image_width * $CropLeft" | bc -l)
offset_horizontal=$(LC_ALL=C printf "%.*f\n" 1 "${offset_horizontal}")
offset_vertical=$(echo "$image_height * $CropTop" | bc -l)
offset_vertical=$(LC_ALL=C printf "%.*f\n" 1 "${offset_vertical}")
# 3. Finally, add crop information
mogrify_crop_options_array+=(-crop "${width_perc}%x${height_perc}%+${offset_horizontal}+${offset_vertical}")
fi
}
# ======================================
# buildMogrifyProfileOptions
# Usage: buildMogrifyProfileOptions [colorspace]
#
# colorspace: 1|gray When image shall be grayscaled
# ======================================
function buildMogrifyProfileOptions {
# Requirements
local colorspace="${1:-0}"; shift;
local icc_profile_path=""
case "${colorspace}" in
gray|1)
# Desaturate colors, if required,
# using a linear Gamma 1.0 Gray profile
icc_profile_path=$(color-profiles gray-linear )
;;
*)
# Default ICC profile for color value.
# Should match DRAW_COLORSPACE_VALUE.
#
# Seems this is not needed as dcraw output image comes with profile
# icc_profile_path=$(color-profiles srgb-linear )
;;
esac
if [ -n "${icc_profile_path}" ]; then
mogrify_options_array+=(-profile "${icc_profile_path}")
fi
}
# ======================================
# buildMogrifyFlipFlopOptions
# Usage: buildMogrifyFlipFlopOptions [option]
# ======================================
function buildMogrifyFlipFlopOptions {
# Requirements
local mirror_output="${1:-}"; shift;
case "${mirror_output}" in
flipflop|vh|both)
mogrify_options_array+=(-flip -flop)
;;
flip|v|vertical)
mogrify_options_array+=(-flip)
;;
flop|h|horizontal)
mogrify_options_array+=(-flop)
;;
*)
;;
esac
}
# ======================================
# buildMogrifyOrientationOptions
# Usage: buildMogrifyOrientationOptions <input_file> <xmp_sidecar>
# ======================================
function buildMogrifyOrientationOptions {
# Requirements
local input_file="${1}"
local xmp_file="${2}"
local orient work_file;
# Where to read orientation from.
# XMP overrides original RAW.
[ -f "${xmp_file}" ] \
&& work_file="${xmp_file}" \
|| work_file="${input_file}"
# Grab orientation from meta data
orient="$(exiftool -s -s -s -n -Orientation "${work_file}")"
case "${orient}" in
1)
# Just normal orientation
;;
6)
mogrify_orientation_options_array+=(-rotate "90")
;;
3)
mogrify_orientation_options_array+=(-rotate "180")
;;
8)
mogrify_orientation_options_array+=(-rotate "270")
;;
*)
e_warning "$(printf 'Unexpected orientation value %s found in %s. Ignoring.' "${orient}" "${work_file}")"
return 1
;;
esac
}
# ======================================
# buildMogrifyResizeOptions
# Usage: buildMogrifyResizeOptions <size>
# ======================================
function buildMogrifyResizeOptions {
# Requirements
local resize_width="${1}"
# Resize image on its larger side
if [ "${resize_width}" -gt 0 ]; then
mogrify_options_array+=(-resize "${resize_width}x${resize_width}>")
fi
}
# ======================================
# buildMogrifyOptions
#
# Build the complete mogrify options string
# for mangling the dcraw output image
# ======================================
function buildMogrifyOptions {