Python批量裁剪圖片的思路詳解
需求
我的需求是批量裁剪某一文件夾下的所有圖片,并指定裁剪寬高。
思路
1、 先使用PIL.Image.size獲取輸入圖片的寬高。
2、寬高除以2得到中心點(diǎn)坐標(biāo)
3、根據(jù)指定寬高,以中心點(diǎn)向四周拓展
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)化的圖片路徑并生成目標(biāo)路徑
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)測(cè)試
裁剪前:

裁剪后:

到此這篇關(guān)于Python批量裁剪圖片小腳本的文章就介紹到這了,更多相關(guān)Python批量裁剪內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)自定義讀寫分離代碼實(shí)例
這篇文章主要介紹了Python實(shí)現(xiàn)自定義讀寫分離代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
Python的Django中django-userena組件的簡(jiǎn)單使用教程
這篇文章主要介紹了Python的Django中django-userena組件的簡(jiǎn)單使用教程,包括用戶登陸和注冊(cè)等簡(jiǎn)單功能的實(shí)現(xiàn),需要的朋友可以參考下2015-05-05

