栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python3 PIL库问题:ImageChops.difference返回None

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python3 PIL库问题:ImageChops.difference返回None

遇到一个关于python PIL库的问题:在python3中,两张明显不同的图片,使用ImageChops.difference 方法计算他们的差异,diff.getbbox()返回值为None,相同的代码在python2中运行就没有问题:

im_source_obj = Image.open(self.im_source_path)
im_target_obj = Image.open(self.im_target_path)
diff = ImageChops.difference(im_source_obj, im_target_obj)
if diff.getbbox() is None:
	print("图片相同")

我的python3版本为 Python 3.7.6,Pillow== 8.4.0;python2版本为 Python 2.7.16,Pillow == 6.2.2 。

解决方案:

stackoverflow上有类似的问题:https://stackoverflow.com/questions/61812374/imagechops-difference-not-working-with-simple-png-images

转换为RGB通道:

im_source_obj = Image.open(self.im_source_path).convert('RGB')
im_target_obj = Image.open(self.im_target_path).convert('RGB')
print(im_source_obj.mode)
diff = ImageChops.difference(im_source_obj, im_target_obj)
if diff.getbbox() is None:
	print("图片相同")

Image.open() 方法默认返回的是RGBA模式,多一个alpha通道,用来记录图像的透明度。其实python2也返回的是RGBA模式,不知道具体是什么原因导致python3中需要转换为RGB通道,也可能是版本问题。

--THE END--
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/422955.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号