Home > Mobile >  Detect red color in Value part of HSV image
Detect red color in Value part of HSV image

Time:11-26

I have a license plate image which is in BGR color format. I translate this image to HSV. Here I can split the color channels to H, S and V respectively. Now I want to select only the red color from the Value image and set everything else as white. I have found ways to select red color from classic images using lower and upper ranges for masks and using cv2.inRange, but I have not found a solution for this specific task.

Input image:

enter image description here

Converted to HSV and split according to channel: enter image description here

Code:

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()

I know that I am trying to apply the mask on the whole of the HSV image, but when I try to apply to only the Value part, I get an error as the array dimensions do not match. This is the result I get currently:

enter image description here

CodePudding user response:

A simple mask will work, no need for cv2.inRange because value values greater than 40 is not red:

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)

enter image description here

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

enter image description here

  • Related