1. 程式人生 > >用Python批量裁剪圖片

用Python批量裁剪圖片

這篇博文主要介紹如何批量裁剪圖片,直接上程式碼,註釋已經講得很清楚了。 

# coding: utf-8
from PIL import Image
import os
import os.path
import numpy as np
import cv2
#指明被遍歷的資料夾
rootdir = r'E:\AD datasets\voiceClassifyGoogle\Class\C'
for parent, dirnames, filenames in os.walk(rootdir):#遍歷每一張圖片
    for filename in filenames:
        print('parent is :' + parent)
        print('filename is :' + filename)
        currentPath = os.path.join(parent, filename)
        print('the fulll name of the file is :' + currentPath)
   
        img = Image.open(currentPath)
        print (img.format, img.size, img.mode)
        #img.show()
        box1 = (17, 16, 158, 189)#設定左、上、右、下的畫素
        image1 = img.crop(box1) # 影象裁剪
        image1.save(r"E:\AD datasets\voiceClassifyGoogle\Class\C_2"+'\\'+filename) #儲存裁剪得到的影象

注意更改自己的路徑和剪下圖片的畫素。