【问题标题】:python - opencv - convert pixel from bgr to hsvpython - opencv - 将像素从 bgr 转换为 hsv
【发布时间】:2017-07-01 02:31:29
【问题描述】:
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):

在上面的例子中,'px' 是 BGR 中的一个像素。我需要将值转换为 HSV,因为我想检查像素是否在某个颜色范围内。

我已经试过了

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

引发错误:标量变量的索引无效

谢谢!

【问题讨论】:

    标签: python opencv pixel hsv bgr


    【解决方案1】:

    这个功能对我有用:

    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
    

    【讨论】:

      【解决方案2】:

      来自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)
      

      您可以使用内置方法将整个 img 转换为 hsv:

      hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
      

      【讨论】:

      • 感谢您的回答!如何检查单个像素是否在蓝色范围内?
      • 在我从文档中提供的代码中是这样说的。只需从mask 获取您的px 并检查它是白色还是黑色。
      • px = img[i,j] 现在返回 0 而不是三个值的数组。你知道这是为什么吗?
      • 您能否更新您的问题以向我展示新代码?
      • 您的蒙版是黑白图像。如果是黑色,则值为 0,如果为白色,则值为 255。您不再需要一组颜色值。
      猜你喜欢
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      相关资源
      最近更新 更多