1

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?

2
  • 1
    Relevant: stackoverflow.com/questions/79680822/…. Commented Aug 4 at 6:16
  • 1
    these two suggested older questions explain the phenomenon sufficiently. the newer one of them was primarily about saturating arithmetic, but secondarily about OpenCV's treatment of Python numpy arrays and it explains that behavior in more detail than the older question's answer. Commented Aug 4 at 10:47

1 Answer 1

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.