#-*-coding=UTF-8-*-
#使用OpenCV自带的split函数,输出为黑白图像
import cv2
import numpy as np
img=cv2.imread("E:\\testpictures\\meizi4.jpg")
'''
下面一句话可以这样
b = cv2.split(img)[0]
g = cv2.split(img)[1]
r = cv2.split(img)[2]
'''
b,g,r=cv2.split(img)
cv2.imshow("Blue",r)
cv2.imshow("Red",g)
cv2.imshow("Green",b)
cv2.waitKey(0)
cv2.destroyAllWindows()
#第二:用numpy数组来实现:
#-*-coding=UTF-8-*-
#直接操作NumPy数组来达到这一目的
import cv2
import numpy
import numpy as np
img=cv2.imread("E:\\testpictures\\meizi9.jpg")
b=np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
g=np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
r=np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
b[:,:]=img[:,:,0]
g[:,:]=img[:,:,1]
r[:,:]=img[:,:,2]
cv2.imshow("Blue",r)
cv2.imshow("Red",g)
cv2.imshow("Green",b)
cv2.waitKey(0)
cv2.destroyAllWindows()
从上面的图可以看出,颜色通道的分离能让有些条纹变得非常清晰有助于处理。
一下合并各通道:
#-*-coding=UTF-8-*-
#合并三个通道的图像
'''
注意:这里只是演示,实际使用时请用OpenCV自带的merge函数!
用NumPy组合的结果不能在OpenCV中其他函数使用,
因为其组合方式与OpenCV自带的不一样.
'''
import cv2
import numpy as np
img=cv2.imread("E:\\testpictures\\meizi9.jpg")
b=np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
g=np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
r=np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
b[:,:]=img[:,:,0]
g[:,:]=img[:,:,1]
r[:,:]=img[:,:,2]
#用opencv自带的merge函数
merged=cv2.merge([b,g,r])
print "Merge by OpenCV"
print merged.strides
print merged
mergedByNp=np.dstack([b,g,r])
print "Merge by Numpy"
print mergedByNp.strides
print mergedByNp
cv2.imshow("Merged",merged)
cv2.imshow("MergedByNp",mergedByNp)
cv2.imshow("Blue",r)
cv2.imshow("Red",g)
cv2.imshow("Green",b)
cv2.waitKey(0)
cv2.destroyAllWindows()