将图像文件中的特定 RGB 颜色像素更改为另一种颜色
我想用Python改变单一颜色。
如果存在 PIL 的快速解决方案,我会更喜欢这个解决方案。
目前,我使用
convert -background black -opaque '#939393' MyImage.png MyImage.png
I would like to change a single color with Python.
If a fast solution with PIL exists, I would prefer this solution.
At the moment, I use
convert -background black -opaque '#939393' MyImage.png MyImage.png
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的计算机上可以使用 numpy,请尝试执行以下操作:
它将使用更多 (3 倍) 的内存,但速度应该要快得多(约 5 倍,但对于较大的图像,速度会更快)。
另请注意,如果您只有 RGB(而不是 RGBA)图像,上面的代码会比实际需要的代码稍微复杂一些。然而,这个例子将单独保留 alpha 波段,而更简单的版本则不会。
If
numpy
is available on your machine, try doing something like:It will use a bit (3x) more memory, but it should be considerably (~5x, but more for bigger images) faster.
Also note that the code above is slightly more complicated than it needs to be if you only have RGB (and not RGBA) images. However, this example will leave the alpha band alone, whereas a simpler version wouldn't have.
这是对乔·金顿上述答案的修改。如果您的图像也包含 Alpha 通道,以下是如何执行此操作。
我花了很长时间才弄清楚如何让它发挥作用。我希望它对其他人有帮助。
This is a modification of Joe Kington's answer above. The following is how to do this if your image contains an alpha channel as well.
It took me a long time to figure out how to get it to work. I hope that it helps someone else.
我刚刚想出了这个解决方案:
虽然 putpixel 速度不快,但对我来说似乎足够快了。
I've just came up with this solution:
Although putpixel isn't fast, it seems to be fast enough for me.
此解决方案使用
glob
编辑文件夹中的所有 png,删除一种颜色并将其替换为另一种颜色,但使用 RGBA。这是 https://stackoverflow.com/a/6483549/541208 的修改
This solution uses
glob
to edit all pngs in a folder, removing a color and swapping it out with another, but uses RGBA.It's a modification of https://stackoverflow.com/a/6483549/541208