

Now, let’s move on to the alternative method to downloading an image and converting it to OpenCV format. If all goes well, you should first see the OpenCV logo: Figure 1: Downloading the OpenCV logo from a URL and converting it to OpenCV format.Īnd next the Google logo: Figure 2: Downloading the Google logo from a URL and converting it to OpenCV format.Īnd here’s an example of me demonstrating face detection in my book, Practical Python and OpenCV: Figure 3: Converting an image URL to OpenCV format with Python. To see our work in action, open up a terminal and execute the following command: $ python url_to_image.py At this point our image can be manipulated with any other OpenCV functions as we normally would. 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.
#CONVERT IMAGE FORMAT WITH PYTHON DOWNLOAD#
Lines 18-21 define a list of image URLs that we are going to download and convert to OpenCV format. Finally, we return the decoded image to the calling function on Line 15.Īlright, time to put this function to work: # initialize the list of image URLs to download the Red, Green, and Blue components, respectively), we make a call to cv2.imdecode on Line 12. To reshape the array into a 2D format, assuming 3 components per pixel (i.e. The raw byte-sequence from the request is then converted to a NumPy array on Line 11.Īt this point the NumPy array is a 1-dimensional array (i.e. Next, we utilize the urllib library to open a connection to the supplied URL on Line 10. This function requires a single argument, url, which is the URL of the image we want to download. We then define our url_to_image function on Line 7.

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. The first thing we’ll do is import our necessary packages. Image = cv2.imdecode(image, cv2.IMREAD_COLOR) Image = np.asarray(bytearray(resp.read()), dtype="uint8") # download the image, convert it to a NumPy array, and then read Open up a new file, name it url_to_image.py, and let’s get started: # import the necessary packages

The first method we’ll explore is converting a URL to an image using the OpenCV, NumPy, and the urllib libraries. In order to run this example, you’ll need Python 2.7 and OpenCV 2.4.X.
#CONVERT IMAGE FORMAT WITH PYTHON CODE#
Looking for the source code to this post? Jump Right To The Downloads Section
