Reinhard tonemapping on CR2 RAW image in Python

I’m currently trying to convert a large amount of CR2 RAW images to TIFF - and I need to apply a Reinhard tonemap to account for the exposure and contrast of the images to get a more consistent result.

However, after extensive google-fu, I have run into a bit of a wall. I can successfully save out the TIFF by loading the CR2 with rawpy and converting it to BGR and saving it back out as such, but the Reinhard tonemap is throwing an error that I can’t decipher.

Here’s my code as of now:

import rawpy
import cv2

raw = rawpy.imread("input.cr2")
rgb = raw.postprocess()

image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)

reinhard_tonemap = cv2.createTonemapReinhard(4.0, 0.2, 1.0, 0.0)
processed_image = reinhard_tonemap.process(image)

cv2.imwrite("output.tiff", processed_image)

This throws the following error:

Traceback (most recent call last):
  File "cr2_to_tiff.py", line 10, in <module>
    processed_image = reinhard_tonemap.process(image)
cv2.error: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv\modules\photo\src\tonemap.cpp:69: error: (-215:Assertion failed) _src.dims() == 2 && _src.type() == CV_32FC3 in function 'cv::TonemapImpl::process'

Based on my loose understanding of the point of error;

It seems I may be feeding it the wrong kind of data, as it seems to expect a Mat, and not a numpy.ndarray, which is what cvtColor returns. I have tried using cv2.imread to load the image, but it returns none, as presumably it doesn’t know how to handle raw images?

What gives? Am I even on the right track?

you’re on the right track, however, it needs float pixel input, like

image.astype('float32')
1 Like

Brilliant, thank you! Worked like a charm - for future reference, where would this be documented?

for one, the assertion says what it expects:

And there’s some documentation that you follow up the inheritance until you find your process() method:

that’s the same. OpenCV adapts between cv::Mat and numpy array. there is no “Mat” in the python bindings. this is a fundamental aspect of how OpenCV works when used from Python.

1 Like