"""用Pythonp批量裁剪圖片"""
from PIL import Image
import matplotlib.pyplot as plt
import os
# 定義待批量裁剪圖像的路徑地址
IMAGE_INPUT_PATH = 'D:/2_Class'
# 定義裁剪后的圖像存放地址
IMAGE_OUTPUT_PATH = 'D:/2_Class[0]'
# 定義裁剪圖片左、上、右、下的像素坐標
BOX_LEFT, BOX_UP, BOX_RIGHT, BOX_DOWN = 130, 180, 600, 400
for each_image in os.listdir(IMAGE_INPUT_PATH):
# 每個圖像全路徑
image_input_fullname = IMAGE_INPUT_PATH + '/' + each_image
# PIL庫打開每一張圖像
img = Image.open(image_input_fullname)
plt.figure("image_input_fullname")
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.axis('off')
print(img.format, img.size, img.mode)
# 從原始圖像返回一個矩形區域,區域是一個4元組定義左上右下像素坐標
box = (BOX_LEFT, BOX_UP, BOX_RIGHT + BOX_LEFT, BOX_DOWN + BOX_UP)
# 進行roi裁剪
roi_area = img.crop(box)
plt.subplot(1, 2, 2)
plt.imshow(roi_area)
plt.axis('off')
print(roi_area.format, roi_area.size, roi_area.mode)
plt.show()
# 裁剪后每個圖像的路徑+名稱
image_output_fullname = IMAGE_OUTPUT_PATH + "/" + each_image
# 存儲裁剪得到的圖像
roi_area.save(image_output_fullname)
print('{0} crop done.'.format(each_image))