stay OpenCV Medium “ Image operation ” Official guide document in , There is such a note
There is a difference between OpenCV addition and Numpy addition. OpenCV addition is a saturated operation while Numpy addition is a modulo operation.
OpenCV and Numpy The addition operation of is different ,OpenCV The addition operation of is saturation operation , and Numpy The addition operation of is modulo operation
Everyone must have seen something similar sat(a+b) The expression of , In fact, this is saturation operation ; And modular operation is generally used directly a+b To represent the .
The biggest feature of saturation operation is not paying attention to overflow , The execution result has little to do with the bottom ; Suppose the type of variable is 8 Bit unsigned integer , Then the maximum number is 255, If the result of adding is greater than 255, Then the result of saturation operation is 255.
Modulo operations consider overflow bits , The execution results need to be explained to the underlying principles of the computer —— Thinking about binary ; Suppose the type of variable is 8 Bit unsigned integer , Then the maximum number is 255( Corresponding binary 11111111), If the result of adding is greater than 255, Then you have an overflow , Only binary bits within the scope of the container are reserved .
Why? np.add() The return value of 0? because 255+1=256, Corresponding binary bit 1[00000000], The first superfluous 1 Belong to overflow position , After removal, it is [00000000], Corresponding to decimal integers 0.
import cv2 as cv
import numpy as np
a = np.array([[255]], dtype=np.uint8)
print(cv.add(a, 1))
print(np.add(a, 1))
# [[255]]
# [[0]]