python实现自动化裁图并保存在指定文件夹下

11 篇文章 1 订阅
8 篇文章 0 订阅

函数功能:自动化裁图并保存
函数应用:在深度学习当中,尤其是工业场景,通常数据集的尺寸大小非常大,而网络输入尺寸是固定的,所以在送入网络之前图片会统一resize到网络输入尺寸,图片较大的话,resize操作就相当于下采样,而图片送入网络后,网络通常还会进行数次下采样,如过我们要检测或分类的目标非常小的话,经过系列的下采样操作,感兴趣区域的目标特征直接2会消失。因此我们可以先将大图裁成数张小图进行训练,然后再将小图拼接回去,这样网络就能很好的学习到感兴趣区域的特征信息。

函数运行示例:
python segmention.py --img_path ./short_circuit/ --out_path ./workplace/short_circuit/

函数运行说明:函数是在命令行窗口运行的,因为我导入了python自带的命令行参数解析包,可以用来方便地读取命令行参数。它的使用也比较简单。
我设置了六个超参数:分别为:
img_path:需要裁图的批量图的路径
out_path: 存放裁剪后的图片的路径
step_x_n: x方向上每次的步长
step_y_n: y方向上每次的步长
crop_img_w_h: 要裁剪图片的宽
crop_img_h_n: 要裁剪图片的高
这里的步长和要裁剪的图片的宽高,都是相对整张图片而言的。

函数的优点:考虑到了边界问题,会进行重采样,使得边界的信息不会丢失

# -*- coding: utf-8 -*-
# @Time: 2020/12/31 18:49
# @Author: Min

import cv2
import os
import argparse


def show_img(img):
    cv2.namedWindow('img',0)
    cv2.resizeWindow('img', 640, 480)
    cv2.imshow('img', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def segment(img, file_name, result_split_path, step_x_n, step_y_n, crop_img_w_n, crop_img_h_n):

    if not os.path.exists(result_split_path):
        os.makedirs(result_split_path)

    step_x = int(img.shape[0] / step_x_n)
    step_y = int(img.shape[1] / step_y_n)
    crop_img_w = int(img.shape[0] / crop_img_w_n)
    crop_img_h = int(img.shape[1] / crop_img_h_n)
    point_x_list = list(range(0, img.shape[0]-crop_img_w, step_x))
    point_y_list = list(range(0, img.shape[1]-crop_img_h, step_y))
    count = 0
    for i in point_x_list:
        for j in point_y_list:
            if i == point_x_list[-1]:
                crop_img = img[i:img.shape[0], j:j+crop_img_h, :]
            else:
                crop_img = img[i:i+crop_img_w, j:j+crop_img_h, :]
            cv2.imwrite(result_split_path + '%s_%s.jpg'%(file_name, count), crop_img)
            count += 1
    for i in point_x_list:
        if i == point_x_list[-1]:
            crop_img == img[i:img.shape[0], img.shape[1]-crop_img_h:img.shape[1], :]
        else:
            crop_img == img[i:i+crop_img_w, img.shape[1]-crop_img_h:img.shape[1], :]
        cv2.imwrite(result_split_path[:-4] + '%s_%s.jpg'%(file_name, count), crop_img)
        count += 1


def get_dst_img(file_name):
    src = cv2.imread(file_name)
    ret, thresh1 = cv2.threshold(src, 0, 255, cv2.THRESH_BINARY)  # binary (黑白二值)
    count = 0
    for i in list(range(src.shape[0] - 1, -1, -1)):
        if thresh1[i, 0][0] == 255:
            count = i
            break
   
    dst = src[0:count - 1, 0:src.shape[1], :]
    return dst

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--img_path', default='./dataset/', help='the path of dataset')
    parser.add_argument('--out_path', default='./dataset/', help='the path of  result_split_images')
    parser.add_argument('--step_x_n',type=int, default=6, help='the step of vertical direction')
    parser.add_argument('--step_y_n',type=int, default=24, help='the step of horizontal direction')
    parser.add_argument('--crop_img_w_n', type=int, default=3, help='the height of crop_image split numbers')
    parser.add_argument('--crop_img_h_n', type=int, default=6, help='the width of crop_image split numbers')
    opt = parser.parse_args()
    file_list = os.listdir(opt.img_path)
    result_split_path = opt.out_path
    step_x_n = opt.step_x_n
    step_y_n = opt.step_y_n
    crop_img_w_n = opt.crop_img_w_n
    crop_img_h_n = opt.crop_img_h_n
    for file_name in file_list:
        dst = get_dst_img(os.path.join(opt.img_path, file_name))
        print(dst.shape)
        segment(dst, file_name, result_split_path, step_x_n, step_y_n, crop_img_w_n, crop_img_h_n)

if __name__ == "__main__":
    main()

#the running sample of script:
#python segmention.py --img_path ./short_circuit/ --out_path ./workplace/short_circuit/
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要批量编号并将图片裁剪后保存指定文件夹,你可以使用Python的PIL库和os库。以下是一个示例代码: ```python import os from PIL import Image # 指定原始文件夹路径和目标文件夹路径 original_folder = 'path/to/original_folder' target_folder = 'path/to/target_folder' # 获取原始文件夹中的所有图片文件 image_files = [f for f in os.listdir(original_folder) if f.endswith(('.jpg', '.jpeg', '.png'))] # 遍历图片文件 for i, image_file in enumerate(image_files): # 构建新的文件名 new_filename = f'{i+1:03d}.jpg' # 例如:001.jpg # 打开图片 image = Image.open(os.path.join(original_folder, image_file)) # 裁剪图片(这里以示例裁剪为正方形,你可以根据需要自定义裁剪区域) width, height = image.size min_dim = min(width, height) crop_box = (0, 0, min_dim, min_dim) cropped_image = image.crop(crop_box) # 保存裁剪后的图片到目标文件夹 cropped_image.save(os.path.join(target_folder, new_filename), 'JPEG') # 关闭打开的图片文件 image.close() ``` 在这段代码中,你需要将 `original_folder` 替换为原始图片文件夹的路径,将 `target_folder` 替换为目标文件夹的路径。代码会遍历原始文件夹中的所有图片文件,并将它们按照顺序编号,并进行裁剪后保存目标文件夹。 请确保在运行代码之前已经安装了PIL库,可以使用以下命令进行安装: ``` pip install pillow ``` 希望对你有帮助!如有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

资料加载中

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值