Python 如何定义阈值以仅检测图像中的绿色对象:Opencv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47483951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define a threshold value to detect only green colour objects in an image :Opencv
提问by S.Am
I just want to detect only green objects from an image which captured in natural environment.How to 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) others are must appear in another colour(black) Please guide me to do this. thanks in advance.
我只想从在自然环境中捕获的图像中仅检测绿色物体。如何定义它?因为在这里我想通过阈值让我们说'x',通过使用这个 x 我只想让绿色物体变成一种颜色(白色)其他必须出现在另一种颜色(黑色)请指导我做这个。提前致谢。
回答by u3547485
Update:
更新:
I make a HSV
colormap. It's more easy and accurate
to find the color range using this map than before.
我做了一个HSV
颜色图。就是more easy and accurate
用这张图比以前找到颜色范围。
And maybe I should change use (40, 40,40) ~ (70, 255,255) in hsv
to find the green
.
也许我应该改变使用(40, 40,40) ~ (70, 255,255) in hsv
来找到green
.
Original answer:
原答案:
- Convert to
HSV
color-space, - Use
cv2.inRange(hsv, hsv_lower, hsv_higher)
to get the green mask.
- 转换为
HSV
色彩空间, - 使用
cv2.inRange(hsv, hsv_lower, hsv_higher)
中获取绿色面具。
We use the range (in hsv)
: (36,0,0) ~ (86,255,255)
for this sunflower
.
我们使用the range (in hsv)
:(36,0,0) ~ (86,255,255)
为此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:
相似的: