使用python对图像进行4等分切割,这里是使用目录,对目录中的所有图像进行切割后保存到新的目录中
mport cv2
import os
import pathlib
source_path = "D:/up_cam124_90"
target_path = "D:/up_cam124_90_split"
def mkdir(path):
path = path.strip()
path = path.rstrip("\\")
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
print(path + ' 创建成功')
return True
else:
print(path + ' 目录已存在')
return False
def split_img(img_file):
img = cv2.imread(img_file)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_h = img.shape[0] # 高度
img_w = img.shape[1] # 宽度
# h1_half = int(img_h / 2)
# w1_half = int(img_w / 2)
h1_half = img_h // 2
w1_half = img_w // 2
img_name = os.path.basename(img_file)
for i in range(4):
img1 = img[int(i / 2) * h1_half: h1_half * (int(i / 2) + 1), int(i % 2) * w1_half: (int(i % 2) + 1) * w1_half]
img1_path = os.path.join(target_path, f"{img_name[:-4]}_{i}.jpg")
print("spilt img:", img1_path)
cv2.imwrite(img1_path, img1)
if __name__ == '__main__':
mkdir(target_path)
for file in pathlib.Path(source_path).glob('**/*'):
split_img(os.path.join(source_path, file))