用Python Pillow库裁剪/模糊.png图像,而不改变其他任何内容。

huangapple go评论87阅读模式
英文:

How crop/blur a .png using python-pillow, wihtout changing anything else

问题

我已经找到了一些有关如何使用Python的Pillow库裁剪图像的有用帖子,但使用Pillow裁剪.png图像会使颜色失真并稍微变暗图片。我使用.png,因为我想避免在处理中图像失真。

当我运行一个甚至不进行任何裁剪的虚拟脚本时:

from PIL import Image

with Image.open('test.png') as image:
    image.save('test copy.png')

生成的副本文件大小约小于原始文件的30%,如果在照片查看器中切换它们,可以明显看到颜色较暗。如何让Pillow裁剪图片但保持颜色不变?我还希望使用局部模糊(用于匿名化)以不改变图像的其余部分来应用模糊。

编辑:上传了.png文件和褪色的副本到https://github.com/Densaugeo/stack-overflow-question/tree/main。

英文:

I've found several helpful posts on here explain how to crop an image with the Pillow library for Python, but cropping a .png with pillow distorts the colors and darkens the picture a bit. I'm using .png because I want to avoid the images getting distorted in processing.

When I run a dummy script that doesn't even do any cropping:

from PIL import Image

with Image.open('test.png') as image:
    image.save('test copy.png')

The resulting copy is ~30% smaller in file size than the original and noticeably darker, if you flip between them in a photo viewer. How do I get Pillow to crop a picture but leave the colors alone? I'd also like to do the same with local blur (for anonymization), apply a blur in one area without altering the rest of the image.

EDIT: Uploaded .png file and discolored copies to https://github.com/Densaugeo/stack-overflow-question/tree/main

答案1

得分: 2

您的 test.png 文件具有值为 50994 的 gAMA 块,但您的输出文件没有该块。为了以相同的颜色呈现,它们还需要该块。

英文:

Your test.png file has a gAMA chunk with value 50994, but your output files do not. They would also need that chunk in order to render with the same colors.

答案2

得分: 1

赞扬和给@MarkAdler的点赞,因为他找出了缺少gAMA块的问题。以下是使用exiftool将一个文件的gAMA传播到另一个文件的方法:

exiftool -tagsfromfile goodImage.png -gamma brokenImage.png

你可能可以在Python中完成这个操作,通过调整这个答案。


这里是另一种使用pngcheckpngcrush的方法。

英文:

Kudos, and upvotes to @MarkAdler for sleuthing the lack of gAMA chunk. Here is a method of propagating forward the gAMA from one file to another using exiftool:

exiftool -tagsfromfile goodImage.png -gamma brokenImage.png

You can probably do this in Python, by adapting this answer.


Here is another method using pngcheck and pngcrush.

huangapple
  • 本文由 发表于 2023年6月12日 01:29:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定