函数正好接受1个参数(给定3个)?

时间:2019-01-18 11:43:38

标签: python opencv image-processing

我正在尝试将图像中的像素值更改为列表中最接近的值,并且我无法弄清楚为什么我不能更改像素值。

我尝试将图像转换为RGB或RGBA,由于某种原因,有时有时需要4个参数。

im = Image.open('rick.png') # Can be many different formats.
rgb_im = im.convert('RGBA')
pix = im.load()

height, width = im.size
image = ImageGrab.grab()

COLORS = (
(0, 0, 0),
(127, 127, 127),
(136, 0, 21),
(237, 28, 36),
(255, 127, 39),
)
def closest_color(r, g, b, COLORS):
    min_diff = 9999
    answer = None
    for color in COLORS:
        cr, cg, cb = color
        color_diff = abs(r - cr) + abs(g - cg) + abs(b - cb)
        if color_diff < min_diff:
            answer = color
            min_diff = color_diff
    return answer


def read_color(height,width, COLORS, pix):
    for x in range(height):
        for y in range(width):
            r,g,b,a = rgb_im.getpixel((x,y))
            color = closest_color(r, g, b, COLORS) # color is returned as tuple
            pix[x,y] = color # Changing color value? -Here i get the error-



read_color(height,width, COLORS, pix)
im.save('try.png')

即使close_value返回一个参数,我也一直收到此错误,我也不知道为什么,感谢您的帮助!

颜色-是颜色的列表,我已经测试过closest_color()函数,并且效果很好 错误消息:

'Exception has occurred: TypeError
function takes exactly 1 argument (3 given)
File "C:\Users\user\Desktop\תוכנות שעשיתי\program.py", line 133, in 
read_color
pix[x,y] = color
File "C:\Users\user\Desktop\תוכנות שעשיתי\program.py", line 137, in 
<module>
read_color(height,width, COLORS, pix)'

编辑!

显然,该代码适用于大多数图像,但不适用于所有图像,例如,此图像不起作用,并且我收到此错误enter image description here

1 个答案:

答案 0 :(得分:2)

通过从RGBA转换后的图像中读取像素,但在原始的可能不是RGBA图像中设置像素,您会感到不一致。该修复程序使您的代码可以处理示例图像。

pix = rgb_im.load()