Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Benjit87/4188834 to your computer and use it in GitHub Desktop.
Save Benjit87/4188834 to your computer and use it in GitHub Desktop.
/*
http://benjithian.sg/2012/12/stream-jpeg-frames-from-andriod-camera-via-http/
I used IP Webcam Andriod App to make my tablet as a webcam but was unable to use the VideoCapture class yet.
So here is just a quick way of streaming it through JPEG Frames, it is similar the my previous post on loading
an image from a website. Make sure the wait time must be greater than your camera frame rate.
*/
#include <stdio.h>
#include <curl/curl.h>
#include <sstream>
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
//curl writefunction to be passed as a parameter
size_t write_data(char *ptr, size_t size, size_t nmemb, void *userdata) {
std::ostringstream *stream = (std::ostringstream*)userdata;
size_t count = size * nmemb;
stream->write(ptr, count);
return count;
}
//function to retrieve the image as Cv::Mat data type
cv::Mat curlImg()
{
CURL *curl;
CURLcode res;
std::ostringstream stream;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.0.108:8080/shot.jpg"); //the JPEG Frame url
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); // pass the writefunction
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream); // pass the stream ptr when the writefunction is called
res = curl_easy_perform(curl); // start curl
std::string output = stream.str(); // convert the stream into a string
curl_easy_cleanup(curl); // cleanup
std::vector<char> data = std::vector<char>( output.begin(), output.end() ); //convert string into a vector
cv::Mat data_mat = cv::Mat(data); // create the cv::Mat datatype from the vector
cv::Mat image = cv::imdecode(data_mat,1); //read an image from memory buffer
return image;
}
int main(void)
{
cv::namedWindow( "Image output", CV_WINDOW_AUTOSIZE );
while(1)
{
cv::Mat image = curlImg(); // get the image frame
cv::imshow("Image output",image); //display image frame
char c = cvWaitKey(33); // sleep for 33ms or till a key is pressed (put more then ur camera framerate mine is 30ms)
if ( c == 27 ) break; // break if ESC is pressed
}
cv::destroyWindow("Image output");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment