2017-05-30 36 views
0

我想比较两张图像并保存差异图像,其中差异标记为红色。 不幸的是我得到以下错误:Python图像库:无法访问像素值

Traceback (most recent call last): 
    File "pythontest.py", line 216, in <module> 
    nDiff = compare(sPathCur, sPathRef, sPathDif) 
    File "pythontest.py", line 88, in compare 
    pix_diff[y, x] = (255, 0, 0) 
TypeError: function takes exactly 1 argument (3 given) 
def compare(sPathCur, sPathRef, sPathDif): 
    im_cur = Image.open(sPathCur) 
    im_ref = Image.open(sPathRef) 

    im_dif = im_cur.convert('L') # convert image to grey scale 

    delta = ImageChops.difference(im_cur, im_ref) 
    width, height = delta.size 

    pix_delta = delta.load() 
    pix_diff = im_dif.load() 

    for y in range(width): 
     for x in range(height): 
      r, g, b = pix_delta[y, x] 
      if (r > 0 or g > 0 or b > 0): 
       pix_diff[y, x] = (255, 0, 0) 

    im_dif.save(sPathDif) 
+0

“putpixel”方法的[docs](http://www.effbot.org/imagingbook/image.htm#tag-Image.Image.putpixel)表示:“颜色以单个数值给出,带图像,以及用于多波段图像的元组“。难道你需要将元组转换为单个值吗? – phd

回答

1

一旦完成转换为灰度图像,每个像素被分配一个值,而不是一个RGB三元组。

http://effbot.org/imagingbook/image.htm摘自:

When converting from a colour image to black and white, the library uses the ITU-R 601-2 luma transform:

L = R * 299/1000 + G * 587/1000 + B * 114/1000 

因此,如果你在像素[X,Y] = [0,0]具有(R,G,B)的值(100150200),然后转换为灰度后,它将包含单个值140.75(然后将四舍五入为整数)

您可以通过在嵌套循环之前检查pix_diff [0,0]的值来验证该值。它应该只返回一个值。

所以,你要么需要在你的pix_diff [Y,X]分配一个灰度值到每个像素,或者将您的pix_diff图像回的RGB兼容的格式,然后才能分配给每个像素您的(255, 0, 0)