如何在 Python 中根据图像尺寸属性过滤图像?


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

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

Pillow 库构建在 Python 图像库 (PIL) 之上,并提供了比其父库 (PIL) 更多的功能。

安装

我们可以使用 pip 安装 pillow,只需在命令终端中输入以下内容:

$ pip install pillow

Pillow 的基本操作

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

from PIL import Image
image = Image.open(r"C:\Users\rajesh\Desktop\imagefolder\beach-parga.jpg")
image.show()
# The file format of the source file.
# Output: JPEG
print(image.format)

# The pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK.”
# Output: RGB
print(image.mode)

# Image size, in pixels. The size is given as a 2-tuple (width, height).
# Output: (2048, 1365)
print(image.size)


# Colour palette table, if any.
#Output: None
print(image.palette)

输出

JPEG
RGB
(2048, 1365)
None

根据尺寸过滤图像

下面的程序将减小特定路径(默认路径:当前工作目录)中所有图像的大小。我们可以在下面给出的程序中更改图像的最大高度、最大宽度或扩展名。

代码

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(宽度/高度)的最大尺寸。

更新于: 2019-07-30

230 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.