转代码,tensor转图片保存

from PIL import Image

import numpy as np

import torch

# 保存灰度图像

def save_gray_image(tensor, file_path):

# 将tensor转换为numpy数组

array = tensor.squeeze().cpu().numpy()

# 将像素值缩放到0-255之间

array = (array * 255).astype(np.uint8)

# 创建图像对象

image = Image.fromarray(array, mode='L')

# 保存图像

image.save(file_path)

# 保存彩色图像

def save_color_image(tensor, file_path):

# 将tensor转换为numpy数组

array = tensor.squeeze().cpu().numpy()

# 将像素值缩放到0-255之间

array = (array * 255).astype(np.uint8)

# 转换为RGB顺序

array = np.transpose(array, (1, 2, 0))

# 创建图像对象

image = Image.fromarray(array, mode='RGB')

# 保存图像

image.save(file_path)

# 创建1*1*1024*1024的灰度图像tensor

gray_tensor = torch.rand(1, 1, 1024, 1024)

# 保存为灰度图像

save_gray_image(gray_tensor, 'gray_image.jpg')

# 创建1*3*1024*1024的彩色图像tensor

color_tensor = torch.rand(1, 3, 1024, 1024)

# 保存为彩色图像

save_color_image(color_tensor, 'color_image.jpg')

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值