我正在尝试将图像中的像素值更改为列表中最接近的值,并且我无法弄清楚为什么我不能更改像素值。
我尝试将图像转换为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)'
编辑!
答案 0 :(得分:2)
通过从RGBA转换后的图像中读取像素,但在原始的可能不是RGBA图像中设置像素,您会感到不一致。该修复程序使您的代码可以处理示例图像。
pix = rgb_im.load()