'Python 3 streaming video using requests: where is the loop?
Varun Chatterji posted how to use requests to stream video from an IP (ethernet) camera that requires a login and password. This is exactly what I needed and the only thing that works for my camera in python 3.4 on windows 7.
However, where is the loop in his code? When I run this code it runs infinitely while showing video in a cv2 window. However, the code lacks a "while True:" statement and I'm not finding any help in my searches. I'd like to move the loop to higher level module, but I don't know where the loop is.
Said another way, can someone refactor this code so there there is a "while True:" line somewhere? That would let me see what is inside the loop and what is not. I'm finding the requests documentation very hard to follow.
Varun's code for reference:
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))
The motivation for this is that I want to move the stuff "inside the loop" into a subroutine, call it ProcessOneVideoFrame() and then be able to put into a larger program:
while True:
ProcessOneVideoFrame()
CheckForInput()
DoOtherStuff()
...
Solution 1:[1]
Well, stream=True basically tells us always to run as long as receiving data which is equal to the while True statement. There is also an inner loop which is the for chunk in r.iter_content(chunk_size=1024) that already explained in François answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willy satrio nugroho |
