【问题标题】:TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple' [duplicate]TypeError:不支持的操作数类型 -:“元组”和“元组”[重复]
【发布时间】:2016-09-21 15:09:51
【问题描述】:

我尝试使用 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')

【问题讨论】:

  • 你不能直接从另一个元组中减去一个元组。查看替代方案here

标签: python python-imaging-library


【解决方案1】:

您正在尝试减去两个元组(具有 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

【讨论】:

  • 感谢您的详细解答! :))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2011-03-08
相关资源
最近更新 更多