Ask Your Question

load image from url

asked 2016-03-30 01:34:34 -0500

AVB gravatar image

updated 2017-08-02 16:29:47 -0500

I'm new to OpenCV. I've given a link to the function imread as follows:

Mat logo = imread("");

I've checked and the image exists on the given path. imread() still fails to read it.

Any mistake that I've made?


edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2016-03-30 02:01:14 -0500

berak gravatar image

imread cannot read an url, only a local file.

if you need to download a car via the internet, you need the help of e.g. libcurl

#include "curl/curl.h" // has to go before opencv headers

#include <iostream>
#include <vector>
using namespace std;

#include <opencv2/opencv.hpp>
using namespace cv;

//curl writefunction to be passed as a parameter
// we can't ever expect to get the whole image in one piece,
// every router / hub is entitled to fragment it into parts
// (like 1-8k at a time),
// so insert the part at the end of our stream.
size_t write_data(char *ptr, size_t size, size_t nmemb, void *userdata)
    vector<uchar> *stream = (vector<uchar>*)userdata;
    size_t count = size * nmemb;
    stream->insert(stream->end(), ptr, ptr + count);
    return count;

//function to retrieve the image as cv::Mat data type
cv::Mat curlImg(const char *img_url, int timeout=10)
    vector<uchar> stream;
    CURL *curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, img_url); //the img url
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); // pass the writefunction
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream); // pass the stream ptr to the writefunction
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); // timeout if curl_easy hangs, 
    CURLcode res = curl_easy_perform(curl); // start curl
    curl_easy_cleanup(curl); // cleanup
    return imdecode(stream, -1); // 'keep-as-is'

int main(void)
    Mat image = curlImg("");
    if (image.empty())
        return -1; // load fail

    namedWindow( "Image output", CV_WINDOW_AUTOSIZE );
    imshow("Image output",image); // here's your car ;)
    waitKey(0); // infinite
edit flag offensive delete link more


Got it to work! Thank You!!

AVB gravatar imageAVB ( 2016-03-30 04:08:55 -0500 )edit

Question Tools

1 follower


Asked: 2016-03-30 01:34:34 -0500

Seen: 8,622 times

Last updated: Mar 30 '16