使用 PIL, OpenCV, Matplotlib 获取图片通道数

本文介绍了使用PIL、OpenCV及Matplotlib等库获取图片通道数的方法,并对比了不同库在处理索引颜色图像时的区别。推荐使用PIL库进行图片读取。

1. PIL

img = Image.open(img_path)
# getbands() 返回包含此图像中每个波段名称的元组。例如,RGB 图像返回 (“R”, “G”, “B”) 。
len(img.getbands())

[参考] https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.getbands

[参考] python - Number of channels in pil (pillow) image - Stack Overflow: https://stackoverflow.com/questions/52962969/number-of-channels-in-pil-pillow-image

2. OpenCV

import cv2
img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
# img.shape 包含三个值依次为垂直尺寸(高),水平尺寸(宽)和通道数
img.shape[2]

3. Matplotlib (plt)

This function exists for historical reasons. It is recommended to use PIL.Image.open instead for loading images.

官方推荐使用 PIL.Image.open 读取图片,故这儿也不再展示 Matplotlib 读取图片的方式

[参考] matplotlib.pyplot.imread — Matplotlib 3.5.2 documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imread.html

4. 特殊情况(OpenCV, PIL 读取通道数结果不同)

4.1. 场景

palette 类型的图像中 (img.modep) ,也就是索引值组成的图像时,OpenCV 和 PIL 读取的通道数结果不同。

4.2. 原因

OpenCV 会自动加载扩展,将此类型图片转化为 RGB 图像处理,所以通道数会显示为 3;PIL 保留原始读取结果,所以通道数为 1

综上在识别图片通道数时,个人更加推荐 PIL

[参考] opencv - why does reading image with cv2 has different behavior from PIL? - Stack Overflow: https://stackoverflow.com/questions/61952256/why-does-reading-image-with-cv2-has-different-behavior-from-pil

[扩展] python - What is the difference between images in ‘P’ and ‘L’ mode in PIL? - Stack Overflow: https://stackoverflow.com/questions/52307290/what-is-the-difference-between-images-in-p-and-l-mode-in-pil/52307690#52307690


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

零一魔法

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

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

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

打赏作者

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

抵扣说明:

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

余额充值