一、通道的拆分
数组下标形式的拆分,代码如下:
# -*- coding: utf-8 -*-
# Data: 2023/7/2
import cv2
img1 = cv2.imread("./1-1.jpg",cv2.IMREAD_UNCHANGED)
b = img1[:,:,0]
g = img1[:,:,1]
r = img1[:,:,2]
cv2.imshow("img",img1)
cv2.imshow("img-B",b)
cv2.imshow("img-G",g)
cv2.imshow("img-R",r)
cv2.waitKey(0)
cv2.destroyAllWindows()
使用split函数进行拆分:
# -*- coding: utf-8 -*-
# Data: 2023/7/2
import cv2
img1 = cv2.imread("./1-1.jpg", cv2.IMREAD_UNCHANGED)
b, g, r = cv2.split(img1)
cv2.imshow("img", img1)
cv2.imshow("img-B", b)
cv2.imshow("img-G", g)
cv2.imshow("img-R", r)
cv2.waitKey(0)
cv2.destroyAllWindows()
效果与上面的一样
我们如果只想用split取一个通道,可以在split函数后面给下标:
b = cv2.split(a)[0]
g = cv2.split(a)[1]
r = cv2.split(a)[2]
二、合并通道
合并通道使用merge函数,一定要注意,里面是数组写法,顺序是g,b,r,而不是r,g,b,示例:
# -*- coding: utf-8 -*-
# Data: 2023/7/2
import cv2
img1 = cv2.imread("./1-1.jpg", cv2.IMREAD_UNCHANGED)
b, g, r = cv2.split(img1)
cv2.imshow("img", img1)
m = cv2.merge([b,g,r])
cv2.imshow("merge-bgr",m)
m2 = cv2.merge([r,g,b])
cv2.imshow("merge-rgb",m2)
cv2.waitKey(0)
cv2.destroyAllWindows()
g,b,r顺序才与原图一致。
下面演示下,合并其中一个通道,其他通道的值都是0的图片:
# -*- coding: utf-8 -*-
# Data: 2023/7/2
import cv2
import numpy as np
img1 = cv2.imread("./1-1.jpg", cv2.IMREAD_UNCHANGED)
rows, cols, chn = img1.shape
b1 = cv2.split(img1)[0]
g1 = np.zeros((rows, cols), img1.dtype)
r1 = np.zeros((rows, cols), img1.dtype)
m1 = cv2.merge([b1, g1, r1])
cv2.imshow("m-1", m1)
b2 = np.zeros((rows, cols), img1.dtype)
g2 = cv2.split(img1)[1]
r2 = np.zeros((rows, cols), img1.dtype)
m2 = cv2.merge([b2, g2, r2])
cv2.imshow("m-2", m2)
b3 = np.zeros((rows, cols), img1.dtype)
g3 = np.zeros((rows, cols), img1.dtype)
r3 = cv2.split(img1)[2]
m3 = cv2.merge([b3, g3, r3])
cv2.imshow("m-3", m3)
cv2.waitKey(0)
cv2.destroyAllWindows()