Varun Chatterji发布了需要登录名和密码的how to use requests to stream video from an IP(以太网)摄像头。这正是我所需要的,也是唯一适用于我的相机在Windows 7上的python 3.4中。
但是,他的代码中的循环在哪里?当我运行此代码时,它会在cv2窗口中显示视频时无限运行。但是,代码缺少“while True:”语句,我在搜索中找不到任何帮助。我想将循环移动到更高级别的模块,但我不知道循环在哪里。
换句话说,有人可以重构这个代码,所以那里有一个“while True:”行吗?那会让我看到循环中的内容和不循环的内容。我发现请求文档很难遵循。
Varun的参考代码:
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))
这样做的动机是我想将“循环内部”的东西移动到子程序中,称之为ProcessOneVideoFrame(),然后能够放入更大的程序:
while True:
ProcessOneVideoFrame()
CheckForInput()
DoOtherStuff()
...
但是,他的代码中的循环在哪里?
在这一行:
for chunk in r.iter_content(chunk_size=1024):
iter_content是一个生成器,它使循环直到流为空。
这里有些博士:http://docs.python-requests.org/en/latest/api/#requests.Response.iter_content