tensor-入门教程(加载数据 tensorboard 数据转换 图片操作)

PIL读取图片

from PIL import Image

bee = Image.open(r"../data_set/train/ants_image/0013035.jpg")
"""
open() Opens and identifies the given image file.
    This is a lazy operation; this function identifies the file, but
    the file remains open and the actual image data is not read from
    the file until you try to process the data
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=768x512 at 0x24D734B34C8>
open打开返回PIL类型
"""
bee.show()

SummaryWritter 和tensorboard 结合使用

from torch.utils.tensorboard import SummaryWriter
from PIL import Image  # PIL现在已经停止更新了,使用pillow
import numpy as np  # writer 支持np tensor格式


writer = SummaryWriter("../data/tensor")  # 打开事件	文件夹
"""
Writes entries directly to event files in the log_dir to be consumed by TensorBoard.
"""
img = Image.open("../data_set/train/ants_image/5650366_e22b7e1065.jpg")
img_np = np.array(img)  # 返回一个numpy
writer.add_image("demo", img_np, 1,dataformats='HWC')  # 可以是tensor 也可以是np

"""
add_image(self, tag, img_tensor, global_step=None, walltime=None, dataformats='CHW'):
Add image data to summary.
       Args:
           tag (string): Data identifier
           img_tensor (torch.Tensor, numpy.array, or string/blobname): Image data
           global_step (int): Global step value to record
           walltime (float): Optional override default walltime (time.time())
             seconds after epoch of event
       Shape:       
           img_tensor: Default is :math:(3, H, W). You can use torchvision.utils.make_grid() to
           convert a batch of tensor into 3xHxW format or call add_images and let us do the job.
           Tensor with :math:(1, H, W), :math:(H, W), :math:(H, W, 3) is also suitable as long as
           corresponding dataformats argument is passed, e.g. CHW, HWC, HW.
"""

writer.close()  # 使用完毕记得关闭,最好是创建一个writer 下面顺手写close().

在pycharm 终端 使用命令行tensorboard --logdir="文件名启动"
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

PILl 类型转换为 tensor (机器学习常用类型 tensor numpy)

from torchvision import transforms
from PIL import Image

img_path = "../data_set/train/ants_image/5650366_e22b7e1065.jpg"
img = Image.open(img_path)

tensor_train = transforms.ToTensor()  # 返回tensor类型  
tensor = tensor_train(img)
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. This transform does not support torchscript. 
       Args:
           pic (PIL Image or numpy.ndarray): Image to be converted to tensor.

       Returns:
"""

print(tensor)	 # Tensor:(3.357.500)

对图片进行归一化和修改图片大小

from PIL import Image
from torch import nn
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
"""
对图片的一些操作,归一化,切割
"""
path = "../data_set/train/ants_image/6240329_72c01e663e.jpg"
img = Image.open(path)  # PIL
tf = transforms.ToTensor()  # PIL -->ToTensor  
img_tensor = tf(img)  # tensor

writer = SummaryWriter("../normalize")  # summarywriter 结合tensorboard查看运行结果
writer.add_image("transfrom", img_tensor, 1)  # 添加transform 作为第一步 PIL -->tensor 


tfn = transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])  # Normalize
"""
Normalize a tensor image with mean and standard deviation.  进行归一化处理
  This transform does not support PIL Image.
    Given mean:  (mean[1],...,mean[n])  and std:  (std[1],..,std[n])  for  n   mean 均值 std 方差
    channels, this transform will normalize each channel of the input
        Args:
        mean (sequence): Sequence of means for each channel.
        std (sequence): Sequence of standard deviations for each channel.
        inplace(bool,optional): Bool to make this operation in-place.
"""
img_normal = tfn(img_tensor)  # tensor
writer.add_image("transfrom", img_normal, 2)


trans_resize = transforms.Resize((200, 200))  # tensor
"""
Resize the input image to the given size. 修改图片大小
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

"""
img_resize = trans_resize(img)  # 返回PIL
img_resize = tf(img_resize)
writer.add_image("resize", img_resize, 3)


seq = nn.Sequential(
    tfn,
    trans_resize
)
trans_com = transforms.Compose(seq)   # Sequential 顺序容器
"""
Composes several transforms together. This transform does not support torchscript
 Args:
        transforms (list of  Transform  objects): list of transforms to compose.

    Example:
        >>> transforms.Compose([
        >>>     transforms.CenterCrop(10),
        >>>     transforms.PILToTensor(),
        >>>     transforms.ConvertImageDtype(torch.float),
        >>> ])
               In order to script the transformations, please use  torch.nn.Sequential  as below.

        >>> transforms = torch.nn.Sequential(
        >>>     transforms.CenterCrop(10),
        >>>     transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
        >>> )
"""

img_com = trans_com(img_tensor)

writer.add_image("compose", img_com, 4)

trans_random = transforms.RandomCrop(30)  # 随机截取30*30大小的图片 
"""
Crop the given image at a random location.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions,
    but if non-constant padding is used, the input is expected to have at most 2 leading dimensions

    Args:
        size (sequence or int): Desired output size of the crop. If size is an
            int instead of sequence like (h, w), a square crop (size, size) is
            made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
        padding (int or sequence, optional): Optional padding on each border
            of the image. Default is None. If a single int is provided this
            is used to pad all borders. If sequence of length 2 is provided this is the padding
            on left/right and top/bottom respectively. If a sequence of length 4 is provided
            this is the padding for the left, top, right and bottom borders respectively.
"""
trans_random = transforms.Compose([trans_random, tf])  # 常用与返回结果不是tensor的类型,使用compose可以转成tensor
for i in range(10):
    img_crop = trans_random(img)
    writer.add_image("random_crop", img_crop, i)

writer.close()

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

参考视频哔哩哔哩小土堆

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值