HSV color space

1. Experiment introduction

1. Experimental content

This lab will introduce the HSV color space.

2. Experimental points

  • RGB threshold
  • Convert to HSV

3. Experimental environment

  • Python 3.6.6
  • numpy
  • matplotlib
  • cv2

2. Experimental steps

1 Import resources

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

import numpy as np
import cv2

%matplotlib inline

2 Read in RGB image

# 读入该图像
image = mpimg.imread('images/car_green_screen2.jpg')

plt.imshow(image)
<matplotlib.image.AxesImage at 0x7f42aad63ba8>

insert image description here

3 RGB Threshold

Visualize the green threshold defined in the green example that has been used so far.

# 在RGB值中定义颜色选择边界
lower_green = np.array([0,180,0]) 
upper_green = np.array([100,255,100])

# 定义掩模区域
mask = cv2.inRange(image, lower_green, upper_green)

# 遮掩图像使得汽车显露出来
masked_image = np.copy(image)

masked_image[mask != 0] = [0, 0, 0]

# 输出该图像
plt.imshow(masked_image)
<matplotlib.image.AxesImage at 0x7f42aad0f7f0>

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-j3W0yQlc-1686485948568)(output_5_1.png)]

4 Convert to HSV

# 转换为HSV
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)

# HSV通道
h = hsv[:,:,0]
s = hsv[:,:,1]
v = hsv[:,:,2]

# 可视化各个颜色通道
f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,10))
ax1.set_title('H channel')
ax1.imshow(h, cmap='gray')
ax2.set_title('S channel')
ax2.imshow(s, cmap='gray')
ax3.set_title('V channel')
ax3.imshow(v, cmap='gray')
<matplotlib.image.AxesImage at 0x7f42a74550f0>

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-EWdNOzd4-1686485948568)(output_7_1.png)]

3. Experimental tasks

Exercise: Masking green areas using HSV color space

# 在HSV值中定义我们的颜色选择边界
# 下界
lower_hue = np.array([50,0,0])
# 上界
upper_hue = np.array([70,255,255])

## TODO: 修改这些阈值
# 此初始阈值允许色相(H)处于某个较低范围


# 定义掩模区域
mask_hsv = cv2.inRange(hsv,lower_hue,upper_hue)


# 遮掩图像使得汽车显露出来
masked_image_hsv = np.copy(image)
masked_image_hsv[mask_hsv != 0] = [0,0,0]



# 输出该图像
plt.imshow(masked_image_hsv)
<matplotlib.image.AxesImage at 0x7f429ffae128>

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-aGGtnTmq-1686485948569)(output_9_1.png)]

Guess you like

Origin blog.csdn.net/qq_52187415/article/details/131263547