温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python3如何实现解析mjpeg http流

发布时间:2020-11-16 15:06:33 来源:亿速云 阅读:465 作者:Leah 栏目:开发技术

python3如何实现解析mjpeg http流?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

前言

网络摄像头的视频流解析直接使用通过http的Mjpeg是具有边界帧信息的multipart / x-mixed-replace,而jpeg数据只是以二进制形式发送。因此,实际上不需要关心HTTP协议标头。所有jpeg帧均以marker开头,0xff 0xd8并以结尾0xff 0xd9。因此,上面的代码从http流中提取了此类帧,并将其一一解码。像下面

...(http)
0xff 0xd8   --|
[jpeg data]   |--this part is extracted and decoded
0xff 0xd9   --|
...(http)
0xff 0xd8   --|
[jpeg data]   |--this part is extracted and decoded
0xff 0xd9   --|
...(http)

如果图像的获取是从tcp网络中传输到本地进行解析需要对bytes类型数据进行解码

在使用OpenCV直接调用网络摄像头时可能会出现

Cam not found

这时候就需要下面这种办法

代码: 
帧解析

import cv2
cap = cv2.VideoCapture('http://localhost:8080/frame.mjpg')
 
while True:
 ret, frame = cap.read()
 print(frame)
 if ret == True:
  cv2.imshow('Video', frame)
 
  if cv2.waitKey(1) == 27:
   exit(0)

视频流解析

import cv2
import requests
import numpy as np
 
r = requests.get('http://192.168.1.xx/mjpeg.cgi', auth=('user', 'password'), stream=True)
if(r.status_code == 200):
  bytes = bytes()
  for chunk in r.iter_content(chunk_size=1024):
    bytes += chunk
    a = bytes.find(b'\xff\xd8')
    b = bytes.find(b'\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.IMREAD_COLOR)
      cv2.imshow('i', i)
      if cv2.waitKey(1) == 27:
        exit(0)
else:
  print("Received unexpected status code {}".format(r.status_code))

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI