スニペット

from pathlib import Path
import glob

def split_imgs(src_dir , dis_dir, x_split_size):
   file_paths = glob.glob(f"{src_dir}/**/*.jpg", recursive = True)
   for file_path in file_paths:
       p = Path(file_path)
       dataset_name = p.parts[0]
       class_name = p.parts[1]
       file_name = p.stem
       ext_name = p.suffix
       full_file_name = p.name
       img_bgr = cv2.imread(file_path)
       height, width = img_bgr.shape[:2]

       next_width = int(width / x_split_size)
       for i in range(x_split_size):
           index = i+1
           x1 = next_width * i
           x2 = x1 + next_width 
           cropped_img_bgr = img_bgr[0:width, x1:x2]
           next_path = "/".join([dis_dir, class_name, f"{file_name}_{index}{ext_name}"])
           next_dir = "/".join([dis_dir, class_name])
           Path(next_dir).mkdir(parents=True, exist_ok=True)
           cv2.imwrite(next_path, cropped_img_bgr)