- Python 3.6
- opencv-python==3.4.2.16
- numpy==1.16.2
针对不同数据类型的numpy.ndarray,cv2.imshow()处理结果不同。
本文就此进行试验,新建不同类型的numpy.ndarray,使用cv2.imshow()显示结果分析。
使用pycharm按住Ctrl加鼠标左键进入函数cv2.imshow()可以看见文档
The function imshow displays an image in the specified window. If the window was created with the
. cv::WINDOW_AUTOSIZE flag, the image is shown with its original size, however it is still limited by the screen resolution.
. Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth:
.
. - If the image is 8-bit unsigned, it is displayed as is.
. - If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the
. value range [0,255*256] is mapped to [0,255].
. - If the image is 32-bit or 64-bit floating-point, the pixel values are multiplied by 255. That is, the
. value range [0,1] is mapped to [0,255].
机翻:
imshow函数在指定窗口中显示图像。如果窗口是用WINDOW_AUTOSIZE标志,图像以其原始大小显示,但仍受屏幕分辨率的限制。
否则,将缩放图像以适应窗口。该函数可根据图像的深度缩放图像:
如果图像是8位无符号的,则按原样显示。
如果图像是16位无符号或32位整数,则像素除以256。也就是说值范围[0, 255*256]映射到[0, 255]。
如果图像是32位或64位浮点,则像素值乘以255。也就是说值范围[0, 1]映射到[0, 255]。
写demo演示
测试不同数据类型
uint8
import cv2
import numpy as np
height, width = 200, 200
def test_uint8():
img_a = np.zeros((height, width, 3), dtype='uint8')
img_a[:, :, 0] = 255
print(f'img_a[0, 0, 0]={img_a[0, 0, 0]}\n'
f'type(img_a)={type(img_a)}\nimg_a.dtype={img_a.dtype}\nimg_a.shape={img_a.shape}\n')
'''
img_a[0, 0, 0]=255
type(img_a)=<class 'numpy.ndarray'>
img_a.dtype=uint8
img_a.shape=(200, 200, 3)
'''
img_b = np.zeros((height, width, 3), dtype='uint8')
img_b[:, :, 0] = 0.8
print(f'img_b[0, 0, 0]={img_b[0, 0, 0]}\n'
f'type(img_b)={type(img_b)}\nimg_b.dtype={img_b.dtype}\nimg_b.shape={img_b.shape}\n')
'''
img_b[0, 0, 0]=0
type(img_b)=<class 'numpy.ndarray'>
img_b.dtype=uint8
img_b.shape=(200, 200, 3)
'''
img_c = np.zeros((height, width, 3), dtype='uint8')
img_c[:, :, 0] = 300
print(f'img_c[0, 0, 0]={img_c[0, 0, 0]}\n'
f'type(img_c)={type(img_c)}\nimg_c.dtype={img_c.dtype}\nimg_c.shape={img_c.shape}\n')
'''
img_c[0, 0, 0]=44
type(img_c)=<class 'numpy.ndarray'>
img_c.dtype=uint8
img_c.shape=(200, 200, 3)
'''
img_d = np.zeros((height, width, 3))
img_d[:, :, 0] = 256
print(f'img_d[0, 0, 0]={img_d[0, 0, 0]}\n'
f'type(img_d)={type(img_d)}\nimg_d.dtype={img_d.dtype}\nimg_d.shape={img_d.shape}\n')
# 对其进行类型转换
img_d = img_d.astype('uint8')
print(f'img_d[0, 0, 0]={img_d[0, 0, 0]}\n'
f'type(img_d)={type(img_d)}\nimg_d.dtype={img_d.dtype}\nimg_d.shape={img_d.shape}\n')
'''
img_d[0, 0, 0]=256.0
type(img_d)=<class 'numpy.ndarray'>
img_d.dtype=float64
img_d.shape=(200, 200, 3)
img_d[0, 0, 0]=0
type(img_d)=<class 'numpy.ndarray'>
img_d.dtype=uint8
img_d.shape=(200, 200, 3)
'''
cv2.imshow('a', img_a)
cv2.imshow('b'