電腦視覺系列-影像基本操作(6)
- 2021 年 1 月 29 日
- AI
-
灰度圖
在數字攝影、電腦生成的影像和色度學中,灰度或影像是指每個像素的值是一個僅代表一個度量的樣本,只攜帶強度資訊。灰度影像是一種黑白或灰色單色影像,只由灰度的陰影組成。對比度範圍從強度最弱的黑色到強度最強的白色。
Python">import cv2 #opencv讀取的格式是BGR
import numpy as np
import matplotlib.pyplot as plt#Matplotlib是RGB
%matplotlib inline
img=cv2.imread('cat.jpg')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img_gray.shape
opencv讀取圖片的默認像素排列是BGR
cv2.imshow("img_gray", img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
運行結果如下:
-
HSV
H – 色調(主波長)。
S – 飽和度(純度/顏色的陰影)。
V值(強度)
HSL(hue,saturation,lightness)和HSV(hue,saturation,value,也稱為HSB或hue,saturation,brightness)是RGB顏色模型的替代表示形式,由電腦圖形學研究人員在20世紀70年代設計,旨在更緊密地與人類視覺感知顏色屬性的方式保持一致。在這些模型中,每個色調的顏色都排列在一個徑向切片中,圍繞中心軸從底部的黑色到頂部的白色。
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
cv2.imshow("hsv", hsv)
cv2.waitKey(0)
cv2.destroyAllWindows()
運行結果如下:
-
影像閾值
ret, dst = cv2.threshold(src, thresh, maxval, type)
src:輸入圖,只能輸入單通道影像,通常來說為灰度圖
dst:輸出圖
thresh:閾值
maxval:當像素值超過了閾值(或者小於閾值,根據type來決定),所賦予的值
type:二值化操作的類型,包含以下5種類型:cv2.THRESH_BINARY;cv2.THRESH_BINARY_INV;cv2.THRESH_TRUNC;cv2.THRESH_TOZERO;cv2.THRESH_TOZERO_INV
cv2.THRESH_BINARY 超過閾值部分取maxval(最大值),否則取0
cv2.THRESH_BINARY_INV THRESH_BINARY的反轉
cv2.THRESH_TRUNC 大於閾值部分設為閾值,否則不變
cv2.THRESH_TOZERO 大於閾值部分不改變,否則設為0
cv2.THRESH_TOZERO_INV THRESH_TOZERO的反轉
Javascript">ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in range(6):
plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
運行結果如下:
-
影像平滑
影像平滑通常用於減少影像中的雜訊或生成像素較少的影像。大多數平滑方法都基於低通濾波器。平滑通常也基於表示影像的單個值,例如影像的平均值或中間值。
img = cv2.imread('lenaNoise.png')
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
運行結果如下:
# 均值濾波
# 簡單的平均卷積操作
blur = cv2.blur(img, (3, 3))
cv2.imshow('blur', blur)
cv2.waitKey(0)
cv2.destroyAllWindows()
運行結果:
# 方框濾波
# 基本和均值一樣,可以選擇歸一化
box = cv2.boxFilter(img,-1,(3,3), normalize=True)
cv2.imshow('box', box)
cv2.waitKey(0)
cv2.destroyAllWindows()
運行結果:
# 方框濾波
# 基本和均值一樣,可以選擇歸一化,容易越界
box = cv2.boxFilter(img,-1,(3,3), normalize=False)
cv2.imshow('box', box)
cv2.waitKey(0)
cv2.destroyAllWindows()
運行結果如下:
# 高斯濾波
# 高斯模糊的卷積核里的數值是滿足高斯分布,相當於更重視中間的
aussian = cv2.GaussianBlur(img, (5, 5), 1)
cv2.imshow('aussian', aussian)
cv2.waitKey(0)
cv2.destroyAllWindows()
運行結果如下:
# 中值濾波
# 相當於用中值代替
median = cv2.medianBlur(img, 5) # 中值濾波
cv2.imshow('median', median)
cv2.waitKey(0)
cv2.destroyAllWindows()
運行結果如下:
# 展示所有的
res = np.hstack((blur,aussian,median))
#print (res)
cv2.imshow('median vs average', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
運行結果如下: