Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to plot a remote image from http url using Matplotlib?
To plot a remote image from an HTTP URL using Matplotlib, we can use io.imread() from scikit-image to read the URL directly. This approach allows us to display images hosted on the web without downloading them locally first.
Basic Example
Here's how to load and display a remote image ?
from skimage import io
import matplotlib.pyplot as plt
# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Load image from HTTP URL
url = "https://matplotlib.org/stable/_static/logo2.png"
image_data = io.imread(url)
# Display the image
plt.imshow(image_data)
plt.axis('off') # Hide axes for cleaner display
plt.title("Remote Image from URL")
plt.show()
Alternative Method Using urllib
You can also use urllib and PIL for more control over the image loading process ?
import matplotlib.pyplot as plt
from PIL import Image
import urllib.request
# Download image from URL
url = "https://matplotlib.org/stable/_static/logo2.png"
with urllib.request.urlopen(url) as response:
image = Image.open(response)
# Display the image
plt.figure(figsize=(8, 4))
plt.imshow(image)
plt.axis('off')
plt.title("Image loaded with urllib and PIL")
plt.show()
Handling Different Image Formats
The io.imread() method supports various image formats including PNG, JPEG, and GIF ?
from skimage import io
import matplotlib.pyplot as plt
# List of different image URLs
urls = [
"https://matplotlib.org/stable/_static/logo2.png",
"https://via.placeholder.com/300x200/blue/white.jpg"
]
# Create subplots for multiple images
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for i, url in enumerate(urls):
try:
image_data = io.imread(url)
axes[i].imshow(image_data)
axes[i].axis('off')
axes[i].set_title(f"Image {i+1}")
except Exception as e:
axes[i].text(0.5, 0.5, f"Error loading\n{url}",
ha='center', va='center', transform=axes[i].transAxes)
plt.tight_layout()
plt.show()
Key Points
- io.imread() from scikit-image can directly read images from HTTP URLs
- Use plt.axis('off') to hide coordinate axes for cleaner image display
- Always handle exceptions when loading remote images as URLs might be unreachable
- Set appropriate figure sizes using plt.rcParams or figsize parameter
Conclusion
Loading remote images with Matplotlib is straightforward using io.imread() from scikit-image. This method handles the HTTP request automatically and returns the image data ready for display with imshow().
Advertisements
