OpenCV & Python -- Can't detect blue objects

14,058

Solution 1

Blue is represented in HSV at a hue of around 240 degrees out of 360. The Hue range in OpenCV-HSV is 0-180, to store the value in 8 bits. Thus, blue is represented in OpenCV-HSV as a value of H around 240 / 2 = 120.

To detect blue correctly, the following values could be chosen:

blue_lower=np.array([100,150,0],np.uint8)
blue_upper=np.array([140,255,255],np.uint8)

Solution 2

Your colour model is set by the line:

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

To be using Hue, Saturation and Value, rather than the default Blue, Green, Red that OpenCV uses by default. See how the colour model works here.

Share:
14,058
Eamorr
Author by

Eamorr

Updated on June 08, 2022

Comments

  • Eamorr
    Eamorr almost 2 years

    I was looking at this question:

    How to detect blue color object using opencv

    Yet after much trial and error, I still can't figure out how to detect blue objects.

    Here is my code:

    import cv2
    import numpy as np
    
    cam=cv2.VideoCapture(0)
    n=0
    
    while True:
        print n
        returnVal,frame=cam.read()
    
        img=cv2.GaussianBlur(frame, (5,5), 0)
        img=cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    
        blue_lower=np.array([150,150,0],np.uint8)
        blue_upper=np.array([180,255,255],np.uint8)
        blue=cv2.inRange(img,blue_lower,blue_upper)
    
        cv2.imshow('img',blue)
    
        n=n+1
        key = cv2.waitKey(10) % 0x100
        if key == 27: break #ESC 
    

    I can detect red objects by setting the following lines:

    red_lower=np.array([0,150,0],np.uint8)
    red_upper=np.array([10,255,255],np.uint8)
    

    When I put a blue piece of paper in front of my webcam using the first code, it just shows up black.

    Can someone please help me to convert RGB for blue colours into HSV?

    Many thanks in advance,