Python – function accepts exactly 1 argument (given 3)?

function accepts exactly 1 argument (given 3)?… here is a solution to the problem.

function accepts exactly 1 argument (given 3)?

I’m trying to change the pixel value in

an image to the closest value in the list, but I don’t understand why I can’t change the pixel value.

I tried converting an image to RGB or RGBA, but for some reason sometimes 3 parameters and sometimes 4 parameters.

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')

I keep getting this error even though closest_value returns a parameter, I don’t know why, thanks for your help!

COLORS – is a list of colors that I tested with the closest_color() function and worked just fine
Error message:

'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)'

EDIT!

Obviously, the code works for most images, but not for all images, for example, this image does not work, I get this error enter image description here

Solution

Reading pixels from an RGBA-converted image, but setting pixels in the original, possibly non-RGBA image, is inconsistent. Fix an issue that makes your code work with sample images.

pix = rgb_im.load()

Related Problems and Solutions