PIL读取图片转numpy格式并用matplolib显示

本文介绍了如何利用Python中的PIL、NumPy和Matplotlib库进行图像读取、转换及显示的方法。首先通过PIL库读取一张PNG格式的图像,接着将该图像转换为NumPy数组形式,最后使用Matplotlib将图像以灰度方式展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导入库

import os
import nunpy as np
from PIL import Image
from matplotlib import pyplot as plt
os.listdir()
----------------------------OUT---------------------------
['1.png']

用PIL读取图片

im = Image.open('1.png')
----------------------------OUT---------------------------
<PIL.PngImagePlugin.PngImageFile image mode=I size=512x512 at 0x7F52D51F98D0>

转numpy格式

im = np.array(im)
----------------------------OUT---------------------------
array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=int32)

用matplotlib显示

plt.imshow(im,cmap='gray') # 以灰度图显示
plt.show()
----------------------------OUT---------------------------
<PIL.PngImagePlugin.PngImageFile image mode=I size=512x512 at 0x7F52D51F98D0>

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值