Search code examples
pythonopencv

How to have an RGB value not go over the 255 limit in OpenCv?


I want to add 100 to the blue value. However in my case I want to have a check happen at every pixel coordinate to check if it goes over the 255 value, it stays at 255.

import numpy as np
import cv2

img = cv2.imread('cake.jpeg')

b,g,r = cv2.split(img)

if b.all() <= 155:
    b += 100

img = cv2.merge((b,g,r))

cv2.imwrite('edited cake.png', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Note: Calculated 255 - 100 = 155 for check statement.

However the if statement doesn't seem to have any effect on preventing the 255 limit from going over.


Solution

  • You do not need to check, if you use Python/OpenCV add. It does the clipping for you. So

    b = cv2.add(b,100)
    

    should work without the need to clip (and be very fast).

    Alternately, you could do

    b = (b+100).clip(0,255)