yarin Cohen
yarin Cohen

Reputation: 1142

function takes exactly 1 argument (3 given)?

i am trying to change the value of a pixel in an image to the closest value i have in my list, and i cant figure out why i cant change the pixel value.

I've tried converting the image to RGB or RGBA and for some reason sometimes it takes 3 arguments sometime 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')

I keep getting this error even tho closest_value returns one argument and i dont know why, thnk you for your help!

COLORS - is a list of colors, i've tested the closest_color() function and it works good 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!

Apperantly the code is working for most of the images but not for all of them, for exmaple this image doesn't work and i get this error enter image description here

Upvotes: 3

Views: 6972

Answers (1)

Stop harming Monica
Stop harming Monica

Reputation: 12618

You are being inconsistent by reading the pixels from the RGBA converted image but setting the pixels in the original maybe-not-RGBA image. Fixing that makes your code work with the sample image.

pix = rgb_im.load()

Upvotes: 3

Related Questions