python - opencv - convert pixel from bgr to hsv
Asked Answered
A

2

12
img = cv2.imread('example.jpg')
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# lower mask (0-10)
lower_red = np.array([0, 50, 50])
upper_red = np.array([10, 255, 255]
mask0 = cv2.inRange(img_hsv, lower_red, upper_red)
# upper mask (170-180)
lower_red = np.array([170, 50, 50])
upper_red = np.array([180, 255, 255])
mask1 = cv2.inRange(img_hsv, lower_red, upper_red)
# join my masks
mask = mask0 + mask1

height = mask.shape[0]
width = mask.shape[1]
# iterate over every pixel
for i in range(height):
    for j in range(width):
        px = mask[i,j]
        print px
        # check if pixel is white or black
        if (px[2] >= 0 and px[2] <= 40):

In the above example 'px' is a pixel in BGR. I need to convert the value to HSV because I want to check if the pixel is in a certain color range.

I already tried

colorsys.rgb_to_hsv(px[2], px[1], px[0})

which evokes the error: invalid index to scalar variable

Thanks!

Abirritate answered 13/2, 2017 at 7:10 Comment(0)
A
21

From the docs:

# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)

You can just convert your whole img to hsv using the built in method:

hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Atrip answered 13/2, 2017 at 7:22 Comment(6)
thanks for the answer! how can i check if a single pixel is in the blue color range?Abirritate
It says so in the code I provided from the docs. Just get your px from mask and check if it is white or black.Atrip
px = img[i,j] is now returning 0 instead if an array of three values. Do you know why that is?Abirritate
Could you update your question to show me the new code?Atrip
Your mask is a black and white image. The value is 0 if it is black or 255 if its white. You don't need an array of color values anymore.Atrip
i have r,g,b values can i convert to h,s,v values using open cv?Ricoriki
S
1

This function worked for me:

def convert_rgb_to_yuv(frame):
"""
Convert a given rgb image into hsv image
:param frame: Color image to convert
:return: YUV image as numpy array
"""

# CODE HERE

#Conversion matrix from rgb to yuv, transpose matrix is used to convert from yuv to rgb
yuv_from_rgb = np.array([[0.114, 0.587,  0.299],
                         [0.436, -0.28886, -0.14713],
                         [-0.10001, -0.51499, 0.615]])

# do conversion
image = frame.dot(yuv_from_rgb.T) 
# add the constants based on the conversion formula
image += np.array([16, 128, 128]).reshape(1, 1, 3)
# convert the image to uint8 format
image = np.array(image, dtype = "uint8")
return image
Swahili answered 11/3, 2021 at 9:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.