Record_ 07_使用opencv對彩色影象中各個通道影象提取,顯示和儲存
阿新 • • 發佈:2021-01-07
領導給安排任務,讓我將提取出的彩色影象中RGB三個通道的圖與紅外影象做對比,上網一搜,知乎大佬的程式碼給的非常詳細,在此感謝大佬,並對程式碼進行丁點優化。
優化程式碼如下
import cv2
import os
import time
import numpy as np
def channel_extract(im,root,rows,cols,channel):
# 初始化一個大小一樣的影象,元素初始化為0
created = np.zeros((rows, cols))
# for in 語句,遍歷陣列,但不能修改陣列
for i in im:
for j in i:
pass
# 給created資料賦值
for i in range(0, rows):
for j in range(0, cols):
created[i, j] = im[i, j, channel]
# 必須加這一條語句, 否則無法正確顯示影象
created = created.astype(np.uint8)
extract_path = os.path.join(root, "{}.jpg" .format(time.time() * 10000))
cv2.imwrite(extract_path, created)
return created
def rgb_extract():
root = "C:/0101/2021_01_06_15"
root_0 = "C:/0101/2021_01_06_15_0"
root_1 = "C:/0101/2021_01_06_15_1"
root_2 = "C:/0101/2021_01_06_15_2"
for parent, _, fnames in os. walk(root):
for fname in fnames:
if fname.endswith("png") or fname.endswith("jpg"):
fname = os.path.join(parent, fname)
# 顯示彩色影象
im = cv2.imread(fname)
cv2.imshow("RGB",im)
cv2.waitKey(1000)
cv2.destroyAllWindows()
# 顯示灰度影象
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray",gray)
cv2.waitKey(1000)
cv2.destroyAllWindows()
# 獲得影象大小
rows, cols, _ = im.shape
# B通道:通道0影象
created_0 = channel_extract(im,root_0,rows, cols, channel=0)
cv2.imshow("channel_0", created_0)
cv2.waitKey(1000)
cv2.destroyAllWindows()
# G通道:通道1影象
created_1 = channel_extract(im,root_1,rows, cols, channel=1)
cv2.imshow("channel_1", created_1)
cv2.waitKey(1000)
cv2.destroyAllWindows()
# R通道:通道2影象
created_2 = channel_extract(im,root_2,rows, cols, channel=2)
cv2.imshow("channel_2", created_2)
cv2.waitKey(1000)
cv2.destroyAllWindows()
if __name__ == '__main__':
rgb_extract()
大佬的程式碼讓我再次感受到影象就是矩陣,其實就是將彩色影象各個通道的畫素矩陣的畫素值進行匯出,複製到一個新的矩陣中,並將這個矩陣顯示以及儲存下來。印象深刻!!!
程式碼進行簡單說明:
root是彩色影象路徑
root_0是0通道影象,即B通道影象儲存路徑
root_1是1通道影象,即G通道影象儲存路徑
root_2是2通道影象,即R通道影象儲存路徑