Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - การทำงานกับรูปภาพ PNG ด้วย Matplotlib

Matplotlib เป็นไลบรารีแสดงผลข้อมูล 2D ยอดนิยม สร้างบน NumPy arrays ทำงานร่วมกับ SciPy stack ได้ดี

ตัวอย่างเทคนิคต่างๆ

1. Pseudocolor (สีเท็จ)

import matplotlib.pyplot as plt
import matplotlib.image as img

im = img.imread('imR.png')
lum = im[:, :, 0]  # เอาช่องสีแรก (Red channel)
plt.imshow(lum)
plt.show()

2. Pseudocolor พร้อม Colormap 'hot' และ Colorbar

plt.imshow(lum, cmap='hot')
plt.colorbar()
plt.show()

3. ปรับขนาดรูปด้วย PIL แล้วแสดง

from PIL import Image
import matplotlib.pyplot as plt

img = Image.open('imR.png')
img.thumbnail((50, 50), Image.Resampling.LANCZOS)
plt.imshow(img)
plt.show()

4. Interpolation 'bicubic'

img = Image.open('imR.png')
img.thumbnail((30, 30), Image.Resampling.LANCZOS)
plt.imshow(img, interpolation='bicubic')
plt.show()

5. Interpolation 'sinc'

plt.imshow(img, interpolation='sinc')
plt.show()

คำอธิบาย

  • im[:,:,0] ดึงช่องสีแรก (Red) มาเป็น grayscale
  • cmap กำหนดแผนที่สี (viridis, hot, cool, jet, ฯลฯ)
  • interpolation ควบคุมวิธีการขยาย/ย่อพิกเซล (nearest, bilinear, bicubic, sinc, ฯลฯ)
  • PIL (Pillow) ใช้สำหรับโหลดและปรับขนาดรูปก่อนส่งให้ Matplotlib