I wrote the code as follows, and the output results are as follows. As far as I know, the add operation in opencv does not have a value of more than 255 because it performs a saturation operation. However, as in the output below, the number 260 is popped out, and the shape is also outputted strangely. The current version of opencv is 4.8.0.
import numpy as np
import cv2
x = np.array([250], np.uint8)
y = np.array([10], np.uint8)
print(cv2.add(x, y))
Output
[[260.] [ 0.] [ 0.] [ 0.]]
Expected
[[255]]
I've only run this code except for everything else. I run the code through jupyter notebook on vscode, and Google colab has normal output results. I've also run it in py file, and it still has a weird result of 260.
I have OpenCV v4.9. I can reproduce your observations.
If you want to get the "expected" behavior, make sure the arrays are shaped appropriately:
x.shape = (1, 1) # (H, W, C) or (H, W)
y.shape = (1, 1)
z = cv.add(x, y)
print(z.dtype) # uint8
print(z) # [[255]]
Since you got a (4,1)-shaped result, I think OpenCV interprets your arguments as equivalent to cv::Scalar, and treats them as floats. That is just speculation though. The docs will probably explain this in some place that needs to be found first.
Instead of assigning the shape explicitly, your code could also have looked like this (specifying 2D arrays directly):
x = np.array([[250]], np.uint8)
y = np.array([[10]], np.uint8)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With