图像通道分离
有两种方法,一个是使用OpenCV自带的split 函数,还有一个是使用Numpy数组来分离通道.
使用OpenCV 自带 split函数
#!/usr/bin/env python
# encoding: utf-8
import cv2
import numpy as np
img = cv2.imread("mini.jpg")
b,g,r = cv2.split(img)
cv2.imshow("Blue",r)
cv2.imshow("Red",g)
cv2.imshow("Green",b)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 也可以单独返回其中一个通道
b = cv2.split(img)[0] # B通道
g = cv2.split(img)[1] # G通道
r = cv2.split(img)[2] # R通道
#!/usr/bin/env python
# encoding: utf-8
import cv2
import numpy as np
#使用Numpy 数组来实现图像通道分离
img = cv2.imread("mini.jpg")
# 创建3个跟图像一样大小的矩阵,数值全部为0
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] # 复制 b 通道的数据
g[:,:] = img[:,:,1] # 复制 g 通道的数据
r[:,:] = img[:,:,2] # 复制 r 通道的数据
cv2.imshow("Blue",b)
cv2.imshow("Red",r)
cv2.imshow("Green",g)
cv2.waitKey(0)
cv2.destroyAllWindows()
通道合并也有两种方法。一种是使用OpenCV自带的 merge 函数
merged = cv2.merge([b,g,r]) #前面分离出来的三个通道
mergedByNp = np.dstack([b,g,r])
问题: 网上看到说用Numpy 合并组合的方式与OpenCV自带的不一样,所以的结果不能在OpenCV 其它函数中使用。使用 OpenCV 自带的 merge 函数。
我的测试结果是它们的合并结果是一致的。我使用的版本是:python-2.7 opencv-2.4.7 numpy-1.7.1
测试代码如下:
merged = cv2.merge([b,g,r])
print "Merge by OpenCV"
print merged.strides
'''
merge by OpenCV
(1890, 3, 1)
'''
mergedByNp = np.dstack([b,g,r])
print "Merge by NumPy "
print mergedByNp.strides
'''
merge by Numpy
(1890, 3, 1)
'''
在Numpy 章节中有介绍。整数类型占4个字节,所以相邻元素之间的步长为4(个字节)
>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> b.strides
(16, 4) # 元素步长为 4,每个一维数组有4个元素所以每个一维数组的步长为 4*4 = 16
>>> c = np.arange(27).reshape(3,3,3)
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
>>> c.strides
(36, 12, 4) # 计算方法:(3×4×3,3×4,4 )
#!/usr/bin/env python
# encoding: utf-8
import cv2
import numpy as np
img = cv2.imread("mini.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]
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", b)
cv2.imshow("Red", r)
cv2.imshow("Green", g)
cv2.waitKey(0)
cv2.destroyAllWindows()
非常谢谢 sunny2038 知识分享,这是转载他的blog 日志
http://blog.csdn.net/sunny2038/article/details/9080047