【发布时间】:2020-04-20 04:30:12
【问题描述】:
我只是尝试使用 platerecognizer.com API 来检测矩形框并识别框内的每个字符(车牌)。但 API 无法读取视频文件,它们只是接收 jpeg/jpg 文件然后生成 JSON。所以我将每一帧的视频分割并发送到 API,我已经完成了。
我有这个代码:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import argparse
import requests
from PIL import Image
import json
import time
import math
import cv2
import os
import json
def main():
cap = cv2.VideoCapture("assets/car-number-plate.mp4")
frameRate = cap.get(5)
print(frameRate)
seconds=2
multiplier=frameRate*seconds
x=1
while (cap.isOpened()):
frameId = int(round(cap.get(1)))
print(frameId)
ret, frame = cap.read()
if (ret != True):
break
result = []
if (frameId % multiplier == 0):
filename = 'output_frame/frameId' + str(int(x)) + ".jpg"
cv2.imwrite(filename, frame)
time.sleep(1)
path = "/home/mycomputer/Documents/platerecognizer-test/%s" % filename
with open(path, 'rb') as fp:
response = requests.post(
'https://api.platerecognizer.com/v1/plate-reader/',
files=dict(upload=fp),
headers={'Authorization': 'Token ' + 'MY_API_KEY'})
result.append(response.json())
print(json.dumps(result, indent=2));
with open('data.json', 'w') as outfile:
json.dump(result, outfile)
os.remove("%s" %filename)
x+=1
time.sleep(1)
resp_dict = json.loads(json.dumps(result, indent=2))
num=resp_dict[0]['results'][0]['plate']
boxs=resp_dict[0]['results'][0]['box']
xmins,ymins,ymaxs,xmaxs=boxs['xmin'],boxs['ymin'],boxs['ymax'],boxs['xmax']
cv2.rectangle(frame, (xmins, ymins), (xmaxs, ymaxs), (0, 255, 0), 2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame,num,(xmins, ymins-10), font, 1,(0, 255, 0),2,cv2.LINE_AA)
cv2.imshow("plat nomor yang terdeteksi",frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(f"mobil dengan plat nomor: {num}")
cap.release()
if __name__ == '__main__':
main()
上面的代码是如何工作的?所以,首先我从 dir 加载视频,按帧分割它们,将它们发送到 API,从 API 接收完整(非空)响应 JSON,如下所示:
[
{
"processing_time": 102.465,
"results": [
{
"box": {
"xmin": 537,
"ymin": 346,
"xmax": 657,
"ymax": 407
},
"plate": "b1399ere",
"region": {
"score": 0.876,
"code": "id"
},
"vehicle": {
"score": 0.802,
"box": {
"xmin": 163,
"ymin": 12,
"xmax": 709,
"ymax": 472
},
"type": "Car"
},
"score": 0.898,
"candidates": [
{
"score": 0.898,
"plate": "b1399ere"
},
{
"score": 0.791,
"plate": "bi399ere"
},
{
"score": 0.79,
"plate": "81399ere"
},
{
"score": 0.683,
"plate": "8i399ere"
}
],
"dscore": 0.732
}
],
"filename": "0243_tzJBu_frameId7.jpg",
"version": 1,
"camera_id": null,
"timestamp": "2020-04-20T02:43:34.123444Z"
}
]
当他们从我们之前发送的图像的 json API 中找到结果时,代码运行良好,但是当代码找到 JSON 响应时,结果为空,如下所示:
[
{
"processing_time": 82.204,
"results": [],
"filename": "0243_aKa1u_frameId8.jpg",
"version": 1,
"camera_id": null,
"timestamp": "2020-04-20T02:43:38.881827Z"
}
]
我只是遇到了这个错误:IndexError: list index out of range
如果结果 JSON 为空,我想让这个循环工作,然后返回以重新生成上面捕获的下一个帧,并获得带有完整结果的 JSON 响应。但是,如何循环呢?
谢谢
【问题讨论】:
-
观察到这个错误,只是因为你试图访问一个空列表。由于这是一个循环,只需添加一个条件即可继续 if resp_dict[0]['results'] == []: continue