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]: