cv2与Image互转
注意只有opencv的图片是BGR顺序的,其他都是RGB顺序
Image转cv2
cv2_img = cv2.cvtColor(numpy.asarray(Img_img),cv2.COLOR_RGB2BGR)
cv2转Image
pil_img = Image.fromarray(cv2.cvtColor(cv_img,cv2.COLOR_BGR2RGB))
UINT8 和float格式互相转换
from PIL import Image
from pylab import *
im = array(Image.open("04.jpg"))
print(im.dtype) #unit8
im3 = 255.0 * (im/255.0)**2 # 将图像像素值变换到100...200 区间
print(im3.dtype) #float64
pil_im = Image.fromarray(uint8(im3))
# 通过PIL中的fromarray方法将图片转换为uint8格式(此时的pil_im为image对象)
imshow(pil_im)
show()
使图像标准化的一种更好的方法是获取每个值并除以数据类型所经历的最大值。这可以确保图像中动态范围较小的图像保持较小,并且不会无意中标准化,从而使图像变灰。
因此,将图像类型而不是实际图像本身的每个值除以可能的最大值。然后,您将按255缩放该比例以生成归一化结果。使用numpy.iinfo
并为其提供图像的类型(dtype
),您将获得该类型的信息结构。然后,您将访问此结构中的max
字段以确定最大值。
因此,与上述情况,做如下修改你的代码:
import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64)/info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)
请注意,我还转换的图像为np.float64
的情况下,输入数据类型是不是这样,并保持浮点精确的时候做分工。