图片批量裁剪器-python_opencv2+PIL

274 阅读1分钟
# -*-coding = utf-8 -*-
# @Time:2022/9/2/19:30
# @Author:seven
# @File:changeend.py
# @Software:PyCharm
import cv2
import numpy as np
import os
from PIL import Image
num = []
#图片路径
path=r"D:\PYcharm\ANIMS\myself_anim\movie\picture\movie\shl\"
#生成路径
path1=r"D:\PYcharm\ANIMS\myself_anim\movie\picture\movie\shl3\"

def hbw(path,path2,num):
    img = Image.open(path)
    w, h = img.size
    print(w,h)
    if num!=0:
        box = (num[0][0],num[0][1],num[1][0],num[1][1])
    else:
        box =(0,0,w,h)
    img = img.crop(box)
    if w/h>0.74:
        da = int((w-(h*0.74))/2)
        box = (da,0, w-da,h)
    else:
        da = int(h-(w/0.74))
        box = (0,0,w,h-da)
    region = img.crop(box)
    out = region.resize((451, 608), Image.ANTIALIAS)
    out.save(path2)
def mouse(event, x, y, flags, param):

    if event == cv2.EVENT_LBUTTONDOWN:
        xy = "%d,%d" % (x, y)
        cv2.circle(img, (x, y), 1, (255, 255, 255), thickness = -1)
        cv2.putText(img, xy, (x, y), cv2.FONT_HERSHEY_PLAIN,
                    1.0, (255, 255, 255), thickness = 1)
        cv2.imshow("image", img)
        num.append([x,y])

for i in os.listdir(path):
    img = cv2.imdecode(np.fromfile(path+i, dtype=np.uint8),
                       cv2.IMREAD_COLOR)
    cv2.namedWindow("image")
    cv2.imshow("image", img)
    cv2.setMouseCallback("image", mouse)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    print(num)
    if num==[]:
        hbw(path+i, path1+i,0)
    elif len(num)==2:
        hbw(path+i, path1+i,num)
    print(i)
    num=[]

不会用的私聊博主