在 Python 中根据大小属性过滤图像?

pythonprogrammingserver side programming

Python 提供了多个图像处理库,包括 Pillow、Python Imaging 库、scikit-image 或 OpenCV。

我们将在这里使用 Pillow 库进行图像处理,因为它提供了多种标准图像处理程序,并支持多种图像文件格式,如 jpeg、png、gif、tiff、bmp 等。

Pillow 库建立在 Python Imaging 库 (PIL) 之上,提供的功能比其父库 (PIL) 更多。

安装

我们可以使用 pip 安装枕头,因此只需在命令终端中输入以下内容 −

$ pip install pillow

枕头上的基本操作

让我们使用枕头对图像进行一些基本操作库。

从 PIL 导入图像
image = Image.open(r"C:\Users\rajesh\Desktop\imagefolder\beach-parga.jpg")
image.show()
# 源文件的文件格式。
# 输出:JPEG
print(image.format)

# 图像使用的像素格式。典型值为"1"、"L"、"RGB"或"CMYK"。
# 输出:RGB
print(image.mode)

# 图像大小,以像素为单位。大小以 2 元组 (宽度、高度) 的形式给出。
# 输出:(2048, 1365)
print(image.size)

# 调色板表(如果有)。
#输出:None
print(image.palette)

输出

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

运行上述脚本时,当前工作目录(当前为 pyton 脚本文件夹)中存在的图像的最大尺寸为 900(宽度/高度)。


相关文章