In the last post I have written how to use an Android phone as a wifi IP camera. Now here I will discuss how we can stream the video using a python script.
I am using IP Webcam app as the camera app in my android phone. It is a super app with a lot of features. The video streams in motion jpeg format. In mjpeg, each frame is is compressed separately as a jpeg image.
I am discussing two ways to extract the video via python. Let the IP address of the android phone be 192.168.1.108.
import cv2 import urllib import numpy as np import os # Stream the video link stream=urllib.urlopen('http://192.168.1.108:8080/video?.mjpeg') bytes='' while True: bytes += stream.read(1024) # 0xff 0xd8 is the starting of the jpeg frame a = bytes.find('\xff\xd8') # 0xff 0xd9 is the end of the jpeg frame b = bytes.find('\xff\xd9') # Taking the jpeg image as byte stream if a!=-1 and b!=-1: os.system ( 'clear' ) jpg = bytes[a:b+2] bytes= bytes[b+2:] # Decoding the byte stream to cv2 readable matrix format i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR) # Display cv2.imshow('Mobile IP Camera',i) print "Press 'q' to exit" # Exit key if cv2.waitKey(1) & 0xFF == ord('q'): exit(0)
The code above manually parses the mjpeg stream without relying on opencv. Mjpeg over http is multipart/x-mixed-replace with boundary frame info and jpeg data is just sent in binary. So you don’t really need to care about http protocol headers. All jpeg frames start with marker
0xff 0xd8 and end with
0xff 0xd9. So the code above extracts such frames from the http stream and decodes them one by one. The execution will be stopped if we press the key ‘q’.
import numpy as np import cv2 import os cap = cv2.VideoCapture() # Opening the link cap.open("http://192.168.1.108:8080/video?.mjpeg") while True: # Capture frame-by-frame ret, frame = cap.read() # Display the resulting frame cv2.imshow('Mobile IP Camera',frame) # Clear screen os.system ( 'clear' ) # Exit key print "Press 'q' to exit" if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
The code above use opencv to extract the video. There will be a small delay while the link is being is being opened. It will be made up within seconds. The while loop starts if the given link is true. Each frames are saved to the variable frame. This frame is then directly displayed as in the line 13. Press the key ‘q’ to exit from execution of the script. Afterwards the captured video should be released.
A more interesting thing is if we connect with the IP
192.168.1.108:8080/enabletorch, the camera flash of the phone will be switched on and with the IP
192.168.1.108:8080/disabletorch, it will be switched off. This can be accessed via python script using