Raw2hdr with CR2 files from Canon

I have a canon 5D and i am shooting in raw, as you probably familiar, canon uses proprietary CR2.

I have been trying with no success to generate an hdr image until now.

With the help of chatgpt, we debugged the raw2hdr script and we made the following changes:

:key: Key Differences from the Original Script

  1. Simplified input pipeline
  • The original script used dcraw -t 0 -4 | ra_ppm | ra_tiff to generate 16-bit TIFFs.
  • This failed because your build of hdrgen did not support TIFF/PPM/HDR inputs.
  • The new script uses dcraw -t 0 -h -w -c | pnmtojpeg to create 8-bit JPGs, which your hdrgen accepts (24-bit RGB requirement).
  1. Removed Radiance utilities dependency
  • No more use of ra_ppm, ra_tiff, or Radiance .hdr intermediate files.
  • Conversion goes directly from RAW → JPG with Netpbm/ImageMagick tools.
  1. Stonits calculation reimplemented with awk
  • The original script relied on rcalc + /tmp/rawinfo.fmt to parse dcraw -i -v output.
  • This broke because field names in your dcraw version didn’t match the expected format.
  • The new script parses dcraw output directly with awk to compute exposure scaling (stonits).
  1. Temporary file handling simplified
  • Original script created multiple temp files (rawinfo.fmt, rawinfo$.txt, .tif, etc.) and deleted them at the end.
  • New script only creates:
    • /tmp/rawinfo-debug.txt (metadata),
    • /tmp/hdrgen-args.txt (hdrgen arguments),
    • /tmp/sqr.rsp (response pattern),
    • plus the temporary JPGs.
  • All are cleaned up automatically at the end of the run.
  1. Removed unsupported/legacy options
  • No use of -q, -m, -r, -s parsing inside hdrgen setup.
  • Script only supports the essential option: -o <output.hdr> input.CR2....

Of course i am not completly sure if the changes are acceptable, so i would like to consult it with you, experts. I am attaching the new script.

I have not been able, until now, to generate hdr from my canon camera, tried using jpg, dngs converted from dnglab until now.

Should i consider another approach ?

Here is the script


#!/bin/bash
#
# raw2hdr - Generar imagen HDR a partir de CR2 usando dcraw + hdrgen
#
# Uso:
#   raw2hdr -o salida.hdr *.CR2
#

if [ $# -lt 2 ]; then
    echo "Uso: $0 -o salida.hdr input1.CR2 input2.CR2 ..."
    exit 1
fi

# --- Parseo de argumentos ---
outfile=""
args=()
while [ $# -gt 0 ]; do
    case "$1" in
        -o)
            shift
            outfile="$1"
            ;;
        *)
            args+=("$1")
            ;;
    esac
    shift
done

if [ -z "$outfile" ]; then
    echo "Falta -o salida.hdr"
    exit 1
fi

# --- Archivos temporales ---
rawinfo="/tmp/rawinfo-debug.txt"
hdrgen_args="/tmp/hdrgen-args.txt"
sqr="/tmp/sqr.rsp"

# 1. Extraer metadatos de CR2
echo "Extrayendo metadatos con dcraw..."
dcraw -i -v "${args[@]}" > "$rawinfo"

# Normalizar shutter en decimal si viene como fracciĂłn
perl -pi -e 'if (my $test = /^Shutter: (.*)\/(.*) sec/) { my $speed = sprintf("%0.9f",$1/$2); s/^Shutter: $1\/$2 sec/Shutter: $speed sec/ }' "$rawinfo"

# 2. Convertir cada CR2 a JPG 8-bit (24-bit RGB que hdrgen acepta)
echo "Generando JPGs 8-bit..."
jpgs=()
for f in "${args[@]}"; do
    base="${f%.*}"
    outjpg="${base}_ldr.jpg"
    dcraw -t 0 -h -w -c "$f" | pnmtojpeg > "$outjpg"
    jpgs+=("$outjpg")
done

