Revision history [back]

On a related note...

Personally I needed to find the absdiff between a float64 (Array "a") and a uint8 (Array "b"). The cv2.absdiff function sadly does not take a data output type, so it complained with the same error as in your post, saying that the two input arrays were different types.

One solution, a BAD solution, is to write: cv2.absdiff(a, b.astype(np.float64))... But this astype call causes Numpy to allocate brand new array memory and copy all values there. Very wasteful.

The final solution, which is almost 50% faster, was to stop using OpenCV's nerfed "absdiff" and instead achieving the result as follows: foo = cv2.subtract(a, b, dtype=cv2.CV_64F) which forces the result-array to be float64, and successfully handles subtracting floats from ints or vice versa. Next, you simply do np.abs(foo, out=foo) to tell Numpy to do an in-place overwriting of each array value with their absolute value, which avoids having to create a brand new array for the abs output.

In short: If OpenCV complains about comparing different types, you have to first of all specify the "greatest common denominator" type in your call to cv2.subtract (or cv2.add or similar). And secondly, if you want absolute values, you simply use Numpy's built-in function and give it the same output as the input to make it do an in-place overwrite.

I hope this helps someone else who chases maximum performance!

On a related note...

Personally I needed to find the absdiff between a float64 (Array "a") and a uint8 (Array "b"). The cv2.absdiff function sadly does not take a data output type, so it complained with the same error as in your post, saying that the two input arrays were different types.

One solution, a BAD solution, is to write: cv2.absdiff(a, b.astype(np.float64))... But this astype call causes Numpy to allocate brand new array memory and copy all values there. Very wasteful.

The final solution, which is almost 50% faster, was to stop using OpenCV's nerfed "absdiff" and instead achieving the result as follows: foo = cv2.subtract(a, b, dtype=cv2.CV_64F) which forces the result-array to be float64, and successfully handles subtracting floats from ints or vice versa. Next, you simply do np.abs(foo, out=foo) to tell Numpy to do an in-place overwriting of each array value with their absolute value, which avoids having to create a brand new array for the abs output.

In short: If OpenCV complains about comparing different types, you have to first of all specify the "greatest common denominator" type in your call to cv2.subtract (or cv2.add or similar). similar) via the dtype= parameter. And secondly, if you want absolute values, you simply use Numpy's built-in function and give it the same output as the input to make it do an a very fast in-place overwrite.

I hope this helps someone else who chases maximum performance!