python - 如何从图像中检测黑色和灰色

标签 python opencv image-processing colors image-segmentation

我正在尝试获取一个程序来检测任何黑色色调(和一些轻微的灰色),但目前很难找到一个好的上色相向量(upper_hue 变量),它可以让我提取黑色的大部分色调没有提取其他颜色。它似乎适用于黑色鞋子或雨伞等图片,但对于亮度变化的道路照片却存在问题。

我正试图找到一个良好的色调上限,使程序能够对此保持稳健,但它有获得非黑色的风险。

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

什么是黑色和灰色值的良好上色调向量。如果这不是问题所在,那么解决此问题的好方法是什么?

代码:

import cv2
import numpy as np
import imutils

def color_seg(choice):
    if choice == 'blue':
        lower_hue = np.array([100,30,30])
        upper_hue = np.array([150,148,255])
    elif choice == 'white':
        lower_hue = np.array([0,0,0])
        upper_hue = np.array([0,0,255])
    elif choice == 'black':
        lower_hue = np.array([0,0,0])
        upper_hue = np.array([50,50,100])
    return lower_hue, upper_hue


# Take each frame
frame = cv2.imread('images/black0.jpg')
#frame = cv2.imread('images/road_1.jpg')

frame = imutils.resize(frame, height = 300)
chosen_color = 'black'


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

# define range of a color in HSV
lower_hue, upper_hue = color_seg(chosen_color)


# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_hue, upper_hue)


cv2.imshow('frame',frame)
cv2.imshow('mask',mask)

cv2.waitKey(0)

最佳答案

在 hsv 颜色空间中,它非常简单。

img = cv2.imread(img_path)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_gray = np.array([0, 5, 50], np.uint8)
upper_gray = np.array([179, 50, 255], np.uint8)
mask_gray = cv2.inRange(hsv, lower_gray, upper_gray)
img_res = cv2.bitwise_and(img, img, mask = mask_gray)

H 是色调,因此灰色检测器需要所有 H 值(0 -> 360°,由 OpenCV 在 0 到 179 的整数范围内表示以适合 8 位)。 S 是饱和度 (0 -> 255)。灰度介于 0 和 50 之间。如果我们不想保留白色值,我们可以将 5 作为最小值。 V 是亮度值(0=暗 -> 255=亮)。

关于python - 如何从图像中检测黑色和灰色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404392/

相关文章:

python - pytest 2.3 中的包范围固定装置

c++ - Visual Studio 不为 KinectBridgeWithOpenCVBasics D2D C++ 示例使用额外的包含目录,但为其他解决方案使用。

c++ - 在 OpenCV 中加快将图像写入硬盘的速度

opencv - 使用基本矩阵opencv确定相机运动

python - 霍夫圆检测: Blurring the image before calling hough circle algorithm?

python - 如何在 Windows 下的 Python 2 shell 中打印 unicode 字符串?

python - 在 Python 中,说我们 "override"内置运算符的行为准确吗?

image - 从车牌上删除多余的像素/线

python - Python 和 matplotlib 的 eps 导出问题

c# - 使用 c Sharp 删除图像纯色背景