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

问题描述 投票:1回答:1

我的代码崩溃,出现以下错误:

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)

更新:

尝试使用Denis的方法时,我收到以下错误:

线程中的异常Thread-1:Traceback(最近一次调用最后一次): 文件“/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)在stream_handler文件“camera.py”,第96行,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中:TypeError:需要一个类似字节的对象,而不是'str'

更新:

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

线程中的异常Thread-1:Traceback(最近一次调用最后一次): 文件“/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)在stream_handler文件“camera.py”,第96行,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.5/json/init.py”,第312行,在加载s.class.name中)TypeError:JSON对象必须是str,而不是'bytes'

python arrays json alpr
1个回答
0
投票

我无法重现你得到的数据,但是尽管我尝试使用你给出的输出,但我可以得出这个结论来获得你正在分析的对象的板块和信心:

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
© www.soinside.com 2019 - 2024. All rights reserved.