【Python】裁剪图片代码
存一个自用裁剪图片代码
功能:固定像素中心裁剪、固定像素左上角裁剪(填充黑边)、图片一分为四
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)
def crop2(input_img_path, output_img_path, crop_w, crop_h, num): #左上角裁剪
image = Image.open(input_img_path)
x_max = image.size[0]
y_max = image.size[1]
if crop_w > x_max: #超出范围填充黑边
print(num, "pic width out of range!")
if crop_h > y_max: #超出范围填充黑边
print(num, "pic height out of range!")
up = 0 # up:上边裁剪起始位置
left = 0 #left:左边裁剪起始位置
down = int(crop_h)
right = int(crop_w)
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)
def crop1_4(input_img_path, output_img_path): #一分为四
image = Image.open(input_img_path)
height = image.size[1]
width = image.size[0]
# print("old image size (wxh)=", (width, height))
img_1 = image.crop([0, 0, width / 2, height / 2])
img_2 = image.crop([width / 2, 0, width, height / 2])
img_3 = image.crop([0, height / 2, width / 2, height])
img_4 = image.crop([width / 2, height / 2, width, height])
img1_path = output_img_path.replace('.jpg', '(1).jpg')
img2_path = output_img_path.replace('.jpg', '(2).jpg')
img3_path = output_img_path.replace('.jpg', '(3).jpg')
img4_path = output_img_path.replace('.jpg', '(4).jpg')
img_1.save(img1_path)
img_2.save(img2_path)
img_3.save(img3_path)
img_4.save(img4_path)
if __name__ == '__main__':
dataset_dir = "" # 图片路径
output_dir = "" # 输出路径
if not os.path.exists(output_dir):
os.makedirs(output_dir)
num = 0 # 裁剪图片数
crop_w = 300 # 裁剪图片宽
crop_h = 300 # 裁剪图片高
# 获得需要转化的图片路径并生成目标路径
image_filenames = [(os.path.join(dataset_dir, x), os.path.join(output_dir, x))
for x in os.listdir(dataset_dir)]
# for x in os.listdir(dataset_dir):
# print(x)
# 转化所有图片
for path in image_filenames:
num = num + 1
# crop(path[0], path[1], crop_w, crop_h) #固定像素中心裁剪
# crop2(path[0], path[1], crop_w, crop_h, num) #左上角为起点裁剪
crop1_4(path[0], path[1]) #一分为四
print(num, "picture has done!")
互联网代码缝合怪,侵删