【问题标题】:Python: can't print different JSON response from APIPython:无法从 API 打印不同的 JSON 响应
【发布时间】:2020-06-22 07:51:35
【问题描述】:

我编写了简单的 python 脚本来读取图像中车牌中的字母和数字,为了读取车牌,我会将其发送到图像识别 API,他们会发回我使用的 JSON 响应。

这是完整的代码:

import glob
import requests
import json
import time
import os
import cv2
import numpy as np

def main():
    result = []
    regions = ['id']
    time_to_wait = np.inf
    time_counter = 0

    while True:
        files = glob.glob(os.path.join("./path_to_imagedir/*.jpg"))
        files.sort(key=os.path.getmtime)
        for file in files:
            if os.path.isfile(file):
                with open(file, 'rb') as fp:
                    response = requests.post(
                        'https://MY_API/',
                        data=dict(regions=regions),
                        files=dict(upload=fp),
                        headers={'Authorization': 'Token ' + 'XXX'})
                    result.append(response.json())
                    resp_dict = json.loads(json.dumps(result, indent=2))
                    if resp_dict[0]['results']:
                        num = resp_dict[0]['results'][0]['plate']
                        print(f"detected number:  {num}")
                    os.remove(file)

        time.sleep(1)
        time_counter += 1
        if time_counter > time_to_wait: break
        print("waiting for file... ")

if __name__ == '__main__':
    main()

当我运行这段代码时,它会在终端上显示如下响应:

waiting for file... 
waiting for file... 
waiting for file... 
detected number:  b1962ub
waiting for file... 
waiting for file... 
waiting for file... 
waiting for file... 
detected number:  b1962ub
waiting for file... 
waiting for file... 
waiting for file... 
waiting for file...

我认为它工作正常,但问题是为什么detected number 在不同的图像上打印相同的数字和不同的数字?我不知道这是怎么回事。

任何帮助都将得到重视! 谢谢你

【问题讨论】:

  • 您需要在循环内清除 results=[],而不是在循环外,否则您会将新结果附加到列表中,但仅在 [0] 处显示第一个结果
  • 如何清除results=[ ]
  • 是的,将results=[] 放入您的for file in files 块中。
  • 是的,结果与stackoverflow.com/a/62509874/8361239 答案相同,它不适用于文件中的多个图像。如何做到这一点?
  • 您是否要在一个 JPEG 文件中分离多个图像?我对图形文件格式了解不多,不知道它们是否自然地在内部支持多个图像,或者您必须使用图像处理软件将它们以数字方式分割。

标签: python json loops response


【解决方案1】:

您一直在附加到您的results,但您总是查看resp_dict[0],所以您总是查看相同的项目。而是查看resp_dict[-1],这样您将查看最新项目

这样:

if resp_dict[0]['results']:
                        num = resp_dict[0]['results'][0]['plate']
                        print(f"detected number:  {num}")

应该是这样的:

if resp_dict[-1]['results']:
                        num = resp_dict[-1]['results'][0]['plate']
                        print(f"detected number:  {num}")

【讨论】:

  • 啊,我明白了,它只适用于一个图像输入,但不适用于多个输入
  • 并不是说它不起作用,只是您阅读了您尝试的第一个而不是您尝试的最后一个的响应
  • 如何使其适用于多个输入? @Nullman
  • 你是什么意思?多个输入在哪里?
  • 对不起,我的意思是如何使它适用于文件夹中的许多图像? @Nullman
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 2019-09-19
  • 2022-01-12
  • 1970-01-01
  • 2017-11-05
相关资源
最近更新 更多