我有这个代码:
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)
我的输出,其中包含错误:
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)],
...
}
我在做什么错了?
答案 0 :(得分:1)
您已经用template
对象覆盖了cv2
变量。
使用:
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)
答案 1 :(得分:1)
在字典IAsyncResult result = cmd.BeginExecuteNonQuery();
while (!result.IsCompleted)
{
// Wait till the command executes
Console.WriteLine("Waiting for query execution");
}
Console.WriteLine("Command complete. Affected {0} rows.", cmd.EndExecuteNonQuery(result));
中,您应该使用可哈希键。当您分配变量toDetectSpeedFrom
时,结果可能不可散列。尝试将某些字符串或其他可哈希类型设置为键。例如:
template = cv2.imread(path, 0)