python-imaging-library - 使用 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,g,b])/3)
print(brightness)
imag.putpixel((x, y), (brightness,brightness,brightness,255))
i= 0
else:
i += 1
imag.putpixel((x,y),(255,255,255,255))
imag.save("test.png")
如果我的测试有效,我会使用这些评论。使用本地 png 也并非一直有效。
解决方案
您不起作用的图像没有 alpha 通道,但您的代码假定它有。尝试在打开时强制使用 Alpha 通道,如下所示:
imag = Image.open("unknown.png").convert('RGBA')
还有一些其他的想法:
使用 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)
推荐阅读
- npm - cljs.closure/build (closure.clj:319 3) 处的执行错误 (ExceptionInfo)。:bundle-cmd :none 失败——带有 webpack 的 clojurescript
- reactjs - 我可以通过 Netlify 使用 react-router-dom 来免费托管我的 react 应用程序吗?
- c# - 当所有 9 个面板具有相同的颜色时触发布尔
- r - 在 R 中循环一个 API 请求
- r - 是否可以检查保存在文件中的模型的 h2o 版本?
- javascript - socket io 房间没有从服务器获取任何数据
- mysql - 用于搜索产品的完美 SQL 查询
- vba - VBA - 从模块更新 ProcessBar - 错误 800100007
- flutter - 从未来中提取价值
- prolog - 计算列表中数字“1”、“2”和“3”的函数,计数表示为,例如,s(s(s(0))) = 3