james strand 123
james strand 123

Reputation: 23

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.

Upvotes: 1

Views: 3846

Answers (4)

ping Chen
ping Chen

Reputation: 1

Setting b.astype(np.uint8) is fine, it will clip the maximum value to 255 automatically just like np.clip().

Upvotes: 0

fmw42
fmw42

Reputation: 53081

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)

Upvotes: 3

Ahx
Ahx

Reputation: 7985

One approach is addding 100 to all the values of the B channel, then check if the value is greater than 255 set 255.

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

b += 100
b[b > 255] = 255

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

Upvotes: 0

Damiano Zappia
Damiano Zappia

Reputation: 1

You are using b.all(), that returns true or false if all elements in b are <= 155 or not. But then inside the "if" you are adding 100 to ALL members of b. Try to do the check only on those elements of b that are <= 155

Upvotes: 0

Related Questions