使用HSV色彩空间遮罩绿色区域

HSV 颜色空间

导入资源

In [3]:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
​
import numpy as np
import cv2
​
%matplotlib inline

读入RGB图像

In [4]:
# Read in the image
image = mpimg.imread('images/car_green_screen2.jpg')
plt.imshow(image)
Out[4]:
<matplotlib.image.AxesImage at 0x7f5077ca1828>
 
 

RGB阈值

将你在之前一直使用的绿色示例中定义的绿色阈值可视化。

In [5]:
# Define our color selection boundaries in RGB values
lower_green = np.array([0,180,0]) 
upper_green = np.array([100,255,100])​
# Define the masked area
mask = cv2.inRange(image, lower_green, upper_green)​
# Mask the image to let the car show through
masked_image = np.copy(image)
masked_image[mask != 0] = [0, 0, 0]
# Display it!
plt.imshow(masked_image)
Out[5]:
<matplotlib.image.AxesImage at 0x7f504639e748>
 
 

转换为HSV

In [6]:
 
 # Convert to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
​
# HSV channels
h = hsv[:,:,0]
s = hsv[:,:,1]
v = hsv[:,:,2]
​
# Visualize the individual color channels
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')
Out[6]:
<matplotlib.image.AxesImage at 0x7f5046289780>
 
 

TODO: 使用HSV色彩空间遮罩绿色区域

In [7]:
## TODO: Define the color selection boundaries in HSV values
## TODO: Define the masked area and mask the image
# Don't forget to make a copy of the original image to manipulate
low= np.array([35, 43, 46])  
up = np.array([77, 255, 255])  
mask1=cv2.inRange(hsv,low,up)
masked_image1=np.copy(image)
masked_image1[mask1!=0]=[0,0,0]
plt.imshow(masked_image1) 
Out[7]:
<matplotlib.image.AxesImage at 0x7f504624aac8>
 

猜你喜欢

转载自www.cnblogs.com/fuhang/p/9176749.html