Title: Convert URL to image with Python and OpenCV - PyImageSearch

URL Source: https://pyimagesearch.com/2015/03/02/convert-url-to-image-with-python-and-opencv/

Published Time: 2015-03-02T15:00:58+00:00

Markdown Content:
[![Image 1: Downloading the OpenCV logo from a URL and converting it to OpenCV format.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20481'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/01/url_to_image_opencv.jpg)

Today’s blog post comes directly from my own personal repository of utility functions.

Over the past month I’ve gotten a handful of PyImageSearch readers emailing in and asking how to download an image from a URL and then convert it to OpenCV format (without writing it to disk and then reading it back) — and in this article I’ll show you exactly how do it.

And as a bonus we’ll also see how we can utilize [scikit-image](http://scikit-image.org/) to download an image from a URL, along with a common “gotcha” that could trip you up along the way.

Continue reading to learn how to convert a URL to an image using Python and OpenCV.

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

**OpenCV and Python versions:**  
In order to run this example, you’ll need **Python 2.7** and **OpenCV 2.4.X**.

Method #1: OpenCV, NumPy, and urllib
------------------------------------

The first method we’ll explore is converting a URL to an image using the OpenCV, NumPy, and the urllib libraries. Open up a new file, name it `url_to_image.py` , and let’s get started:

\# import the necessary packages
import numpy as np
import urllib
import cv2

# METHOD #1: OpenCV, NumPy, and urllib
def url\_to\_image(url):
	# download the image, convert it to a NumPy array, and then read
	# it into OpenCV format
	resp = urllib.urlopen(url)
	image = np.asarray(bytearray(resp.read()), dtype="uint8")
	image = cv2.imdecode(image, cv2.IMREAD\_COLOR)

	# return the image
	return image

The first thing we’ll do is import our necessary packages. We’ll use NumPy for converting the byte-sequence from the download to a NumPy array, `urllib` to perform the actual request, and `cv2` for our OpenCV bindings.

We then define our `url_to_image` function on **Line 7**. This function requires a single argument, `url` , which is the URL of the image we want to download.

Next, we utilize the `urllib` library to open a connection to the supplied URL on **Line 10**. The raw byte-sequence from the request is then converted to a NumPy array on **Line 11**.

At this point the NumPy array is a 1-dimensional array (i.e. a long list of pixels). To reshape the array into a 2D format, assuming 3 components per pixel (i.e. the Red, Green, and Blue components, respectively), we make a call to `cv2.imdecode` on **Line 12**. Finally, we return the decoded image to the calling function on **Line 15**.

Alright, time to put this function to work:

\# initialize the list of image URLs to download
urls = \[
	"https://pyimagesearch.com/wp-content/uploads/2015/01/opencv\_logo.png",
	"https://pyimagesearch.com/wp-content/uploads/2015/01/google\_logo.png",
	"https://pyimagesearch.com/wp-content/uploads/2014/12/adrian\_face\_detection\_sidebar.png",
\]

# loop over the image URLs
for url in urls:
	# download the image URL and display it
	print "downloading %s" % (url)
	image = url\_to\_image(url)
	cv2.imshow("Image", image)
	cv2.waitKey(0)

**Lines 18-21** define a list of image URLs that we are going to download and convert to OpenCV format.

We start looping over each of these URLs on **Line 25**, make a call to our `url_to_image` function on **Line 28**, and then finally display our downloaded image to our screen on **Lines 29 and 30**. At this point our image can be manipulated with any other OpenCV functions as we normally would.

To see our work in action, open up a terminal and execute the following command:

$ python url\_to\_image.py

If all goes well, you should first see the OpenCV logo:

[![Image 3: Figure 1: Downloading the OpenCV logo from a URL and converting it to OpenCV format.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20481'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/01/url_to_image_opencv.jpg)

**Figure 1:** Downloading the OpenCV logo from a URL and converting it to OpenCV format.

And next the Google logo:

[![Image 4: Figure 2: Downloading the Google logo from a URL and converting it to OpenCV format.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20257'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/01/url_to_image_google.jpg)

**Figure 2:** Downloading the Google logo from a URL and converting it to OpenCV format.

And here’s an example of me demonstrating face detection in my book, [_Practical Python and OpenCV_](https://pyimagesearch.com/practical-python-opencv/ "Practical Python and OpenCV"):

[![Image 5: Figure 3: Converting an image URL to OpenCV format with Python.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20254'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/01/url_to_image_face.jpg)

**Figure 3:** Converting an image URL to OpenCV format with Python.

Now, let’s move on to the alternative method to downloading an image and converting it to OpenCV format.

Method #2: scikit-image
-----------------------

The second method assumes that you have the [scikit-image](http://scikit-image.org/) library installed on your system. Let’s take a look at how we can leverage scikit-image to download an image from a URL and convert it to OpenCV format:

\# METHOD #2: scikit-image
from skimage import io

# loop over the image URLs
for url in urls:
	# download the image using scikit-image
	print "downloading %s" % (url)
	image = io.imread(url)
	cv2.imshow("Incorrect", image)
	cv2.imshow("Correct", cv2.cvtColor(image, cv2.COLOR\_BGR2RGB))
	cv2.waitKey(0)

One of the nice aspects of the scikit-image library is that the `imread`  function in the `io`  sub-package can tell the difference between a path to an image on disk and a URL (**Line 39**).

_**However, there is an important gotcha that can really trip you up!**_

OpenCV represents images in BGR order — whereas scikit-image represents images in RGB order. If you use the scikit-image `imread`  function and want to utilize OpenCV functions after downloading the image, you need to take special care to convert the image from RGB to BGR (**Line 41**).

If you don’t take this extra step, you may obtain incorrect results:

[![Image 6: Figure 4: Special care needs to be taken to convert from RGB to BGR when using scikit-image to convert a URL to an image.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20320'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/01/url_to_image_opencv_skimage.jpg)

**Figure 4:** Special care needs to be taken to convert from RGB to BGR when using scikit-image to convert a URL to an image. The image on the _left_ is incorrectly specified in the RGB order. The image on the _right_ correctly displays the image after it is converted from RGB to BGR order.

Take a look at the Google logo below to make this point even more clear:

[![Image 7: Figure 5: Order matters. Be sure to convert from RGB to BGR order or you might be tracking down a hard-to-find bug.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20128'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/01/url_to_image_google_skimage.jpg)

**Figure 5:** Order matters. Be sure to convert from RGB to BGR order or you might be tracking down a hard-to-find bug.

So there you have it! Two methods to convert a URL to an image using Python, OpenCV, urllib, and scikit-image.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

Summary
-------

In this blog post we learned about two methods to download an image from a URL and convert it to OpenCV format using Python and OpenCV.

The first method is to use the `urllib`  Python package to download the image, convert it to an array using NumPy, and finally reshape the array using OpenCV to construct our image.

The second method is to use the `io.imread`  function of [scikit-image](http://scikit-image.org/).

So which method is better?

It all depends on your setup.

If you already have scikit-image installed, I would use the `io.imread`  function (just don’t forget to convert from RGB to BGR if you are using OpenCV functions). And if you do not have scikit-image installed, I would hand-roll the `url_to_image`  function detailed at the beginning of this article.

I’ll also be adding this function to the [imutils](https://github.com/jrosebr1/imutils) package on GitHub soon.

![Image 8](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a **FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.** Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!