The problem of outliers after image matrix addition and subtraction operations

Insert picture description here

OpenCV image addition and subtraction function method

The addition and subtraction operation of the image matrix is ​​converted to the OpenCV image addition (add) and subtract (subtract) function operation.

def bilateral_filter(image, level1=3, level2=1):
    img_smooth = cv2.bilateralFilter(image, level1 * 5, level1 * 12.5, level1 * 12.5)
    img_diff = cv2.subtract(img_smooth, image)
    img_hp = cv2.add(img_diff, (10, 10, 10, 128))
    img_blur = cv2.GaussianBlur(img_hp, (2 * level2 - 1, 2 * level2 - 1), 0)
    img_tmp = cv2.subtract(cv2.add(cv2.add(img_blur, img_blur), image), (10, 10, 10, 255))
    img_blend = cv2.addWeighted(image, 0.1, img_tmp, 1 - 0.1, 0.0)
    return img_blend

Data type conversion method

Process image data type conversion to float32 type.

def bilateral_filter(image, level1=3, level2=1):
    image = np.array(image, dtype=np.float32) # very important
    img_smooth = cv2.bilateralFilter(image, level1 * 5, level1 * 12.5, level1 * 12.5)

    img_hp = img_smooth - image + 128

    img_blur = cv2.GaussianBlur(img_hp, (2 * level2 - 1, 2 * level2 - 1), 0)
    img_blend = np.uint8(image * 0.5 + (image + 2 * img_blur - 255) * 0.5)
    return  img_blend

Data overflow needs to be truncated

And the truncation must be before the conversion to uint8.

def bilateral_filter(image, level1=3, level2=1):
    image = np.array(image, dtype=np.float32) # very important
    img_smooth = cv2.bilateralFilter(image, level1 * 5, level1 * 12.5, level1 * 12.5)

    img_hp = img_smooth - image + 128

    img_blur = cv2.GaussianBlur(img_hp, (2 * level2 - 1, 2 * level2 - 1), 0)
    img_blend = np.uint8(np.clip(image * 0.5 + (image + 2 * img_blur - 255) * 0.5, 0, 255))#clip在uint8转换之前

    return  img_blend

Reference

1. Talking about python opencv's addition and subtraction operation overflow on the image color channel
2. [opencv note 06 image addition and subtraction add() and subtract()]
3. Opencv Python image subtraction operation CV2. Detailed description of the subtraction function and comparison with matrix subtraction, OpenCVPython, operation, cv2subtract, detailed explanation, and, and, difference, comparison
4. There is no negative number (values ​​are 0-255) when matrix subtraction appears in python digital image processing Situation analysis
5. OpenCV-Python image subtraction operation cv2.subtract function detailed explanation and comparison with matrix subtraction

Guess you like

Origin blog.csdn.net/studyeboy/article/details/112781532