python,pytorch:读取,保存,显示图片
程序员文章站
2022-03-19 22:09:32
...
一,Pytorch
1. 直接保存Tensor
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import torch
from torchvision import utils as vutils
def save_image_tensor(input_tensor: torch.Tensor, filename):
"""
将tensor保存为图片
:param input_tensor: 要保存的tensor
:param filename: 保存的文件名
"""
assert (len(input_tensor.shape) == 4 and input_tensor.shape[0] == 1)
# 复制一份
input_tensor = input_tensor.clone().detach()
# 到cpu
input_tensor = input_tensor.to(torch.device('cpu'))
# 反归一化
# input_tensor = unnormalize(input_tensor)
vutils.save_image(input_tensor, filename)
2.Tensor 转CV2 保存
二、python
1. opencv
import cv2 as cv
# load `在这里插入代码片`
img = cv.imread(imagepath)
# shape=(height, width, channel)
h,w,c = img.shape
# show
cv.imshow('window_title', img)
# save
cv.imwrite(savepath, img)
2.matplotlib:
import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
import numpy as np
# load
img = mpimg.imread('cat.jpg')
# 此时 img 就已经是一个 np.array 了,可以对它进行任意处理
# height, width, channel=(360, 480, 3)
h,w,c = img.shape
# show
plt.imshow(img) # 显示图片
plt.axis('off') # 不显示坐标轴
plt.show()
# save
# 适用于保存任何 matplotlib 画出的图像,相当于一个 screencapture
plt.savefig('fig_cat.png')
3. PIL
from PIL import Image
import matplotlib.pyplot as plt
img=Image.open('/home/wanghao/Pictures/001.jpg')
plt.figure("head")
plt.imshow(img)
plt.show()