4.3 图像元素访问、通道分离与合并

对图像方面了解,可参考:http://www.cambridgeincolour.com/

  1. 元素访问 通过对图像添加人工的椒盐现象了解元素访问
import cv2
import numpy as np
def salt(img, n):
    for k in range(n):
        i = int(np.random.random() * img.shape[1]);
        j = int(np.random.random() * img.shape[0]);
        if img.ndim == 2: 
            img[j,i] = 0
        elif img.ndim == 3: 
            img[j,i,0]= 0
            img[j,i,1]= 0
            img[j,i,2]= 0
    return img
if __name__ == '__main__':
    img = cv2.imread("G:\\python project\\cat.jpg")
    saltImage = salt(img, 500)
    cv2.imshow("Salt", saltImage)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

对于灰度图,只需要img[i,j]就可以进行访问赋值(0-255不同灰度值:0为黑,255为白);对于RGB,多了第三个量--通道(0:R通道;1:G通道;2:B通道),赋值为0-255。

结果:

2.通道分离:可以直接通过Opencv中split()函数

b, g, r = cv2.split(img)
  1. 通道合并:可以直接通过Opencv中merge()函数
merged = cv2.merge([b,g,r])

当然,通道分离与合并可以通过其他方法(如:Numpy)进行,完整代码

import cv2
import numpy as np
img = cv2.imread("G:\\python project\\cat.jpg")
b, g, r = cv2.split(img)
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", merged)
cv2.imshow("Blue", b)
cv2.imshow("Red", r)
cv2.imshow("Green", g)
cv2.waitKey(0)
cv2.destroyAllWindows()

运行结果:

原创自:http://blog.csdn.net/sunny2038/article/details/9080047(作者:sunny2038)

results matching ""

    No results matching ""