Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hiển thị nhiều ảnh kích thước thực trên subplot Matplotlib

Để hiển thị nhiều file ảnh với kích thước gốc (actual size) trên các subplot, dùng plt.imread() đọc ảnh và ax.imshow() trên từng axes.

Các bước

  • Thiết lập figure size và autolayout.
  • Đọc 2 ảnh: im1 = plt.imread("bird.jpg"), im2 = plt.imread("opencv-logo.png").
  • Tạo subplot 1 hàng 2 cột.
  • Tắt axes cho cả 2: ax[0].axis('off'), ax[1].axis('off').
  • Hiển thị ảnh: ax[0].imshow(im2), ax[1].imshow(im1, cmap='gray').
  • Hiển thị bằng show().

Ví dụ

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

im1 = plt.imread("bird.jpg")
im2 = plt.imread("opencv-logo.png")
fig, ax = plt.subplots(nrows=1, ncols=2)
ax[1].axis('off')
ax[1].imshow(im1, cmap='gray')
ax[0].axis('off')
ax[0].imshow(im2, cmap='gray')
plt.show()

Kết quả

Hiển thị nhiều ảnh kích thước thực trên subplot Matplotlib