Python 3.x - TypeError: unhashable type: 'numpy.ndarray'

Python 3.x - TypeError: unhashable type: 'numpy.ndarray'

我有这个代码:

templates = {
    '1.png': 0.7,
    '2.png': 0.7,
    '4.png': 0.7,
}

img_rgb = cv2.imread('mta-screen_2020-01-01_12-07-24.png')
img_speed = img_rgb[983:1000, 1464:1510]
cv2.imwrite('cropped.png', img_speed)
img_speed_gray = cv2.cvtColor(img_speed, cv2.COLOR_BGR2GRAY)
toDetectSpeedFrom = {}
for template in templates:
    print(template, templates[template])
    path = 'D:\!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton\MTA_pyautogui\TrainImgs' + chr(92) + template
    template = cv2.imread(path, 0)
    w, h = template.shape[::-1]
    res = cv2.matchTemplate(img_speed_gray, template, cv2.TM_CCOEFF_NORMED)
    threshold = 0.7  # float(templates[template])
    loc = nm.where(res >= threshold)
    for pt in zip(*loc[::-1]):
        print(pt, (pt[0] + w, pt[1] + h))
        toDetectSpeedFrom[template] = ([pt, (pt[0] + w, pt[1] + h)])
        cv2.rectangle(img_speed, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 1)
    cv2.imwrite('res.png', img_speed)

print(toDetectSpeedFrom)

我有检测模板的图片(你可以在右下角看到速度):

我有这些模板

我的 output 包含 error:

1.png 0.7
Traceback (most recent call last):
(5, 3) (13, 15)
  File "D:/!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton/MTA_pyautogui/main.py", line 63, in <module>
    toDetectSpeedFrom[template] = ([pt, (pt[0] + w, pt[1] + h)])
TypeError: unhashable type: 'numpy.ndarray'

所以你可以看到当我 print(pt, (pt[0] + w, pt[1] + h)) 它给出了 (5, 3) (13, 15)。为什么我不能将它附加到字典中?

预期字典:

toDetectSpeedFrom = {
    '1.png': [pt, (pt[0] + w, pt[1] + h)],
     ...
}

我做错了什么?

您已经用 cv2 对象覆盖了 template 变量。

使用:

for template in templates:
    print(template, templates[template])
    path = 'D:\!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton\MTA_pyautogui\TrainImgs' + chr(92) + template
    template_obj = cv2.imread(path, 0)  #Changed variable name!!!
    w, h = template_obj.shape[::-1]
    res = cv2.matchTemplate(img_speed_gray, template_obj, cv2.TM_CCOEFF_NORMED)
    threshold = 0.7  # float(templates[template])
    loc = nm.where(res >= threshold)
    for pt in zip(*loc[::-1]):
        print(pt, (pt[0] + w, pt[1] + h))
        toDetectSpeedFrom[template] = ([pt, (pt[0] + w, pt[1] + h)])
        cv2.rectangle(img_speed, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 1)
    cv2.imwrite('res.png', img_speed)

在字典 toDetectSpeedFrom 中,您应该使用可散列的键。当您分配变量 template = cv2.imread(path, 0) 时,结果可能不可散列。尝试将一些字符串或其他可散列类型设置为键。例如:

toDetectSpeedFrom[path] = ([pt, (pt[0] + w, pt[1] + h)])

另见 What does "hashable" mean in Python?