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

การกรองภาพตามขนาดแอตทริบิวต์ใน Python

Python มีไลบรารีสำหรับการประมวลผลภาพหลายตัว รวมถึง Pillow, Python Imaging Library (PIL), scikit-image และ OpenCV ในบทความนี้จะใช้ไลบรารี Pillow เนื่องจากมีขั้นตอนมาตรฐานสำหรับการจัดการภาพหลากหลาย และรองรับรูปแบบไฟล์ภาพมากมาย เช่น JPEG, PNG, GIF, TIFF, BMP และอื่นๆ

Pillow สร้างขึ้นบนฐานของ Python Imaging Library (PIL) และให้คุณสมบัติมากกว่าไลบรารีต้นทาง

การติดตั้ง

สามารถติดตั้ง Pillow ผ่าน pip ได้ด้วยคำสั่ง:

$ pip install pillow

การดำเนินการพื้นฐานกับ Pillow

ลองทำการดำเนินการพื้นฐานบนภาพโดยใช้ไลบรารี Pillow:

from PIL import Image

image = Image.open(r"C:\Users\rajesh\Desktop\imagefolder\beach-parga.jpg")
image.show()

# รูปแบบไฟล์ของไฟล์ต้นทาง
# Output: JPEG
print(image.format)

# รูปแบบพิกเซลที่ใช้โดยภาพ ค่าทั่วไปคือ "1", "L", "RGB", หรือ "CMYK"
# Output: RGB
print(image.mode)

# ขนาดภาพในพิกเซล ขนาดจะถูกให้เป็น 2-tuple (width, height)
# Output: (2048, 1365)
print(image.size)

# ตารางพาเลตสี หากมี
# Output: None
print(image.palette)

ผลลัพธ์

การกรองภาพตามขนาดแอตทริบิวต์ใน Python

JPEG RGB (2048, 1365) None

กรองภาพตามขนาด

โปรแกรมด้านล่างจะลดขนาดของภาพทั้งหมดจากเส้นทางที่กำหนด (ค่าเริ่มต้น: ไดเรกทอรีทำงานปัจจุบัน) สามารถเปลี่ยน max_height, max_width หรือนามสกุลไฟล์ภาพในโปรแกรมด้านล่างได้:

โค้ด

import os
from PIL import Image

max_height = 900
max_width = 900
extensions = ['JPG']
path = os.path.abspath(".")

def adjusted_size(width, height):
    if width > max_width or height > max_height:
        if width > height:
            return max_width, int(max_width * height / width)
        else:
            return int(max_height * width / height), max_height
    else:
        return width, height

if __name__ == "__main__":
    for img in os.listdir(path):
        if os.path.isfile(os.path.join(path, img)):
            img_text, img_ext = os.path.splitext(img)
            img_ext = img_ext[1:].upper()
            if img_ext in extensions:
                print(img)
                image = Image.open(os.path.join(path, img))
                width, height = image.size
                image = image.resize(adjusted_size(width, height))
                image.save(os.path.join(path, img))

ผลลัพธ์

another_Bike.jpg clock.JPG myBike.jpg Top-bike-wallpaper.jpg

เมื่อรันสคริปต์ข้างต้น ขนาดของภาพในไดเรกทอรีทำงานปัจจุบัน (ซึ่งเป็นโฟลเดอร์สคริปต์ Python) จะมีขนาดสูงสุดที่ 900 พิกเซล (กว้าง/สูง)