Pytorch基础:数据读取与预处理——图像读取与存储

Pytorch基础:数据读取与预处理——图像读取与存储

1.读取图片

  • 图像库 opencv-python、imageio、PIL 等都具有图像读取的功能。
(base) PS C:\Users\阳> conda activate yang
(yang) PS C:\Users\阳> python
Python 3.11.5 | packaged by Anaconda, Inc. | (main, Sep 11 2023, 13:26:23) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>>
>>> import PIL
>>> from PIL import Image
>>>
>>> # 读取本地图片
>>> image=Image.open("D:\\阳\\工作\\1.机器视觉\\2D视觉\\VisionPro学习\\动态卡尺自动路径搜索\\1.jpg")
>>> print("image width:",image.width)
image width: 1000
>>> print("image width:",image.height)
image width: 750
>>>
>>> image=image.resize(size=(256,256),resample=PIL.Image.NEAREST)
>>> print("image width:",image.width)
image width: 256
>>> print("image width:",image.height)
image width: 256
>>>
  • Image 的创建也可以通过 numpy 完成。
>>> import numpy as np
>>>
>>> line=np.linspace(0,255,256)
>>> line=np.expand_dims(line,0)
>>> image=np.tile(line,(256,1))
>>> image=image.astype(np.uint8)
# 从numpy创建Image对象
>>> image=Image.fromarray(image)
# 保存图像
>>> image.save("D:\\孙明阳\\工作\\1.机器视觉\\2D视觉\\VisionPro学习\\动态卡尺自动路径搜索\\3.jpg")

在这里插入图片描述

2. 使用 matplotlib 库显示和保存图像

  • 如果电脑没有安装matplotlib,则需要执行以下命令:
conda activate yang //进入虚拟环境
conda install -c conda-forge matplotlib  //安装matplot

(base) PS C:\Users\孙明阳> conda activate yang
(yang) PS C:\Users\孙明阳> python
Python 3.11.5 | packaged by Anaconda, Inc. | (main, Sep 11 2023, 13:26:23) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import numpy as np
>>> from PIL import Image
>>> import matplotlib.pyplot as plt
>>>
>>> rows=2
>>> cols=2
>>> for i in range(rows*cols):
...     plt.subplot(rows,cols,i+1)
...     plt.title("Figure "+ str(i))
...     plt.imshow(image)
>>> plt.savefig("fareguan.jpg",dpi=500,bbox_inches='tight')
>>> plt.show()
>>>


//Format 'bmp' is not supported (supported formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff, webp)
  • 需要注意的是 plt.savefig 是不支持bmp 格式的。它支持的格式有 eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff, webp
  • 但是 Image.open 可以打开 bmp 文件。
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MechMaster

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值