Python图像库:无法访问像素值

2024-09-30 10:35:36 发布

您现在位置: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)

Tags: in图像diff差异filecomparedeltacur
1条回答
网友
1楼 · 发布于 2024-09-30 10:35:36

执行到灰度图像的转换后,每个像素将被指定一个值,而不是一个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\u diff[y,x]中的每个像素指定一个灰度值,或者将pix\u diff图像转换回与RGB兼容的格式,然后才能为每个像素指定值(255, 0, 0)

相关问题 更多 >

    热门问题