首页 > 解决方案 > 连接字符串而不是字节

问题描述

我试图将我的 IP 摄像头链接到我的 AWS 服务,我有两种方法可以做到这一点,或者使用我的内置计算机摄像头(运行良好)和一个 IP 摄像头。我使用的代码来自https://github.com /aws-samples/amazon-rekognition-video-analyzer使用 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()

标签: python-3.xstringbyte

解决方案


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

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


推荐阅读