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

การหา Resolution ของภาพด้วย scikit-image ใน Python

Resolution ของภาพ = ขนาดความกว้าง × ความสูง (Width × Height) และจำนวน Channels สามารถดูได้จาก Attribute .shape ของ NumPy Array ที่ได้จาก io.imread()

ตัวอย่างโค้ด


from skimage import io
import matplotlib.pyplot as plt

path = "puppy.png"  # ปรับ Path ตามจริง

img = io.imread(path)
print("Image being read")
print("Image dtype:", img.dtype)

# แสดงภาพ
plt.imshow(img)
plt.title("Loaded Image")
plt.axis('off')
plt.show()

# Resolution และ Channels
print("Image resolution (H, W, C):", img.shape)
print(f"Height: {img.shape[0]} pixels")
print(f"Width:  {img.shape[1]} pixels")
if img.ndim == 3:
    print(f"Channels: {img.shape[2]}")
    if img.shape[2] == 3:
        print("Format: RGB")
    elif img.shape[2] == 4:
        print("Format: RGBA (มี Alpha Channel)")
else:
    print("Format: Grayscale")

ผลลัพธ์


Image being read
Image dtype: uint8
Image resolution (H, W, C): (397, 558, 4)
Height: 397 pixels
Width: 558 pixels
Channels: 4
Format: RGBA (มี Alpha Channel)

การหา Resolution ของภาพด้วย scikit-image ใน Python

คำอธิบาย

  • io.imread() อ่านไฟล์ภาพคืน NumPy Array

  • img.shape คืน Tuple (Height, Width, Channels)

  • Index 0 = Height (Rows), Index 1 = Width (Columns), Index 2 = Channels

  • Channel = 4 หมายถึง RGBA (Red, Green, Blue, Alpha/Transparency)

การเปลี่ยนแปลง Resolution (Resizing)


from skimage.transform import resize

# Resize เป็น 200x200
img_resized = resize(img, (200, 200), anti_aliasing=True)
print("Resized shape:", img_resized.shape)  # (200, 200, 4)

# รักษา Aspect Ratio
from skimage.transform import rescale
img_scaled = rescale(img, 0.5, channel_axis=2, anti_aliasing=True)
print("Scaled 0.5x shape:", img_scaled.shape)

การบันทึกภาพ


io.imsave("output.png", img)
io.imsave("output.jpg", img, quality=90)  # JPEG Quality

รูปแบบไฟล์ที่รองรับ

skimage รองรับ: PNG, JPEG, TIFF, BMP, GIF (ผ่าน plugin) และอื่นๆ