如何解决使用 Python 图像库进行 Discord.py 图像编辑仅适用于某些图片?
我尝试了一种图像编辑效果,该效果应该为带有小黑点的图片重新着色,但它仅适用于某些图像,老实说我不知道为什么。有什么想法吗?
#url = member.avatar_url
#print(url)
#response = requests.get(url=url,stream=True).raw
#imag = Image.open(response)
imag = Image.open("unknown.png")
#out = Image.new('I',imag.size)
i = 0
width,height = imag.size
for x in range(width):
i+=1
for y in range(height):
if i ==5:
# changes every 5th pixel to a certain brightness value
r,g,b,a = imag.getpixel((x,y))
print(imag.getpixel((x,y)))
brightness = int(sum([r,b])/3)
print(brightness)
imag.putpixel((x,y),(brightness,brightness,255))
i= 0
else:
i += 1
imag.putpixel((x,(255,255,255))
imag.save("test.png")
如果我的测试有效,我会使用这些评论。使用本地 png 也并非一直有效。
解决方法
您不起作用的图像没有 alpha 通道,但您的代码假定它有。尝试在打开时强制使用 Alpha 通道,如下所示:
imag = Image.open("unknown.png").convert('RGBA')
另见What's the difference between a "P" and "L" mode image in PIL?
还有其他一些想法:
-
使用 Python
for
循环遍历图像缓慢且效率低下 - 通常,尝试找到矢量化的 Numpy 替代方案 -
您有一个 alpha 通道,但在任何地方都将其设置为
255
(即不透明),因此实际上,您最好没有它并节省大约 1/4 的文件大小 -
您的输出图像是 RGB,所有 3 个组件设置相同 - 这实际上是一个灰度图像,因此您可以这样创建它,并且您的输出文件将是其大小的 1/3
所以,这里是另一种演绎:
#!/usr/bin/env python3
from PIL import Image
import numpy as np
# Load image and ensure neither palette nor alpha
im = Image.open('paddington.png').convert('RGB')
# Make into Numpy array
na = np.array(im)
# Calculate greyscale image as mean of R,G and B channels
grey = np.mean(na,axis=-1).astype(np.uint8)
# Make white output image
out = np.full(grey.shape,255,dtype=np.uint8)
# Copy across selected pixels
out[1::6,1::4] = grey[1::6,1::4]
out[3::6,0::4] = grey[3::6,0::4]
out[5::6,2::4] = grey[5::6,2::4]
# Revert to PIL Image
Image.fromarray(out).save('result.png')
改变了这个:
进入这个:
如果您接受使用普通方法计算灰度,而不是平均 R、G 和 B,您可以更改为:
im = Image.open('paddington.png').convert('L')
并删除进行平均的行:
grey = np.mean(na,axis=-1).astype(np.uint8)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。