首页 > 解决方案 > Python JSON 对象必须是 str,而不是“元组”

问题描述

我的代码因以下错误而崩溃:

TypeError:JSON 对象必须是 str,而不是 'tuple'

我已经打印了来自 ALPR 的通讯并收到以下信息:

(b'plate0:10 个结果\n - SBG984\t 置信度:85.7017\n - SBG98\t 置信度:83.3453\n - S8G984\t 置信度:78.3329\n - 5BG984\t 置信度:76.6761\n - S8G98\t 置信度: 75.9766\n - SDG984\t 置信度:75.5532\n - 5BG98\t 置信度:74.3198\n - SG984\t 置信度:73.3743\n - SDG98\t 置信度:73.1969\n - BG984\t 置信度:71.7671\n' , 没有任何)

我想知道如何让代码阅读并分解它?我从网上找到的另一个示例中获取了以下代码,它适用于他们,所以我不确定我做错了什么。我在下面附上了我的代码。

# Setting up Pyrebase config below
config = {

}

camera = PiCamera()
global alpr_command_args

def Take_an_Image():
    global alpr_command_args
    camera.start_preview()
    sleep(5)
    camera.capture('picture.jpg')
    camera.stop_preview()

    #alpr subprocess args
    alpr_command = "alpr -c gb pictureold.jpg"
    alpr_command_args = shlex.split(alpr_command)
    read_plate()

def alpr_subprocess():
    global alpr_command_args
    return subprocess.Popen(alpr_command_args, stdout=subprocess.PIPE)

def alpr_json_results():
    alpr_out, alpr_error = alpr_subprocess().communicate()

    if not alpr_error is None:
        return None, alpr_error
    elif b"No license plates found." in alpr_out:
        return None, None

    try:
        return json.loads(alpr_out), None
    except (ValueError) as e:
        return None, e


def read_plate():
    alpr_json, alpr_error = alpr_json_results()
    if not alpr_error is None:
        print (alpr_error)
        return
    if alpr_json is None:
        print ("No results!")
        return
    results = alpr_json["results"]
    print(results)
    ordinal = 0
    for result in results:
        candidates = result["candidates"]
        for candidate in candidates:
            if candidate["matches_template"] == 1:
                ordinal += 1
                print ("PLATE " + candidate["plate"] + candidate["confidence"])


firebase = pyrebase.initialize_app(config)
db = firebase.database()

# Setting initial values to Firebase Database on startup
data = {
    "CAMERA": "OFF",
}

# Setting default values on Pi

results = db.update(data)

# This is the handler when Firebase database changes
def stream_handler(message):
    path = str(message["path"]) # This is what sensor changes, e.g path returns /LED
    status = str(message["data"]) # This is what the sensor says, e.g /LED says "ON"
    # Getting global values
    if path =="/CAMERA":
        if status == "ON":
            print("**TAKE PIC**")
            data = {
                "CAMERA": "OFF",
            }
            results = db.update(data)
            Take_an_Image();

# Starting stream for Firebase
my_stream = db.stream(stream_handler)

更新:

通过尝试丹尼斯的方法,我收到以下错误:

线程 Thread-1 中的异常:回溯(最后一次调用):
文件“/usr/lib/python3.5/threading.py”,第 914 行,在 _bootstrap_inner self.run() 文件“/usr/lib/python3. 5/threading.py”,第 862 行,在运行 self._target(*self._args, **self._kwargs) 文件“/home/pi/.local/lib/python3.5/site-packages/pyrebase/pyrebase .py”,第 563 行,在 start_stream self.stream_handler(msg_data) 文件“camera.py”,第 96 行,在 stream_handler Take_an_Image();文件“camera.py”,第 29 行,在 Take_an_Image 中 read_plate() 文件“camera.py”,第 50 行,在 read_plate alpr_json,alpr_error = alpr_json_results() 文件“camera.py”,第 36 行,在 alpr_json_results elif “没有板成立。” 在 alpr_out:类型错误:

更新:

通过在“未找到车牌”之前添加 ab 来修复字节问题后。我现在收到以下错误:

线程 Thread-1 中的异常:回溯(最后一次调用):
文件“/usr/lib/python3.5/threading.py”,第 914 行,在 _bootstrap_inner self.run() 文件“/usr/lib/python3. 5/threading.py”,第 862 行,在运行 self._target(*self._args, **self._kwargs) 文件“/home/pi/.local/lib/python3.5/site-packages/pyrebase/pyrebase .py”,第 563 行,在 start_stream self.stream_handler(msg_data) 文件“camera.py”,第 96 行,在 stream_handler Take_an_Image();文件“camera.py”,第 29 行,在 Take_an_Image read_plate() 文件“camera.py”,第 52 行,在 read_plate alpr_json,alpr_error = alpr_json_results() 文件“camera.py”,第 46 行,在 alpr_json_results 返回 json.loads (alpr_out),无文件“/usr/lib/python3.. name )) TypeError:JSON 对象必须是 str,而不是 'bytes'

标签: pythonarraysjsonalpr

解决方案


我无法重现您获得的数据,但是尽管我尝试了您提供的输出,但我可以得出这个结论,以从您正在分析的对象中获得盘子和置信度:

import json

alpr_example = b'plate0: 10 results\n - SBG984\t confidence: 85.7017\n - SBG98\t confidence: 83.3453\n - S8G984\t confidence: 78.3329\n - 5BG984\t confidence: 76.6761\n - S8G98\t confidence: 75.9766\n - SDG984\t confidence: 75.5532\n - 5BG98\t confidence: 74.3198\n - SG984\t confidence: 73.3743\n - SDG98\t confidence: 73.1969\n - BG984\t confidence: 71.7671\n', None

def alpr_json_results():
    alpr_out, alpr_error = alpr_example

    if not alpr_error is None:
        return None, alpr_error
    elif b"No license plates found." in alpr_out:
        return None, None

    try:
        decoded = alpr_out.decode('utf-8')
        decoded = decoded.replace('-', 'plate:')
        decoded = decoded[19:]
        decoded = decoded.replace('plate:', ',plate:')
        decoded = decoded.replace('confidence:', ',confidence:')
        decoded = decoded.split(',')
        decoded.pop(0)
        plateList=[]
        confidenceList=[]
        for i, item in enumerate(decoded):
            if (i%2 == 0):
                print(item.replace('plate: ',''))
            else:
                print(item.replace('confidence: ',''))

        return plateList, confidenceList
    except (ValueError) as e:
        return None, e

alpr_json_results()

#SBG984  
#85.7017
# 
#SBG98   
#83.3453
# 
#S8G984  
#78.3329
# 
#5BG984  
#76.6761
# 
#S8G98   
#75.9766
# 
#SDG984  
#75.5532
# 
#5BG98   
#74.3198
# 
#SG984   
#73.3743
# 
#SDG98   
#73.1969
# 
#BG984   
#71.7671

推荐阅读