Read Image From Url as Byte Stream Python
Today's blog mail service comes directly from my own personal repository of utility functions.
Over the by month I've gotten a handful of PyImageSearch readers emailing in and request how to download an paradigm from a URL and so catechumen information technology to OpenCV format (without writing it to disk and and then reading it dorsum) — and in this article I'll show y'all exactly how do it.
And as a bonus we'll also see how nosotros can apply scikit-image to download an paradigm from a URL, forth with a common "gotcha" that could trip yous up forth the way.
Go on reading to learn how to catechumen a URL to an image using Python and OpenCV.
Looking for the source code to this post?
Jump Right To The Downloads Department OpenCV and Python versions:
In guild to run this example, yous'll need Python 2.7 and OpenCV 2.four.X.
Method #one: OpenCV, NumPy, and urllib
The offset 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 permit's get started:
# import the necessary packages import numpy every bit np import urllib import cv2 # METHOD #1: OpenCV, NumPy, and urllib def url_to_image(url): # download the image, catechumen it to a NumPy array, and then read # information technology into OpenCV format resp = urllib.urlopen(url) epitome = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # return the prototype return image
The first affair 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 asking, and cv2 for our OpenCV bindings.
We then define our url_to_image function on Line 7. This function requires a single statement, url , which is the URL of the image nosotros want to download.
Next, we apply the urllib library to open a connection to the supplied URL on Line 10. The raw byte-sequence from the asking 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 2nd format, assuming 3 components per pixel (i.east. the Red, Green, and Blue components, respectively), we make a call to cv2.imdecode on Line 12. Finally, we return the decoded epitome to the calling office on Line fifteen.
Alright, time to put this function to work:
# initialize the list of paradigm 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 paradigm URLs for url in urls: # download the paradigm URL and display information technology impress "downloading %southward" % (url) prototype = url_to_image(url) cv2.imshow("Image", image) cv2.waitKey(0) Lines xviii-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, then finally display our downloaded image to our screen on Lines 29 and thirty. At this point our image can be manipulated with whatever other OpenCV functions as we normally would.
To run across our work in action, open a last and execute the following command:
$ python url_to_image.py
If all goes well, you should first run into the OpenCV logo:
And next the Google logo:
And here's an case of me demonstrating face detection in my book, Practical Python and OpenCV:
Now, allow's motion on to the alternative method to downloading an paradigm and converting it to OpenCV format.
Method #2: scikit-image
The second method assumes that yous have the scikit-epitome library installed on your organisation. Let's accept a expect at how we can leverage scikit-image to download an image from a URL and convert information technology to OpenCV format:
# METHOD #2: scikit-image from skimage import io # loop over the image URLs for url in urls: # download the paradigm using scikit-image impress "downloading %due south" % (url) image = io.imread(url) cv2.imshow("Incorrect", image) cv2.imshow("Correct", cv2.cvtColor(prototype, cv2.COLOR_BGR2RGB)) cv2.waitKey(0) One of the squeamish aspects of the scikit-paradigm library is that the imread function in the io sub-bundle can tell the departure between a path to an image on disk and a URL (Line 39).
However, there is an important gotcha that tin can really trip you up!
OpenCV represents images in BGR society — whereas scikit-image represents images in RGB order. If you apply the scikit-image imread function and desire to utilize OpenCV functions after downloading the image, you need to accept special intendance to convert the image from RGB to BGR (Line 41).
If you don't have this extra step, you may obtain incorrect results:
Have a look at the Google logo beneath to make this point fifty-fifty more than clear:
And then at that place you have information technology! Two methods to convert a URL to an image using Python, OpenCV, urllib, and scikit-paradigm.
What's side by side? I recommend PyImageSearch University.
Class information:
35+ total classes • 39h 44m video • Concluding updated: February 2022
★★★★★ iv.84 (128 Ratings) • 3,000+ Students Enrolled
I strongly believe that if y'all had the right teacher you could principal estimator vision and deep learning.
Do you think learning calculator vision and deep learning has to exist time-consuming, overwhelming, and complicated? Or has to involve circuitous mathematics and equations? Or requires a degree in computer science?
That's not the instance.
All y'all need to master reckoner vision and deep learning is for someone to explain things to yous in uncomplicated, intuitive terms. And that'due south exactly what I exercise. My mission is to change education and how circuitous Artificial Intelligence topics are taught.
If you lot're serious about learning reckoner vision, your next terminate should be PyImageSearch Academy, the most comprehensive calculator vision, deep learning, and OpenCV course online today. Here you'll learn how to successfully and confidently utilise calculator vision to your work, research, and projects. Join me in calculator vision mastery.
Inside PyImageSearch University you'll discover:
- ✓ 35+ courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 35+ Certificates of Completion
- ✓ 39h 44m on-need video
- ✓ Brand new courses released every month , ensuring you can keep upward with country-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all lawmaking examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Admission to centralized code repos for all 500+ tutorials on PyImageSearch
- ✓ Like shooting fish in a barrel i-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Click hither to join PyImageSearch University
Summary
In this blog mail service 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 employ the urllib Python package to download the image, convert it to an assortment using NumPy, and finally reshape the assortment using OpenCV to construct our image.
The second method is to use the io.imread function of scikit-prototype.
And then which method is amend?
It all depends on your setup.
If y'all already have scikit-epitome installed, I would utilise the io.imread part (but don't forget to convert from RGB to BGR if y'all are using OpenCV functions). And if you do not have scikit-epitome installed, I would manus-roll the url_to_image part detailed at the beginning of this article.
I'll also exist adding this role to the imutils package on GitHub shortly.
Download the Source Lawmaking and Free 17-page Resource Guide
Enter your electronic mail address below to go a .zippo of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll observe my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!
Source: https://pyimagesearch.com/2015/03/02/convert-url-to-image-with-python-and-opencv/
0 Response to "Read Image From Url as Byte Stream Python"
Post a Comment