Reading an mjpeg stream from an IP camera in OpenCV

A lot of times when I’m out running the streets or posted up at the club, I often overhear people talking about OpenCV.  Usually it’s something along the lines of, “well, I’d love to get started with OpenCV, but in order to do anything practical I really need a wireless connection to a camera that’s not directly tied to the computer I’m sitting at.”

This is unfortunate.  OpenCV is an extremely simple and powerful library to use.  Face detection, object detection, and edge detection are all things that can be done in a matter of minutes.  I dealt with this problem for my own needs, and hopefully others might stumble upon the solution I’ve developed, as the internets seemed to be lacking in any resources of this category.

Please see my code on Github.  The code is admittedly somewhat hacky.  This was a weekend project that I just wanted to get up and running.  I basically read jpeg frames, but the content-length in the jpeg header didn’t seem to match up with the amount of data being transmitted.  Rather than relying on the header info, I just scanned every byte to see if the end of the jpeg was reached (based on the encoding standards of a jpeg image).

Please note that in order to avoid messing with the extra steps necessary for authentication in connecting to the camera, I just removed the authentication entirely.  The camera I had access to for this project was a D-Link DCS-933L.

Another discovery I made while writing this code was that I needed to use iter_content() rather than iter_lines() in the python requests library.  Since the ASCII value for a new line character can also be used to represent a byte in a jpeg image, the stream would ignore that important piece of information and instead interpret it as a delimiter, thus giving us an invalid jpeg image and leaving me scratching my head.

  • Jose Antony

    is it possible to download a mjpeg stream mp4 video to sd card in android

    • Scott Benedict Lobdell

      yes, but that would be a fairly different project

      • Jose Antony

        can you help me to do that plz give me some guidance i am a starter in android
        now i can stream live MJPEG stream but i can download