Python下使用opencv 对图片进行裁剪并按原来的图片名保存 import os import cv2 def file_name(file_dir): L=[] for root, dirs, files in os.walk(file_dir): for file in files: if os.path.splitext(file)[1] == '.jpg' or os.path.splitext(file)[1] == '.JPG' or os.path.splitext(file)[1] == '.JPEG' or os.path.splitext(file)[1] == '.jpeg'or os.path.splitext(file)[1] == '.png': fpath=os.path.join(root, file) L.append(fpath) return L def main(): train_path = "/path/to/your/img" files = file_name(train_path) for file in files: alls = file.split('/') name = alls[-1] img = cv2.imread(file) W = img.shape[1] #原图的宽 H = img.shape[0] #原图的高 W_R = int(H/3) #需要裁剪的宽 H_R = int(H/3) #需要裁剪的高 cropped = img [0:H_R,0:W] cv2.imwrite("/path/to/save/"+name, cropped) main()