Reputation:
I'm trying to display the live stream from my phone (using IP Webcam) on a webpage using django. The code:
def gen(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
def video(request):
return StreamingHttpResponse(gen(IPWebCam(camera_ip)),content_type='multipart/x-mixed-replace; boundary=frame')
class IPWebCam(object):
def __init__(self,camera_ip):
self.url = "https://"+ camera_ip + "/shot.jpg"
print(self.url)
def __del__(self):
cv2.destroyAllWindows()
def get_frame(self):
imgResp = urllib.request.urlopen(self.url,context=context)
imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8)
img = cv2.imdecode(imgNp, -1)
# We are using Motion JPEG, but OpenCV defaults to capture raw images,
# so we must encode it into JPEG in order to correctly display the
# video stream
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
resize = cv2.resize(img, (270,250), interpolation=cv2.INTER_LINEAR)
ret, jpeg = cv2.imencode('.jpg', resize)
return jpeg.tobytes()
So here video
is the view to display the live stream. I'm using "{% url 'video' %}"
to render the view on a template and also added the view in urlpatterns. The template where i'm displaying the stream has grid view. Where i would like to display cameras with different ip in each grid. Right now i'm able to display the same IP webcam stream in all the grids since there is only one view i.e video
and im rendering the same view in the template.
I would like to know,how can i display multiple streams in their corresponding grids?. There are six grids on a page. Should i create a view for each grid, but there will be more than 1 page, i cant keep creating these views and add them to urlpatterns. Is there a way where i can use the same view and use dynamic urls to solve this problem?
Upvotes: 0
Views: 1400
Reputation: 1609
You should define a parameter (camera_ip) in video
view to tell which camera stream should return.
def video(request, camera_ip):
return StreamingHttpResponse(gen(IPWebCam(camera_ip)),content_type='multipart/x-mixed-replace; boundary=frame')
You should pass all camera_ip values to page rendered in your detail view (I suppose that view exists but not mentioned in your question), then loop over the ip information to call "{% url 'video' camera_ip %}"
where camera_ip
should change each loop step.
Upvotes: 1