獲取圖像屬性
1: 形狀-shape: 通過shape關鍵字獲取圖像的形狀,返回包含行數、列數、通道數的元祖。其中灰度圖像返回行數和列數,彩色圖像返回行數、列數和通道數
import cv2 img = cv2.imread("result.jpg", cv2.IMREAD_UNCHANGED) # 返回行數,列數,通道數 print(img.shape) # (515, 425, 3)
2:像素數目-size: 通過size關鍵字獲取圖像的像素數目,其中灰度圖像返回行數 * 列數,彩色圖像返回行數 * 列數 * 通道數
import cv2 img = cv2.imread("result.jpg", cv2.IMREAD_UNCHANGED) print(img.size) # 656625
3:圖像類型-dtype: 通過dtype關鍵字獲取圖像的數據類型,通常返回uint8
import cv2 img = cv2.imread("result.jpg", cv2.IMREAD_UNCHANGED) # 獲取圖像類型, 通常返回uint8 print(img.dtype) # uint8
圖像通道處理
1: 通道拆分: OpenCV讀取的彩色圖像由B、G、R三原色組成,可以通過下面代碼獲取不同的通道.(b=img[位置參數, 0] g=img[位置參數, 1] r=img[位置參數, 2])
借助split()函數拆分通道
import cv2 img = cv2.imread("result.jpg", cv2.IMREAD_UNCHANGED) # 拆分通道 b, g, r = cv2.split(img) cv2.imshow("B", b) cv2.imshow("G", g) cv2.imshow("R", r) cv2.waitKey(0) cv2.destroyAllWindows()
2:通道合並: 圖像通道合並主要調用merge()函數實現(m = cv2.merge([r, g, b]))
import cv2 img = cv2.imread("result.jpg", cv2.IMREAD_UNCHANGED) b, g, r = cv2.split(img) m = cv2.merge([r, g, b]) cv2.imshow("Demo", m)
可以修改通道之后再合並
import cv2 import numpy as np img = cv2.imread("result.jpg", cv2.IMREAD_UNCHANGED) rows, cols, chn = img.shape b1 = cv2.split(img)[0] # G, R通道設置為0, g1 = np.zeros((rows, cols), dtype=img.dtype) r1 = np.zeros((rows, cols), dtype=img.dtype) m1 = cv2.merge([b1, g1, r1]) cv2.imshow("Demo1", m1) cv2.waitKey(0) cv2.destroyAllWindows()
效果如下:
轉自:https://blog.csdn.net/Eastmount/category_7912787.html