用Python批量裁取圖,來獲取資料夾中所有圖片名
阿新 • • 發佈:2020-12-15
批量截圖(擷取正方形圖,哪個邊短就用哪個邊作為標準來擷取)
功能是裁取圖片中紅色框的部分。
程式碼為:
import sys
from tkinter.tix import Tk
from PIL import Image
import os
import tkinter
# 獲取資料夾中所有圖片名
def getFileName(filePath):
# file_dir = r"D:\\image123"
file_dir = filePath
i = 1
imageNameList = None
for root, dirs, files in os.walk(file_dir):
# print(i)
i += 1
# print(root) #當前目錄路徑
# print(dirs) #當前路徑下所有子目錄
# print(files) #當前路徑下所有非目錄子檔案
imageNameList = files
# print('所有的檔名為:', fileNameList)
return imageNameList
# 裁剪正方形圖,哪個邊短就用哪個邊作為標準來擷取
def cutImage(path, imageName):
# img = Image.open("D://image123//1.png")
# print('檔名為:', path + imageName)
img = Image.open(path + imageName)
# 圖片的寬度和高度
img_size = img.size
# print("圖片寬度和高度分別是{}".format(img_size))
cutSize = img_size[0] if (img_size[0] < img_size[1]) else img_size[1]
if (img_size[0] > img_size[1]): # 寬比高長
startX = (img_size[0] - img_size[1]) / 2 # 計算中間的位置
# 擷取中間的位置圖片
cropped = img.crop((startX, 0, cutSize + startX, cutSize)) # (left, upper, right, lower)
else: # 高比寬長
startY = (img_size[1] - img_size[0]) / 2 # 計算中間的位置
# 擷取中間的位置圖片
cropped = img.crop((0, startY, cutSize, cutSize + startY)) # (left, upper, right, lower)
# 判斷 D://cut_ok 目錄是否存在,不存在則新建
if not os.path.exists('D://cut_ok'):
os.makedirs('D://cut_ok')
# 儲存圖片
cropped.save("D://cut_ok//" + imageName)
def start(filePath):
print("路徑==:", filePath)
allImage = getFileName(filePath)
for fileName in allImage:
print(fileName)
# cutImage("D://image123//", fileName)
cutImage(filePath+"//", fileName)
if __name__ == '__main__':
if hasattr(sys, 'frozen'):
os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
# 介面****begin
window = Tk()
window.geometry("300x100")
# L1 = tkinter.Label(window, text="資料夾名:")
# L1.pack()
E1 = tkinter.Entry(window, bd=3, )
E1.pack()
# 獲取輸入框的值:E1.get()
B = tkinter.Button(window, text="開始剪下", command=lambda: start(E1.get()