【OpenCV】高手勿入! 半小時學會基本操作 5
- 概述
- 影像處理
- 轉換影像
- 轉換成灰度圖
- HSV
- YUV
- 二值化操作
- 原圖
- Binary
- Binary Inverse
- Trunc
- Tozero
- Tozero Inverse
概述
OpenCV 是一個跨平臺的計算機視覺庫, 支持多語言, 功能強大. 今天小白就帶大家一起攜手走進 OpenCV 的世界. (第 5 課)

影像處理
影像處理是非常基礎和關鍵的, 今天就帶大家來一起了解一下影像處理.

轉換影像
cv.cvtColor可以幫助我們轉換圖片通道.
格式:
cv2.cvtColor(src, code[, dst[, dstCn]])
引數:
- src: 需要轉換的圖片
- code: 顏色空間轉換碼
- dst: 輸出影像大小深度相同, 可選引數
- desCn: 輸出影像的顏色通道, 可選引數
轉換成灰度圖
RGB 到灰度圖轉換公式:
Y' = 0.299 R + 0.587 G + 0.114 B
例子:
# 讀取資料
img = cv2.imread("cat.jpg")
# 轉換成灰度圖
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 輸出維度
print(img_gray.shape) # (554, 640)
# 展示影像
cv2.imshow("img_gray", img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出結果:

HSV
HSV (Hue, Saturation, Value) 是根據顏色的直觀特性由 A.R. Smith 在 1978 年創建的一種顏色空間.
例子:
# 轉換成hsv
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 輸出維度
print(img_hsv.shape) # (554, 640, 3)
# 展示影像
cv2.imshow("img_hsv", img_hsv)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出結果:

YUV
YUV 是一種顏色編碼的方法, 主要用在視頻, 圖形處理流水線中.
例子:
# 讀取資料
img = cv2.imread("cat.jpg")
# 轉換成hsv
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
# 輸出維度
print(img_yuv.shape) # (554, 640, 3)
# 展示影像
cv2.imshow("img_yuv", img_yuv)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出結果:

二值化操作
格式:
ret, dst = cv2.threshold(src, thresh, maxval, type)
引數:
- src: 需要轉換的圖
- thresh: 閾值
- maxval: 超過閾值所賦的值
- type: 二值化操作型別
回傳值:
- ret: 輸入的閾值
- dst: 處理好的圖片
原圖

Binary
大于閾值的設為 255, 低于或等于閾值的為 0.
例子:
# 讀取資料
img_gray = cv2.imread("cat_gray.jpg")
# 二值化
ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
# 圖片展示
cv2.imshow("thresh1", thresh1)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出結果:

Binary Inverse
與 Binary 相反.
例子:
# 讀取資料
img_gray = cv2.imread("cat_gray.jpg")
# 二值化
ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
# 圖片展示
cv2.imshow("thresh2", thresh2)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出結果:

Trunc
大于閾值的設為 255, 低于或等于閾值的不變.
例子:
# 讀取資料
img_gray = cv2.imread("cat_gray.jpg")
# 截斷
ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
# 圖片展示
cv2.imshow("thresh3", thresh3)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出結果:

Tozero
大于閾值部分不變, 否則設為 0.
代碼:
# 讀取資料
img_gray = cv2.imread("cat_gray.jpg")
# Tozero
ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
# 圖片展示
cv2.imshow("thresh4", thresh4)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出結果:

Tozero Inverse
與 Tozero 相反.
代碼:
# 讀取資料
img_gray = cv2.imread("cat_gray.jpg")
# Tozero
ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
# 圖片展示
cv2.imshow("thresh5", thresh5)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/289643.html
標籤:其他
