如何在 HSV opencv python 中指定颜色的上限值和下限值 [英] how to i specify the upper and the lower value of a color in HSV opencv python

查看:55
本文介绍了如何在 HSV opencv python 中指定颜色的上限值和下限值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了将 RGB 转换为 HSV 的方法,但仍然无法找到颜色的上下值.我该如何计算?

I found way to convert RGB to HSV, but still I am unable to find the upper and lower value of color. How to do i calculate that?

我必须从图片中取出pickachu

I have to take out the pickachu from the image

这是我的代码到现在

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)


    lower_red = np.array([30,50,50])
    upper_red = np.array([255,255,180])  #it is trial and error

    mask = cv2.inRange(frame, lower_red, upper_red)
    res = cv2.bitwise_and(frame, frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
       break
cv2.destroyAllWindows()
cap.release()

请帮帮我

推荐答案

您可以使用以下程序通过单击像素(即您想要的像素)来找到它的上下色调值.

you can use the following program to find the upper and lower hue values for the pixel by clicking on it(i.e. the pixel you want).

import cv2
import numpy as np

image_hsv = None   # global ;(
pixel = (20,60,80) # some stupid default

# mouse callback function
def pick_color(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN:
        pixel = image_hsv[y,x]

        #you might want to adjust the ranges(+-10, etc):
        upper =  np.array([pixel[0] + 10, pixel[1] + 10, pixel[2] + 40])
        lower =  np.array([pixel[0] - 10, pixel[1] - 10, pixel[2] - 40])
        print(pixel, lower, upper)

        image_mask = cv2.inRange(image_hsv,lower,upper)
        cv2.imshow("mask",image_mask)

def main():
    import sys
    global image_hsv, pixel # so we can use it in mouse callback

    image_src = cv2.imread(sys.argv[1])  # pick.py my.png
    if image_src is None:
        print ("the image read is None............")
        return
    cv2.imshow("bgr",image_src)

    ## NEW ##
    cv2.namedWindow('hsv')
    cv2.setMouseCallback('hsv', pick_color)

    # now click into the hsv img , and look at values:
    image_hsv = cv2.cvtColor(image_src,cv2.COLOR_BGR2HSV)
    cv2.imshow("hsv",image_hsv)

    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__=='__main__':
    main()

这篇关于如何在 HSV opencv python 中指定颜色的上限值和下限值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