0

I have this code:

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)

I have the picture to detect the template from (You can see the speed in the downer right corner):Train

I have these templates: FiletreeOfTrainimgs

My output which contains the 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'

So you can see when I print(pt, (pt[0] + w, pt[1] + h)) it gives (5, 3) (13, 15). Why can't I append it to a dictionary?

Expected dictionary:

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

What am I doing wrong?

I'm the man.
  • 207
  • 2
  • 13

2 Answers2

1

You have overwritten the template variable with cv2 object.

Use:

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)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

In the dict toDetectSpeedFrom you should use hashable keys. When you assign the variable template = cv2.imread(path, 0) the result is probably not hashable. Try to set some string or other hashable type as a key. For example:

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

See also What does "hashable" mean in Python?

Yann
  • 2,426
  • 1
  • 16
  • 33