How can I define a threshold value to detect only green colour objects in an image with Python OpenCV?
Asked Answered
S

3

34

I want to detect only green objects from an image captured in a natural environment. How can I define it?

Because in here I want to pass the threshold value, let's say 'x'. By using this x, I want to get only green colour objects in to one colour (white), and others are must appear in another colour (black).

How can I do it?

Stegosaur answered 25/11, 2017 at 8:20 Comment(1)
The other question is Android-specific is it not? This question is marked python.Fabe
R
80

One way

I make a HSV colormap. It's more easy and accurate to find the color range using this map than before.

And maybe I should change use (40, 40,40) ~ (70, 255,255) in HSV to find the green.

Enter image description here

Another way

  1. Convert to the HSV color space,
  2. Use cv2.inRange(hsv, hsv_lower, hsv_higher) to get the green mask.

We use the range (in HSV): (36,0,0) ~ (86,255,255) for this sunflower.


The source image:

Enter image description here

The masked green regions:

Enter image description here

More steps:

Enter image description here


The core source code:

import cv2
import numpy as np

## Read
img = cv2.imread("sunflower.jpg")

## Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

## Mask of green (36,25,25) ~ (86, 255,255)
# mask = cv2.inRange(hsv, (36, 25, 25), (86, 255,255))
mask = cv2.inRange(hsv, (36, 25, 25), (70, 255,255))

## Slice the green
imask = mask>0
green = np.zeros_like(img, np.uint8)
green[imask] = img[imask]

## Save 
cv2.imwrite("green.png", green)

Similar:

  1. Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)
Revolute answered 25/11, 2017 at 8:22 Comment(15)
Nice! Do you care to share your code?Cecilia
Since I m using python opencv i used hsv values for bgr as for lower green area as 50,100,100 and upper green area as 70,255,255, hsv value for green colour is given as 60,255,255. But it didn't work , by using that I am getting only plain black image as a result.Stegosaur
In my case, I use [36 0 0] ~ [ 86 255 255]Unrealizable
@Silencer thank you it's works for meStegosaur
@Silencer Can u suggest me for yellow colour range for pictures taken from natural environemt also?Stegosaur
@S.Am At least for my "sunflower", it works. As for other images, it maybe not the best, but it can be a choice. You can also choose other methods you found.Unrealizable
@Silencer oki .. Can I know the yellow colour range you have used?Stegosaur
In this "sunflower", green in (36,0,0)~(86,255,255), yellow in (15,0,0)~(36,255,255), blue in (90,0,0)~(110,255,255)Unrealizable
@S.Am The sunflower is not that colorful. So the range is not that accurate for other colorful image. I make a hsv colormap to find the range easily and accurately. Maybe it helps.Unrealizable
Did I understand you correctly that this color map is calculated only for this image ? Which tool did you use to get HSV color map from image ?Paten
Yes, I just used this sunflower to illustrate how to use inRange in HSV. Because there is only three main colors, so even not precise range works ok. I wrote code to generate this colormap, maybe useful, maybe not.Unrealizable
Sorry, I'm new in OpenCV and trying to understand: can I use your color map for my image ? For example to detect threshold of blue pixels ?Paten
Why not? If you lookup the map, you will find blue(HSV) mainly locate in (110,150,50) ~ (120,255,255).Unrealizable
it cuts non-greenLodhia
@Kinght金 In this color map, what is in X and Y axis?Entertaining
R
10

Intro:

Applying a threshold to detect green color can be performed quite easily using LAB color space.

The LAB color space also has 3 channels but unlike its RGB counterpart (where all 3 are color channels), in LAB there are 2 color channels and 1 brightness channel:

  • L-channel: represents the brightness value in the image
  • A-channel: represents the red and green color in the image
  • B-channel: represents the blue and yellow color in the image

Observing the following diagram:

enter image description here

The green and red color are represented on the extremes of the A-channel. Applying a suitable threshold on either of these extremes on this channel can segment either green or red color.

