使用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]:
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]:
转换为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]:
TODO: 使用HSV色彩空间遮罩绿色区域
然后利用cv2.inRange函数设阈值,去除背景部分
函数很简单,参数有三个
第一个参数:hsv指的是原图
第二个参数:lower_red指的是图像中低于这个lower_red的值,图像值变为0
第三个参数:upper_red指的是图像中高于这个upper_red的值,图像值变为0
而在lower_red~upper_red之间的值变成255
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]:
版权声明:本文为fuhang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。