Python批量裁剪圖片的思路詳解
更新時間:2022年07月07日 10:22:46 作者:zstar-_
這篇文章主要介紹了Python批量裁剪圖片的程序代碼,是批量裁剪某一文件夾下的所有圖片,并指定裁剪寬高,本文給大家分享實現(xiàn)思路,需要的朋友可以參考下
需求
我的需求是批量裁剪某一文件夾下的所有圖片,并指定裁剪寬高。
思路
1、 先使用PIL.Image.size獲取輸入圖片的寬高。
2、寬高除以2得到中心點坐標
3、根據(jù)指定寬高,以中心點向四周拓展
4、調(diào)用PIL.Image.crop完成裁剪
程序
import os
from PIL import Image
def crop(input_img_path, output_img_path, crop_w, crop_h):
image = Image.open(input_img_path)
x_max = image.size[0]
y_max = image.size[1]
mid_point_x = int(x_max / 2)
mid_point_y = int(y_max / 2)
right = mid_point_x + int(crop_w / 2)
left = mid_point_x - int(crop_w / 2)
down = mid_point_y + int(crop_h / 2)
up = mid_point_y - int(crop_h / 2)
BOX_LEFT, BOX_UP, BOX_RIGHT, BOX_DOWN = left, up, right, down
box = (BOX_LEFT, BOX_UP, BOX_RIGHT, BOX_DOWN)
crop_img = image.crop(box)
crop_img.save(output_img_path)
if __name__ == '__main__':
dataset_dir = "cut" # 圖片路徑
output_dir = 'out' # 輸出路徑
crop_w = 300 # 裁剪圖片寬
crop_h = 300 # 裁剪圖片高
# 獲得需要轉(zhuǎn)化的圖片路徑并生成目標路徑
image_filenames = [(os.path.join(dataset_dir, x), os.path.join(output_dir, x))
for x in os.listdir(dataset_dir)]
# 轉(zhuǎn)化所有圖片
for path in image_filenames:
crop(path[0], path[1], crop_w, crop_h)測試
裁剪前:

裁剪后:

到此這篇關(guān)于Python批量裁剪圖片小腳本的文章就介紹到這了,更多相關(guān)Python批量裁剪內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python的Django中django-userena組件的簡單使用教程
這篇文章主要介紹了Python的Django中django-userena組件的簡單使用教程,包括用戶登陸和注冊等簡單功能的實現(xiàn),需要的朋友可以參考下2015-05-05

