python读取并显示图像中坑

假设一个案例:cv读入图像,转化为tensor,再次转化为图像并显示
这里有很多坑点,我在代码中注解
坑点

  1. cv模块读入数据是BGR
  2. numpy数据是(H,W,C)
  3. tensor数据是(C,H,W)
  4. plt支持0-1的浮点数和0-255的整型
import matplotlib.pyplot as plt
from PIL import Image
import torchvision.transforms as transforms
import cv2 as cv
import numpy as np

img = cv.imread('./test_image/test.png') # openCV 读入数据为 BGR (坑点一)
print(type(img))
print(img.shape)   # numpy数组格式为(H,W,C)(坑点二)

transf = transforms.ToTensor() # tensor是浮点数
img_tensor = transf(img)  # tensor数据格式是torch(C,H,W) (坑点三)
print(img_tensor.size())
# tensor (c, h, w) 需要转为(h,w,c)才能正常显示
npimg = img_tensor.numpy()
# 转换维度
npimg = npimg.swapaxes(0, 2)
npimg = npimg.swapaxes(0, 1)
print(npimg.shape)
npimg = npimg[:,:,::-1] # 把BGR改成RGP
# npimg.show()
plt.imshow(npimg) # 可以直接渲染0-1浮点数
plt.show()
  • 演示效果
    在这里插入图片描述

不要以为这样就完了,真正的坑点在以下代码,注意对比区别

import matplotlib.pyplot as plt
from PIL import Image
import torchvision.transforms as transforms
import cv2 as cv
import numpy as np
from PIL import Image

img = cv.imread('./test_image/test.png') # openCV 读入数据为 BGR (坑点一)
print(type(img))
print(img.shape)   # numpy数组格式为(H,W,C)(坑点二)

transf = transforms.ToTensor()
img_tensor = transf(img)  # tensor数据格式是torch(C,H,W) (坑点三)
print(img_tensor.size())
# tensor (c, h, w) 需要转为(h,w,c)才能正常显示
npimg = img_tensor.numpy()
# 转换维度
npimg = npimg.swapaxes(0, 2)
npimg = npimg.swapaxes(0, 1)
print(npimg.shape)
npimg =  npimg * 255
# 必须转化为int类型,
npimg = npimg[:,:,::-1] # 把BGR改成RGP
# 确实从numpy转化为Image对象的,而且,必须使用int对象
npimg = Image.fromarray(np.uint8(npimg), "RGB") 
# npimg.show()
plt.imshow(npimg) # 可以直接渲染0-1
plt.show()
    

正确效果演示
在这里插入图片描述
如果npimg = Image.fromarray(np.uint8(npimg), "RGB") 使用了npimg = Image.fromarray(npimg, "RGB") 那么一个新的错误就产生了
在这里插入图片描述

  • 以上的错误来自于float和int,下面的图演示两个图片数据的区别

float类型
在这里插入图片描述
int类型,注意上面的图后面有点。
在这里插入图片描述

  • 最后希望大家注意细节,python中各个图像处理的库都有各自的特点,有微小的区别。

猜你喜欢

转载自blog.csdn.net/Fly_the_start/article/details/129741817
今日推荐