基本屬性
包括:
讀取到的圖片數(shù)據(jù)的類型
圖片數(shù)據(jù)的類型
圖片的維度
圖片的形狀
圖片的大小
import cv2 # 導(dǎo)入 cv2
from functools import reduce
img = cv2.imread("***.jpg") # 讀取圖片
print('type of image: ', type(img))
print('dtype of image: ', img.dtype)
print('dim of image :', img.ndim)
print('shape of image :', img.shape)
print('size of image :', img.size)
print('{} = {}'.format('*'.join(map(str, img.shape)), reduce(lambda x, y: x * y, img.shape)))
結(jié)果:
type of image: <class 'numpy.ndarray'>
dtype of image: uint8
dim of image : 3
shape of image : (574, 733, 3)
size of image : 1262226
5747333 = 1262226
總結(jié):
從上面結(jié)果中可以看到躯保,opencv讀取出的圖片類型其實(shí)是ndarray坐儿,因此可以聯(lián)想到numpy數(shù)據(jù)中具備的一些功能接口玻熙,在這里也是通用的裹唆。
顏色空間
- opencv 中讀取到的圖像數(shù)據(jù),3個(gè)通道的排列順序依次為B,G,R,因此直接讀取出的圖像顯示效果與原圖不相同,需要將通道順序調(diào)整為RGB
# 法1: 提取出各通道脖含,直接調(diào)整順序
import cv2
import numpy as np
img= cv2.imread("****.jpg")
img_shape = img.shape
img_b = img[ :, :, 0]
img_g = img[ :, :, 1]
img_r = img[ :, :, 2]
img_rgb = np.full(img_shape, 0, dtype=np.uint8)
img_rgb [ :, :, 0] = img_r
img_rgb [ :, :, 1] = img_g
img_rgb [ :, :, 2] = img_b
# 或者直接使用簡(jiǎn)便方法
img_rgb = img_rgb[ :, :, ::-1] # 第3個(gè)維度,也就是通道維度投蝉,以相反的順序排布
# 法2:直接使用cv2.cvtColor轉(zhuǎn)換通道順序
img_bgr = cv2.cvtColor(img, cv2.COLOR_BRG2RGB)
plt.imshow(img_bgr)
通道數(shù)據(jù)的拆分與組合
b, g , r = cv2.split(img) # 拆分為獨(dú)立的3個(gè)通道數(shù)據(jù)
merge_img = cv2.merge([r, g, b]) # 將3個(gè)通道數(shù)據(jù)組合形成一幅圖片像素