【问题标题】:Detect red color in Value part of HSV image检测 HSV 图像值部分中的红色
【发布时间】:2021-11-25 13:58:13
【问题描述】:

我有一张 BGR 彩色格式的车牌图像。我将此图像转换为 HSV。在这里,我可以将颜色通道分别拆分为 H、S 和 V。现在我只想从 Value 图像中选择 red 颜色,并将其他所有颜色设置为白色。我已经找到了从经典图像中选择红色的方法,使用遮罩的上下范围以及使用 cv2.inRange,但我还没有找到针对此特定任务的解决方案。

输入图片:

转换为HSV并根据渠道拆分:

代码:

import cv2
import matplotlib.pyplot as plt
import numpy as np


img = cv2.imread('zg4515ah.png')
cv2_imshow(img)

img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

fig, ax = plt.subplots(1, 3, figsize=(15,5))
ax[0].imshow(img_hsv[:,:,0], cmap='hsv')
ax[0].set_title('Hue',fontsize=15)
ax[1].imshow(img_hsv[:,:,1], cmap='hsv')
ax[1].set_title('Saturation',fontsize=15)
ax[2].imshow(img_hsv[:,:,2], cmap='hsv')
ax[2].set_title('Value',fontsize=15)
plt.show()

lower_red = np.array([155,25,0])
upper_red = np.array([179,255,255])
mask = cv2.inRange(img_hsv, lower_red, upper_red)

# or your HSV image, which I *believe* is what you want
output_hsv = img_hsv.copy()
output_hsv[np.where(mask==0)] = 0

imgplot = plt.imshow(output_hsv)
plt.show()

我知道我正在尝试将蒙版应用于整个 HSV 图像,但是当我尝试仅应用于 Value 部分时,由于数组尺寸不匹配,我收到错误消息。这是我目前得到的结果:

【问题讨论】:

标签: python opencv


【解决方案1】:

一个简单的掩码就可以了,不需要cv2.inRange,因为大于40的value值不是红色的:

img = cv2.imread('image.png')

img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

fig, ax = plt.subplots(1, 3, figsize=(15,5))
ax[0].imshow(img_hsv[:,:,0], cmap='hsv')
ax[0].set_title('Hue',fontsize=15)
ax[1].imshow(img_hsv[:,:,1], cmap='hsv')
ax[1].set_title('Saturation',fontsize=15)
ax[2].imshow(img_hsv[:,:,2], cmap='hsv')
ax[2].set_title('Value',fontsize=15)
plt.show()


# or your HSV image, which I *believe* is what you want
output_hsv = img_hsv.copy()

# Using this threshhold
output_hsv[np.where(output_hsv[:,:,2]>40)] = 255

imgplot = plt.imshow(output_hsv)

output_hsv[np.where(output_hsv[:,:,2]<40)] = 255

【讨论】:

  • 我明白了,谢谢。关于第二张图片,使用 OTSU 阈值方法可以获得非常相似的输出,当然它是黑白的,具体取决于上限阈值。
  • 你说得对,我差点忘了OTSU哈哈
猜你喜欢
  • 2019-05-12
  • 2011-11-12
  • 1970-01-01
  • 2016-01-16
  • 2015-06-13
  • 1970-01-01
  • 2014-06-19
  • 2012-06-19
  • 1970-01-01
相关资源
最近更新 更多