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.

Another way
- Convert to the HSV color space,
- 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:

The masked green regions:

More steps:

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:
- Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)