TypeError:不支持的操作数类型 - :' tuple'和'元组'

时间:2016-05-24 12:01:26

标签: python python-imaging-library

我尝试使用Moravec检测。当我尝试运行此代码时,我收到一些错误:

     diff = diff - image.getpixel((x, y))
TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

我该如何解决?任何帮助将不胜感激。代码是:

def moravec(image, threshold = 100):
    """Moravec's corner detection for each pixel of the image."""

    corners = []
    xy_shifts = [(1, 0), (1, 1), (0, 1), (-1, 1)]

    for y in range(1, image.size[1]-1):
        for x in range(1, image.size[0]-1):
            # Look for local maxima in min(E) above threshold:
            E = 100000
            for shift in xy_shifts:
                diff = image.getpixel((x + shift[0], y + shift[1]))
                diff = diff - image.getpixel((x, y))
                diff = diff * diff
                if diff < E:
                    E = diff
            if E > threshold:
                corners.append((x, y))

    return corners

if __name__ == "__main__":
        threshold = 100

        image = Image.open('all.jpg')
        corners = moravec(image, threshold)
        draw_corners(image, corners)
        image.save('low2.png')

1 个答案:

答案 0 :(得分:4)

您尝试减去两个元组(使用RGB值),并且未定义*-等元组的算术运算。

要找到距离,您可以这样做:

c1 = image.getpixel((x + shift[0], y + shift[1]))
c2 = image.getpixel((x, y))
diff = (c1[0] - c2[0]) ** 2 + (c1[1] - c2[1]) ** 2 + (c1[2] - c2[2]) ** 2
if diff < E:
    E = diff

假设你已经习惯了这一点,假设也可以使用numpy让点积和算术运算开箱即用,虽然这有点过分:

import numpy as np

c1 = image.getpixel((x + shift[0], y + shift[1]))
c2 = image.getpixel((x, y))
diff = (np.diff([c1, c2]) ** 2).sum()
if diff < E:
    E = diff