尝试从http地址将视频流式传输到opencv

时间:2018-03-22 00:22:51

标签: python http opencv raspberry-pi video-streaming

我对此比较陌生,但这就是我要做的事情。我有一个覆盆子零连接到覆盆子pi相机,我通过uv4l无线传输来自覆盆子pi的视频。我用这个命令:

sudo uv4l -f -k --sched-fifo --mem-lock --driver raspicam --auto-video_nr --encoding h264 --width 1080 --height 720 --enable-server on

我可以通过查看pi的ip地址在Web浏览器上访问此流。现在我想做的是能够在opencv中查看视频流。这是我读过的作品,但是我遇到了以下错误:

Streaming http://192.168.1.84:8080/stream
Traceback (most recent call last):
  File "videoStream.py", line 17, in <module>
    bytes+=stream.read('1024')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 448, in read
    b = bytearray(amt)
TypeError: string argument without an encoding

这是我的代码。注意我正在运行python 3.5和opencv 3:

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

host = "192.168.1.84:8080"
if len(sys.argv)>1:
    host = sys.argv[1]

hoststr = 'http://' + host + '/stream'
print('Streaming ' + hoststr)

stream=urllib.request.urlopen(hoststr)

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(hoststr,i)
        if cv2.waitKey(1) ==27:
            exit(0)

我不确定如何解决此问题,或者是否有更好的方法可以在opencv中查看此视频流。

3 个答案:

答案 0 :(得分:1)

尝试一下。更改

bytes=''
while True:
    bytes+=stream.read('1024')
    a = bytes.find('\xff\xd8')
    b = bytes.find('\xff\xd9')

bytes=b''
while True:
    bytes+=stream.read(1024)
    a = bytes.find(b'\xff\xd8')
    b = bytes.find(b'\xff\xd9')

并使用

i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)

这在python 3.5 cv2 4.0.0版本中对我有用

答案 1 :(得分:0)

我无法验证您的代码,因为我没有与我进行流媒体设置。但首先,我认为stream.read('1024')应为stream.read(1024)1024是缓冲区的大小(以字节为单位),而不是1024的字符串。

其次,urllib.request.openurl().read()会返回一个字节对象,因此,当np.fromstring(jpg, dtype=np.uint8)期待np.fromstring作为字符串时,您的代码可能会遇到解码问题jpg ,但jpg的类型是一个字节。您需要将其转换为如下字符串:

np.fromstring(jpg.decode('utf-8'), dtype=np.uint8)

答案 2 :(得分:0)

只需替换

bytes=''

bytes=bytearray()

bytes+=stream.read('1024')

bytes+=bytearray(stream.read(1024))
相关问题