使用 Python 图像库进行 Discord.py 图像编辑仅适用于某些图片?

时间:2021-02-09 22:55:48

标签: python-imaging-library discord.py brightness

我尝试了一种图像编辑效果,该效果应该为带有小黑点的图片重新着色,但它仅适用于某些图像,老实说我不知道​​为什么。有什么想法吗?

#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 也并非一直有效。

1 个答案:

答案 0 :(得分:1)

您不起作用的图像没有 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')

改变了这个:

enter image description here

进入这个:

enter image description here


如果您接受使用普通方法计算灰度,而不是平均 R、G 和 B,您可以更改为:

im = Image.open('paddington.png').convert('L')

并删除进行平均的行:

grey = np.mean(na, axis=-1).astype(np.uint8)
相关问题