Demo:

The following images are in the order:

1. Original image -->> 2. A-channel of LAB converted image

3. Threshold -->> 4. Mask on the original image

Sample 1:

enter image description here enter image description here

enter image description here enter image description here

Sample 2:

enter image description here enter image description here

enter image description here enter image description here

Sample 3:

enter image description here enter image description here

enter image description here enter image description here

Code:

The code just has few lines:

# read image in BGR
img = cv2.imread('image_path')
# convert to LAB space
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
# store the a-channel
a_channel = lab[:,:,1]
# Automate threshold using Otsu method
th = cv2.threshold(a_channel,127,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)[1]
# Mask the result with the original image
masked = cv2.bitwise_and(img, img, mask = th)

Exception:

The method above will work perfectly if green color appears distinctly. But applying an automated threshold might not always work, especially when there various shades of green in the same image.

In such cases, one set the threshold manually on the A-channel.

img = cv2.imread('flower.jpg')
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
a_channel = lab[:,:,1]
# manually set threshold value
th = cv2.threshold(a_channel, 105, 255, cv2.THRESH_BINARY_INV)
# perform masking
masked = cv2.bitwise_and(img, img, mask = th)

enter image description here enter image description here

    Threshold image                              Masked image
Relational answered 16/5, 2022 at 19:0 Comment(1)
While searching for a color range in HSV involves 3 channels, in LAB space searching involves only 2 channels. This reduces manual search to a great extentRelational
M
5

You can use a simple HSV color thresholder script to determine the lower/upper color ranges using trackbars for any image on the disk. Simply change the image path in cv2.imread(). Example to isolate green:

import cv2
import numpy as np

def nothing(x):
    pass

# Load image
image = cv2.imread('1.jpg')

# Create a window
cv2.namedWindow('image')

# Create trackbars for color change
# Hue is from 0-179 for Opencv
cv2.createTrackbar('HMin', 'image', 0, 179, nothing)
cv2.createTrackbar('SMin', 'image', 0, 255, nothing)
cv2.createTrackbar('VMin', 'image', 0, 255, nothing)
cv2.createTrackbar('HMax', 'image', 0, 179, nothing)
cv2.createTrackbar('SMax', 'image', 0, 255, nothing)
cv2.createTrackbar('VMax', 'image', 0, 255, nothing)

# Set default value for Max HSV trackbars
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)

# Initialize HSV min/max values
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0

while(1):
    # Get current positions of all trackbars
    hMin = cv2.getTrackbarPos('HMin', 'image')
    sMin = cv2.getTrackbarPos('SMin', 'image')
    vMin = cv2.getTrackbarPos('VMin', 'image')
    hMax = cv2.getTrackbarPos('HMax', 'image')
    sMax = cv2.getTrackbarPos('SMax', 'image')
    vMax = cv2.getTrackbarPos('VMax', 'image')

    # Set minimum and maximum HSV values to display
    lower = np.array([hMin, sMin, vMin])
    upper = np.array([hMax, sMax, vMax])

    # Convert to HSV format and color threshold
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower, upper)
    result = cv2.bitwise_and(image, image, mask=mask)

    # Print if there is a change in HSV value
    if((phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ):
        print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax))
        phMin = hMin
        psMin = sMin
        pvMin = vMin
        phMax = hMax
        psMax = sMax
        pvMax = vMax

    # Display result image
    cv2.imshow('image', result)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

HSV lower/upper color threshold ranges

(hMin = 52 , sMin = 0, vMin = 55), (hMax = 104 , sMax = 255, vMax = 255)

Once you have determined your lower and upper HSV color ranges, you can segment your desired colors like this:

import numpy as np
import cv2

image = cv2.imread('1.png')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([52, 0, 55])
upper = np.array([104, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
result = cv2.bitwise_and(image, image, mask=mask)

cv2.imshow('result', result)
cv2.waitKey()
Murmurous answered 17/4, 2022 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.