【问题标题】:Concatenating strings not bytes连接字符串而不是字节
【发布时间】:2019-08-27 19:36:46
【问题描述】:

我试图将我的 IP 摄像头链接到我的 AWS 服务,我有两种方法可以做到这一点,或者使用我的内置计算机摄像头(运行良好)和一个 IP 摄像头。我使用的代码来自 https://github.com/aws-samples/amazon-rekognition-video-analyzer wich正在用 python 2.7 编写(但我是在 python 3 中编写的),我已经将代码转换为 python 3(使用 python 2to3)。但是当我运行代码时,我不断收到 only concatenate strings not bytes:

我是 python 新手,所以我的研究是 2to3 将完成这项工作,但我很确定将字节转换为字符串的这部分不存在,我不确定如何处理此转换/解析。

Traceback (most recent call last):
  File "video_cap_ipcam.py", line 140, in <module>
    main()
  File "video_cap_ipcam.py", line 104, in main
    bytes += stream.read(16384*2)
TypeError: can only concatenate str (not "bytes") to str

video_cap_ipcam.py 文件:

def main():

    ip_cam_url = ''
    capture_rate = default_capture_rate
    argv_len = len(sys.argv)

    if argv_len > 1:
        ip_cam_url = sys.argv[1]

        if argv_len > 2 and sys.argv[2].isdigit():
            capture_rate = int(sys.argv[2])
    else:
        print("usage: video_cap_ipcam.py <ip-cam-url> [capture-rate]")
        return

    print(("Capturing from '{}' at a rate of 1 every {} frames...".format(ip_cam_url, capture_rate)))
    stream = urllib.request.urlopen(ip_cam_url)

    bytes = ''
    pool = Pool(processes=3)

    frame_count = 0
    while True:
        # Capture frame-by-frame
        frame_jpg = ''

        bytes += stream.read(16384*2)
        b = bytes.rfind('\xff\xd9')
        a = bytes.rfind('\xff\xd8', 0, b-1)


        if a != -1 and b != -1:
            #print 'Found JPEG markers. Start {}, End {}'.format(a,b)

            frame_jpg_bytes = bytes[a:b+2]
            bytes = bytes[b+2:]

            if frame_count % capture_rate == 0:


                img_cv2_mat = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
                rotated_img = cv2.transpose(cv2.flip(img_cv2_mat, 0))


                retval, new_frame_jpg_bytes = cv2.imencode(".jpg", rotated_img)

                #Send to Kinesis
                result = pool.apply_async(send_jpg, (bytearray(new_frame_jpg_bytes), frame_count, True, False, False,))

            frame_count += 1

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python-3.x string byte


    【解决方案1】:

    当您最初将变量bytes 设置为'' 时,该变量变成了一个字符串,在Python 3 中它被认为是一个字符 序列而不是一个字节序列。 (一个字符可以用多个字节表示。)

    如果您希望bytes 是一个字节序列,请将其初始化为b''。然后您可以将更多字节连接到它。

    【讨论】:

    • 您能否详细解释一下,我已经将其初始化为 '''b ' ' ''' 并引发语法错误
    • b'' 之间不应该有空格。
    • 另外,“''”中的每个“'”之间不应该有空格,因为它应该是一个空字符串。
    • 谢谢,它开始变得有意义,但是对于切片表示法是否可行? rame_jpg_bytes = bytes[a:b+2]我已经试过了frame_jpg_bytes =[a:b+2].encode()
    • 切片符号适用于字节序列。 [a:b+2].encode() 有两个问题。第一个是你在“[”前面少了一个变量名,第二个是字节序列没有encode()方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多