During my learning process of OpenCV-Python, I encountered an issue. My environment uses Python version 3.13, NumPy version 2.2.6, and OpenCV-Python version 4.12.
In the "Arithmetic Operations on Images" section of the official documentation, it mentions the difference between OpenCV addition and NumPy addition: OpenCV addition is a saturated operation while NumPy addition is a modulo operation. Official documentation page
However, the actual results I obtained during computation differ from the values provided in the documentation.
My code:
import cv2 as cv
import numpy as np
x = np.uint8([250])
y = np.uint8([10])
print(f"x+y = {x+y}")
print(f"cv.add(x,y) = {cv.add(x,y)}")
Official documentation result:
[4]
[[255]]
My result:
[4]
[[260.]
[0.]
[0.]
[0.]]
I checked cv.add(x,y).dtype
and found it returns float64
instead of uint8
.
After attempting data type conversion and retrieving the first value with cv.add(x,y).astype(np.uint8)[0]
, the result is [4], which matches the NumPy addition result.
How can I obtain the correct value from the cv.add()
algorithm?
There is a reported issue for this mismatch between documentation and actual behavior.
As you pass 1D arrays to cv.add
the interpretation within OpenCV
may be ambiguous. The output [[260.], [ 0.], [ 0.], [ 0.]]
suggests OpenCV
is treating the input as a 4-channel vector (possibly RGBA), filling missing channels with zeros, and performing the addition channel-wise.
To avoid ambiguity, use explicit 2D arrays (e.g., np.uint8([[250]])
) or specify the shape.
See also this answer.
import cv2 as cv
import numpy as np
# Explicitly create a 1x1 image
x = np.uint8([[250]])
y = np.uint8([[10]])
print(f"x+y = {x+y}")
print(f"cv.add(x,y) = {cv.add(x,y)}")
# Reshape to 1x1 image
x = np.uint8([250]).reshape((1, 1))
y = np.uint8([10]).reshape((1, 1))
print(f"x+y = {x+y}")
print(f"cv.add(x,y) = {cv.add(x,y)}")
x+y = [[4]]
cv.add(x,y) = [[255]]
x+y = [[4]]
cv.add(x,y) = [[255]]