在 HSV 图像的值部分检测红色

Detect red color in Value part of HSV image

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

输入图像:

转换为 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 图像,但是当我尝试仅应用于值部分时,我收到错误消息,因为数组维度不匹配。这是我目前得到的结果:

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

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