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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:13:44  来源:igfitidea点击:

How to define a threshold value to detect only green colour objects in an image :Opencv

pythonopencvimage-processingthreshold

提问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 HSVcolormap. It's more easy and accurateto 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 hsvto find the green.

也许我应该改变使用(40, 40,40) ~ (70, 255,255) in hsv来找到green.

enter image description here

在此处输入图片说明



Original answer:

原答案

  1. Convert to HSVcolor-space,
  2. Use cv2.inRange(hsv, hsv_lower, hsv_higher)to get the green mask.
  1. 转换为HSV色彩空间,
  2. 使用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:

源图像:

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)
  1. 使用 `cv::inRange` (OpenCV) 为颜色检测选择正确的 HSV 上下边界