逐帧下载MJPEG流

时间:2018-12-07 12:51:45

标签: python python-3.x python-requests mjpeg

我已经设置了一个IP摄像机,并且可以浏览到其IP并获取MJPEG流,我试图逐帧下载它,以便可以在另一台服务器上分析图像。但是我在阅读流时遇到了麻烦。我的代码是:

import cv2
import urllib.request
import numpy as np
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE       

stream = urllib.request.urlopen('https://x.x.x.x:8602/Interface/Cameras/GetJPEGStream?Camera=Bosch%20NBE6502AL%20Bullet&ResponseFormat=XML&AuthUser=username&AuthPass=password',context=ctx)
bytes = ''
while True:
    bytes += stream.read(1024)
    a = bytes.find('\xff\xd8')
    b = bytes.find('\xff\xd9')
    if a != -1 and b != -1:
        jpg = bytes[a:b+2]
        bytes = bytes[b+2:]
        i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_COLOR)
        cv2.imshow('i', i)
        if cv2.waitKey(1) == 27:
            exit(0)  

它给我以下错误:

Traceback (most recent call last):
File "mjpeg.py", line 15, in <module>
bytes += stream.read(1024)
TypeError: can only concatenate str (not "bytes") to str

我认为流输出字符串,但是如何将流转换为字节并保存文件呢?

亲切的问候,

艾伦斯

3 个答案:

答案 0 :(得分:0)

您需要始终bytes,所以将bytes(作为内建类型的名称也是最好的名称)初始化为字节串,然后使用字节文字以查找开始/结束标记:

bytes = b''
while True:
    bytes += stream.read(1024)
    a = bytes.find(b'\xff\xd8')
    b = bytes.find(b'\xff\xd9')
    if a != -1 and b != -1:
        # ...

答案 1 :(得分:0)

初始化后(字节=”),而不是(字节= b ''),您的字节变量为str,请更改

stream = urllib.request.urlopen('https://x.x.x.x:8602/Interface/Cameras/GetJPEGStream?Camera=Bosch%20NBE6502AL%20Bullet&ResponseFormat=XML&AuthUser=username&AuthPass=password',context=ctx)
bytes = ''
while True:

对此

stream = urllib.request.urlopen('https://x.x.x.x:8602/Interface/Cameras/GetJPEGStream?Camera=Bosch%20NBE6502AL%20Bullet&ResponseFormat=XML&AuthUser=username&AuthPass=password',context=ctx)
bytes = b''
while True:

您可以像这样检查自己

>>> type('') == type(b'')
False
>>> type(''),type(b'')
(<class 'str'>, <class 'bytes'>)

答案 2 :(得分:0)

concatenation仅适用于

相同类型的值
string with a string str += str
bytes with a bytes bytes += bytes 

因此将您的bytes变量设置为bytes = b''。希望一切正常。

import cv2
import urllib.request
import numpy as np
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE       

stream = urllib.request.urlopen('https://x.x.x.x:8602/Interface/Cameras/GetJPEGStream?Camera=Bosch%20NBE6502AL%20Bullet&ResponseFormat=XML&AuthUser=username&AuthPass=password',context=ctx)
bytes = b''# MAKE IT BYTES
while True:
    bytes += stream.read(1024)
    a = bytes.find('\xff\xd8')
    b = bytes.find('\xff\xd9')
    if a != -1 and b != -1:
        jpg = bytes[a:b+2]
        bytes = bytes[b+2:]
        i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_COLOR)
        cv2.imshow('i', i)
        if cv2.waitKey(1) == 27:
            exit(0)
相关问题