连接字符串而不是字节

时间:2019-08-27 19:36:46

标签: python-3.x string byte

im尝试将我的IP摄像机链接到我的AWS服务,并且有两种方法可以实现此目的,即使用我的内置计算机摄像机(运行良好)和一个IP摄像机。我使用的代码来自{{3} } wich正在用python 2.7编写(但是我在python 3中做到了),我已经将代码转换为python 3(使用python 2to3)。但是当我运行代码时,我不断收到此错误,只能连接字符串而不是字节

我是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()

1 个答案:

答案 0 :(得分:1)

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

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