python - PIL putpixels函数

标签 python numpy python-imaging-library

我正在使用 PIL 使图像的颜色四舍五入为最接近的颜色。然而,当我这样做时,我使用函数 putpixel 遇到了许多错误。我尝试将 RGB 值转换为 int,以防它们是 float。我尝试只使用 RGB 的 int 形式,但到目前为止似乎没有任何效果。

以下是我的尝试:

import numpy as np

from PIL import Image

im = Image.open("milford_sound_new_zealand_bay_reflection_mountains_104080_1920x1080.jpg");

out = Image.new('I', im.size, 0xffffff);

col_amt = 10;
cold = []

def nearest(arr, val):
    arr = np.asarray(arr)
    idx = (np.abs(arr - val)).argmin()
    return arr[idx]

def rgbint(r,g,b):
    rgb = r;
    rgb = (rgb << 8) + g
    rgb = (rgb << 8) + b
    return rgb

def intrgb(rgb):
    return(rgb // 256 // 256 % 256, rgb // 256 % 256, rgb % 256)


for i in range(col_amt):
    rgb = ((256*256*256)-1)/(col_amt-1) * i;
    #print(rgb);
    cold.append(rgb)

cold = np.array(cold)

width, height = im.size
for x in range(width):
    for y in range(height):
        r,g,b = im.getpixel((x,y))
        d = rgbint(r,g,b)
        cd = nearest(cold, d)
        rgb = intrgb(cd)
        #if b < g and b < r or r==g==b:
        #print(rgb)
        out.putpixel((x,y),(int(rgb[0]), int(rgb[1]), int(rgb[2])))

out.save('bar.png')

最佳答案

您放置了R,G,B,因此您必须在

中使用'RGB'而不是'I'
out = Image.new('RGB', im.size, 0xffffff)

对于I,你必须输入int(cd)

out.putpixel((x, y), int(cd))

因为它需要 32 位值而不是 3x8 位值

文档:Modes

关于python - PIL putpixels函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57829738/

相关文章:

python - 重复 numpy 操作的预期行为

python-3.x - 将频谱图存储为Python中的图像

python.pil : command not found

Python OpenCV 视频格式浏览器播放

python - Cython numpy 数组索引器速度改进

python - 如何在Mac上通过anaconda安装openCV?

python - 如何定义一个函数作为包入口点?

python - Kivy中如何通过函数实现到新Screen的转换?

python - BeautifulSoup 抓取无输出

python - pycurl 在异常后恢复