Problem: 你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
Solution: Resize Images, Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import cv2 import os def resize_images(base_dir, size=(1136, 640)): ''' 更改图片尺寸,使之不高于 iPhone 5 的分辨率 ''' files = os.listdir(base_dir) for f in files: if os.path.splitext(f)[1][1:] in ['jpg', 'png', 'bmp', 'gif', 'jpeg']: img = cv2.imread(base_dir + f) img_size = img.shape[:2] if 0 < img_size[0] <= size[0] and 0 < img_size[1] <= size[1]: size = img_size else: img = cv2.resize(img, size) cv2.imwrite(base_dir + 'resized_' + f, img) if __name__ == '__main__': base_dir = 'iPhone5/' resize_images(base_dir)
|
主要目的是练习使用 Python 操作图像,这里使用的是 cv2
的 API —— 读取图像 cv2.imread(self, args)
,获得图像的尺寸 im.shape
,更改图像尺寸 cv2.resize(self, args)
,以及写图片 cv2.imwrite(self, args)
。也可以使用 PIL 的 API 去实现。
题目来源:Python 练习册,每天一个小程序 THX!