# 3. Calcular stonits y armar args para hdrgen
echo "Calculando stonits..."
awk '
/^Filename:/ {
  if (have) {
    stonits = 161 * ap * ap / (spd * iso);
    printf("-s %.6f %s_ldr.jpg\n", stonits, img);
  }
  fname = $2; sub(/\r$/,"",fname);
  split(fname, a, "."); img = a[1];
  iso = spd = ap = 0; have = 0;
}
/^(ISO speed:|ISO:)/ { iso = $NF + 0; }
/^Shutter:/ {
  if ($2 ~ /\//) { split($2, a, "/"); spd = a[1] / a[2]; }
  else           { spd = $2 + 0; }
}
/^Aperture:/ { sub(/^Aperture: f\//,""); ap = $0 + 0; }
{ if (img != "" && iso > 0 && spd > 0 && ap > 0) have = 1; }
END {
  if (have) {
    stonits = 161 * ap * ap / (spd * iso);
    printf("-s %.6f %s_ldr.jpg\n", stonits, img);
  }
}
' "$rawinfo" > "$hdrgen_args"

# 4. Crear archivo de respuesta (patrĂłn cuadrado)
cat > "$sqr" << _EOF_
2 1 0 0
2 1 0 0
2 1 0 0
_EOF_

# 5. Ejecutar hdrgen
echo "Ejecutando hdrgen..."
hdrgen -m 400 -e -a -r "$sqr" -o "$outfile" $(cat "$hdrgen_args")
res=$?

# 6. Limpiar temporales
rm -f "$rawinfo" "$hdrgen_args" "$sqr"
rm -f "${jpgs[@]}"

exit $res

This is not very helpful. Where did you get this raw2hdr bash script? Was it created from the original C-shell script, or from the Perl script? These original scripts never called ra_ppm, and that is just the beginning of what’s wrong with ChatGPT’s reworking of it.

We really need to avoid replacing the experts on this forum with bad advice from ChatGPT. I am tempted to delete this post, but I would rather it stand as an example of what not to offer on the forum. In the end, it only confuses people with wrong answers and feeds back to create a downward spiral of bad ideas and ill-considered directions.

First, Canon CR2 format is proprietary as you say, as are most all “Camera RAW” formats, which is why we need dcraw.

Second, using JPEG files as an intermediary is not a good solution, unless you set the maximum quality and make sure the gamma value fits with the response function.

Rather than discussing the non-sense going on here, I will repost the original C-shell and Perl scripts, and hope that people go from these rather than what you have from ChatGPT.

Best,
-Greg

#!/bin/csh -f
#
# Convert camera RAW file to HDR image
# Based on dcraw version 8.94 (May 15, 2009)
# Also requires hdrgen and exiftool
#
if ($#argv < 1) then
	echo "Usage: $0 [hdrgen opts][-h][-w][-n nproc] -o output.hdr input1.raw .."
	exit 1
endif
set td=/tmp/r2hdr$$
# Calibration factor for our camera:
set calib_fact=1
set bscale=1.1
set nprocs=1
set dcraw=(dcraw -c -o 2 -t 0 -W -g 2 0 -T)
set exiftags=( -GPSDateStamp -GPSTimeStamp -GPSLatitude -GPSLatitudeRef \
	-GPSLongitude -GPSLongitudeRef -GPSAltitude -GPSAltitudeRef \
	-ImageOrientation -CameraOrientation \
	-FocalLengthIn35mmFormat -UserComment -FocusDistance\>SubjectDistance \
	'-PrimaryChromaticities=0.64 0.33 0.21 0.71 0.15 0.06' )
set hdrgen=(hdrgen -m 400 -e -a -c AdobeRGB -r $td/sqr.rsp)
while ($#argv > 1)
	switch ($argv[1]:q)
	case -c:
		shift argv
		set hdrgen=($hdrgen:q -c $argv[1])
		breaksw
	case -o:
		shift argv
		set outfile="$argv[1]"
		set hdrgen=($hdrgen:q -o $outfile:q)
		breaksw
	case -q:
		shift argv
		set hdrgen=($hdrgen:q -q $argv[1])
		breaksw
	case -m:
		shift argv
		set hdrgen=($hdrgen:q -m $argv[1])
		breaksw
	case -F:
		set force_write
	case -a:
	case -e:
	case -f:
	case -g:
	case -x:
		set hdrgen=($hdrgen:q $argv[1])
		breaksw
	case -r:
	case -s:
		echo "hdrgen $argv[1] option not supported"
		exit 1
	case -h:
	case -w:
		set dcraw=($dcraw:q $argv[1])
		breaksw
	case -b:
		shift argv
		set bscale=$argv[1]
		breaksw
	case -n:
		shift argv
		set nprocs=$argv[1]
		breaksw
	default:
		if ("$argv[1]" =~ "-*") then
			echo "Unknown option: $argv[1]"
			exit 1
		endif
		break
	endsw
	shift argv
end
set dcraw=($dcraw:q -b $bscale)
if (! $?outfile) then
	echo "Missing -o output file specification"
	exit 1
endif
if (! $?force_write && -f $outfile:q ) then
	echo "${outfile}: file exists"
	exit 1
endif
set res=2
onintr quit
mkdir $td
cat > $td/sqr.rsp << _EOF_
2 $calib_fact 0 0
2 $calib_fact 0 0
2 $calib_fact 0 0
_EOF_
set np=$nprocs
foreach rawfile ($argv:q)
	set tiff="$td/$rawfile:t"
	set tiff="$tiff:r.tif"
	if ($nprocs > 1) then
		( $dcraw $rawfile:q > $tiff:q ; \
			exiftool -q -overwrite_original \
				-TagsFromFile $rawfile:q $exiftags:q $tiff:q ) &
		@ np--
		if ($np <= 0) then
			wait
			set np=$nprocs
		endif
	else
		$dcraw -v $rawfile:q > $tiff:q
		exiftool -overwrite_original \
			-TagsFromFile $rawfile:q $exiftags:q $tiff:q
	endif
	set hdrgen=($hdrgen:q $tiff:q)
end
if ($np != $nprocs) wait
$hdrgen:q
set res=$status
quit:
rm -rf $td
exit $res
#!/usr/bin/perl -w
#
# Convert camera RAW file to HDR image
# Based on dcraw version 8.94 (May 15, 2009)
# Also requires hdrgen and exiftool
#
if ($#ARGV < 0) {
	print "Usage: raw2hdr [hdrgen opts][-h][-w][-C calib][-c cspace] -o output.hdr input1.raw ..\n";
	exit 1;
}
my $td = `mktemp -d /tmp/raw2hdr.XXXXXX`;
chomp $td;
# Calibration factor for our camera:
my $calib_fact = 1;
my $bscale = 1.1;
my @dcraw = qw(dcraw -c -t 0 -W -g 2 0 -T);
my @exiftags = qw( -GPSDateStamp -GPSTimeStamp -GPSLatitude -GPSLatitudeRef
	-GPSLongitude -GPSLongitudeRef -GPSAltitude -GPSAltitudeRef
	-Orientation -ImageOrientation -CameraOrientation
	-FocalLengthIn35mmFormat -UserComment -FocusDistance\>SubjectDistance );
my @hdrgen = "hdrgen -m 400 -e -a -r $td/sqr.rsp";
my $ocs = "sRGB";
my $force_write = 0;
my $outfile;
while ($#ARGV >= 0) {
	if ("$ARGV[0]" eq "-c") {
		shift @ARGV;
		$ocs = $ARGV[0];
	} elsif ("$ARGV[0]" eq "-C") {
		shift @ARGV;
		$calib_fact = $ARGV[0];
	} elsif ("$ARGV[0]" eq "-K") {
		push @hdrgen, @ARGV[0..4];
		shift @ARGV for (1..4);
	} elsif ("$ARGV[0]" eq "-o") {
		shift @ARGV;
		$outfile = $ARGV[0];
		push @hdrgen, "-o $outfile";
	} elsif ("$ARGV[0]" =~ /^-[qmp]$/) {
		push @hdrgen, "$ARGV[0] $ARGV[1]";
		shift @ARGV;
	} elsif ("$ARGV[0]" eq "-m") {
		shift @ARGV;
		push @hdrgen, "-m $ARGV[0]";
	} elsif ("$ARGV[0]" eq "-F") {
		$force_write = ! $force_write;
	} elsif ("$ARGV[0]" =~ /^-[aefgx]$/) {
		push @hdrgen, $ARGV[0];
	} elsif ("$ARGV[0]" =~ /^-[rs]$/) {
		print "hdrgen $ARGV[0] option not supported";
		exit 1;
	} elsif ("$ARGV[0]" =~ /^-[hw]$/) {
		push @dcraw, $ARGV[0];
	} elsif ("$ARGV[0]" eq "-b") {
		shift @ARGV;
		$bscale = $ARGV[0];
	} elsif ("$ARGV[0]" =~ /^-./) {
		print "Unknown option: $ARGV[0]\n";
		exit 1;
	} else {
		last;
	}
	shift @ARGV;
}
if (not $outfile) {
	print "Missing -o output file specification\n";
	exit 1;
}
if ($force_write) {
	push @hdrgen, "-F";
} elsif (-e $outfile) {
	print "$outfile: file exists\n";
	exit 1;
}
if ("$ocs" eq "XYZ") {
	# CIE XYZ
	push @dcraw, "-o 5";
	push @exiftags, "'-PrimaryChromaticities=1.00 0.00 0.00 1.00 0.00 0.00'",
			"'-WhitePoint=.3333 .3333'";
} elsif ("$ocs" eq "AdobeRGB") {
	# Adobe RGB (1998)
	push @dcraw, "-o 2";
	push @exiftags, "'-PrimaryChromaticities=0.64 0.33 0.21 0.71 0.15 0.06'",
			"'-WhitePoint=.3127 .3290'";
} elsif ("$ocs" eq "sRGB") {
	# sRGB is dcraw default and what hdrgen expects on input
	push @dcraw, "-o 1"
} else {
	die "Unsupported output color space";
}
push @hdrgen, "-c $ocs";
push @dcraw, "-b $bscale";
open OUTF, '>', "$td/sqr.rsp";
print OUTF "2 $calib_fact 0 0\n" x 3;
close OUTF;
foreach my $rawfile (@ARGV) {
	$_ = $rawfile;
	s|.*/||g;
	s/\.[^.]*$/.tif/;
	my $tiff = "$td/$_";
	system "@dcraw -v $rawfile > $tiff" and die 'dcraw failed';
	system "exiftool -overwrite_original -TagsFromFile '$rawfile' @exiftags $tiff";
	push @hdrgen, $tiff;
}
print "Executing: @hdrgen\n";
my $res = system "@hdrgen";
system "rm -rf $td";
exit $res;