123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- import argparse
- import os
- import cv2
- from tqdm import tqdm
- def image_cut_save(path, left, upper, right, lower, save_path, pix):
- """
- 所截区域图片保存
- :param pix: 将图片height缩放的pix
- :param path: 图片路径
- :param left: 区块左上角位置的像素点离图片左边界的距离
- :param upper:区块左上角位置的像素点离图片上边界的距离
- :param right:区块右下角位置的像素点离图片左边界的距离
- :param lower:区块右下角位置的像素点离图片上边界的距离
- 故需满足:lower > upper、right > left
- :param save_path: 所截图片保存位置
- """
- img = cv2.imread(path) # 打开图像
- cropped = img[upper:lower, left:right]
- if pix != 0:
- height, width = cropped.shape[:2] # 原始分辨率
- if height != 0 and width != 0:
- while height < pix or width < pix:
- if height <= width:
- # 等比例缩放到pix
- scale = pix / height
- # 缩放后分辨率
- height = pix
- width = int(width * scale)
- else:
- # 等比例缩放到pix
- scale = pix / width
- # 缩放后分辨率
- width = pix
- height = int(height * scale)
- img = cv2.resize(cropped, (width, height))
- # 保存截取的图片
- cv2.imwrite(save_path, img)
- else:
- cv2.imwrite(save_path, cropped)
- if __name__ == '__main__':
- parser = argparse.ArgumentParser()
- parser.add_argument('--img_dir', type=str, default='./www', help='图片路径,填文件夹的路径')
- parser.add_argument('--save_dir', type=str, default='./', help='截取图片保存的文件夹路径')
- args = parser.parse_args()
- for path in tqdm(os.listdir(args.img_dir)):
- image_cut_save(args.img_dir + '/' + path, 465, 365, 640, 400, args.save_dir + '/bg_id_' + path, 0)
|