Search code examples
pythonopencvimage-processing

How can I get a specific color from a .png picture with OpenCV and Python


I want to check if a PNG-image contains a specific color.

I use this tutorial

This is the image:

enter image description here

I want to check if the light green color exist. In RGB it is: [165, 209, 103]

This is my script:

import cv2
import numpy as np

image = cv2.imread("01.png")
hsvimg = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lb = np.array([68, 100, 100])
ub = np.array([88, 255, 255])
mask = cv2.inRange(hsvimg, lb, ub)
if 255 in mask:
    print("true")  

I get the range from the script in the tutorial. It says the HSV color is [78, 129, 209]. Is this right?

But the script doesn't return true.

Here is a second picture I have trouble with:

3


Solution

  • You can check this answer for understanding how to select the filter values for the colors. Checking this, I think for green, lb is [36, 25, 25] and ub is [70, 255, 255], but you can change according to which shade of green you need.

    import cv2
    import numpy as np
    
    image = cv2.imread("green.png")
    hsvimg = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    lb = np.array([36, 25, 25])
    ub = np.array([70, 255, 255])
    mask = cv2.inRange(hsvimg, lb, ub)
    if 255 in mask:
        print("true")
    else:
        print("false")
    

    output

    true