上一篇文章介绍如何用os.walk(file_path)来遍历文件夹里面的文件,同时顺便介绍了file_path.endwith(arg)的用法。
本次介绍一个实际应用,也是刚好昨天有一个朋友有约3000张照片要按要求上传至网站。但是这些照片都是用手机拍,每张少说也有2M,不符合上传的要求。用PYTHON压缩图片有很多种办法,这里使用OPENCV。(安装办法:pip install opencv-python)
- os.makedirs(resize_image_dir,exist_ok=True):表示在当前目录创建一个文件夹,参数exist_ok=True,True是指如果被创建的文件夹存在,也可以使用。
- os.path.join(dir_path , file):组建文件路径
- cv2.imread(image_path):用OPENCV读取图片
- 100/image.shape[1]:shape[1]表示图片的宽度数据,shape[0]表示图片高度数据
- cv2.resize(image, new_image_size, interpolation=cv2.INTER_AREA):这是OPENCV调整图片的函数,第一个参数是传入图片对象,第二个参数是一个元组,传入要调整尺寸,第三参数是要传入调整的方式。
#coding=utf-8
import cv2
import os
resize_image_dir = "rezie" #新建一个放置压缩相片的文件
os.makedirs(resize_image_dir,exist_ok=True)
for dir_path , dir_list ,file_list in os.walk(r"."):
if(not dir_path.endswith(resize_image_dir)):
os.makedirs(os.path.join(resize_image_dir, dir_path), exist_ok=True)
for file in file_list:
image_path = os.path.join(dir_path , file)
if image_path.endswith(('.jpg', '.png', '.gif', '.jpeg')):
image = cv2.imread(image_path) #用OPENCV导入图片
resize_percent = 100/image.shape[1] #这里设置宽为100,高按原比例进行缩放
new_image_size = (int(image.shape[1]*resize_percent) , int(image.shape[0]*resize_percent)) #设置缩放图片尺寸,这里是一个元组,元组里只能是整数。
new_image= cv2.resize(image, new_image_size, interpolation=cv2.INTER_AREA)
new_image_path = os.path.join(str(resize_image_dir), image_path.strip('\.'))
cv2.imwrite(new_image_path, new_image)