1

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?

I have to take out the pickachu from the image

enter image description here

and this my code till now

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()

please help me

api55
  • 11,070
  • 4
  • 41
  • 57
Tanay Kumar
  • 81
  • 1
  • 2
  • 7
  • so, what color do you want to extract? Yellow? That is around Hue = 60, so in openCV (at least C++, not sure about python) it is around hue = 30. Try lower = np.array([20,50,50]) upper = np.array([40,255,255]) – Micka Nov 12 '18 at 08:58
  • https://stackoverflow.com/users/2393191/micka thank you but still some above portion on the right side is till not visible – Tanay Kumar Nov 12 '18 at 09:16
  • try allowing smaller saturation and value (2nd and 3rd param in lower range) and/or allow more hue variation. – Micka Nov 12 '18 at 10:13

1 Answers1

3

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()
Matthijs
  • 2,483
  • 5
  • 22
  • 33