cv2和numpy深度契合,其圖片讀入后就是numpy.array,只不過dtype比較不常用而已,支持全部數組方法
數組既圖片
import numpy as np import cv2 img = np.zeros((3, 3), dtype=np.uint8) # numpy數組使用np.uint8編碼就是cv2圖片格式 print(img, '\n', img.shape, '\n') img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) # 單通道轉化BGR格式3通道 print(img, '\n', img.shape)
[[0 0 0]
[0 0 0]
[0 0 0]]
(3, 3)
[[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]]
(3, 3, 3)
讀寫圖片文件
image = cv2.imread('img1.jpg') # 讀文件
cv2.imwrite('img1.png', image) # 寫文件
print(image.shape)
(2716, 1920, 3)
灰度模式讀取
grayImage = cv2.imread('img2.jpg', cv2.IMREAD_GRAYSCALE) # 讀取為灰度模式
cv2.imwrite('img2_gray.png', grayImage)
True
數組or圖片屬性查詢
img = cv2.imread('img1.jpg') # 圖片屬性查詢
print(img[0, 0])
print(img.shape)
print(img.size)
print(img.dtype)
[18 18 18]
(2716, 1920, 3)
15644160
uint8
其他演示
cv2.cvtColor(img,cv2.COLOR_BAYER_BG2BGR)
img.item(0,0)
img.itemset((0,0),0)
cv2.imshow('my image',img)
cv2.waitKey()
cv2.destroyAllWindows()
1 # coding=utf-8 2 import cv2 3 import numpy as np 4 5 # array數組生成 6 img = np.zeros((3,3),dtype=np.uint8) 7 print img.shape 8 9 # array數組轉化為BGR模式 10 # 我也不懂為什么不用RGB而用BGR這么蹩腳的用法 11 img = cv2.cvtColor(img,cv2.COLOR_BAYER_BG2BGR) 12 print img.shape 13 14 # 讀取圖片,左上像素點改寫為藍色,保存 15 img = cv2.imread('beauti.jpeg') 16 img[0][0] = [255,0,0] 17 cv2.imwrite('MyPic.png',img) 18 19 # 丟失顏色信息,左上像素點改寫為黑色,保存 20 img = cv2.imread('beauti.jpeg',cv2.IMREAD_GRAYSCALE) 21 print img.shape 22 img[0][0] = 0 23 cv2.imwrite('MyPic-gray.png',img) 24 25 # 使用array.item和array.itemset優雅的重寫上面代碼 26 img = cv2.imread('beauti.jpeg',cv2.IMREAD_GRAYSCALE) 27 print img.shape 28 #img[0][0] = 0 29 print img.item(0,0) 30 img.itemset((0,0),0) 31 cv2.imwrite('MyPic-gray.png',img) 32 33 # 去掉綠色通道 34 img = cv2.imread('beauti.jpeg') 35 img[:,:,1] = 0 36 cv2.imwrite('no_green.png',img) 37 print img.shape,img.size,img.dtype 38 39 img = cv2.imread('beauti.jpeg') 40 # 顯示圖片,必須輸入兩個參數 41 cv2.imshow('my image',img) 42 # 窗口展示時間 43 cv2.waitKey() 44 # 釋放窗口 45 cv2.destroyAllWindows()
