首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python JSON对象必须是str,而不是'tuple‘

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

Stack Overflow用户
提问于 2019-03-20 16:43:17
回答 1查看 540关注 0票数 1

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

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

我已从ALPR打印了来文,并收到以下信息:

(B‘高原0: 10结果\n-SBG98 984\t置信度: 85.7017\n -SBG98 98\t置信度: 83.3453\n - S8G984\t信任: 78.3329\n -5BG 984\t置信度: 76.6761\n - S8G98\t置信度: 75.9766\n -SBG98 984\t置信度: 75.5532\n -5BG 98\t置信度: 74.3198\n -SG984信任: 73.3743\nSDG98 98\t置信度: 73.1969\n -BG984 984\t置信度: 71.7671\n‘(无)

我想知道我是如何让代码读懂并分解它的?我从我在网上找到的另一个例子中拿出了下面的代码,它对它们有效,所以我不知道我做错了什么。我已经把我的密码附在下面。

代码语言:javascript
复制
# 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的方法,我会收到以下错误:

线程线程-1中的异常:回溯(最近一次调用): 文件“/usr/lib/python3.5/tening.py”,第914行,在_bootstrap_inner self.run() self.run“/usr/lib/python3.5/tening.py”中,第862行,在run self._target(*self._args,**self._kwargs)文件self._target第563行中在start_stream self.stream_handler(msg_data)文件"camera.py“中,第96行,在stream_handler Take_an_Image()中;文件"camera.py",第29行,在Take_an_Image read_plate() File“camera.py”中,第50行,在read_plate alpr_json中,alpr_error = alpr_json_results() File“camera.py”中,第36行,在alpr_json_results elif中“没有找到盘子”。在alpr_out: TypeError中:需要一个类似字节的对象,而不是'str‘

更新:

修正字节问题后,在“找不到牌照”之前加上b。我现在收到以下错误:

线程线程-1中的异常:回溯(最近一次调用): 文件“/usr/lib/python3.5/tening.py”,第914行,在_bootstrap_inner self.run() self.run“/usr/lib/python3.5/tening.py”中,第862行,在run self._target(*self._args,**self._kwargs)文件self._target第563行中在start_stream self.stream_handler(msg_data)文件"camera.py“中,第96行,在stream_handler Take_an_Image()中;文件"camera.py",第29行,在Take_an_Image read_plate() File“camera.py”中,第52行,在read_plate alpr_json中,alpr_error = alpr_json_results() File "camera.py",第46行,在alpr_json_results Re返回json.loads(Alpr_out)中,None File json.loads(alpr_out),None File json.loads第312行,在loads s.class.name)) TypeError中: JSON对象必须是str,而不是‘字节’

EN

回答 1

Stack Overflow用户

发布于 2019-03-20 16:50:59

我无法复制你所得到的数据,但只要我试着用你给出的输出结果,我就可以得出这样的结论,从你正在分析的对象中得到盘子和信心:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55266011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档