目录

 

1.将单张图片裁剪为若干份存入文件夹

2.将多张图片裁剪为若干份存入多个文件夹


 

1.将单张图片裁剪为若干份存入文件夹

核心代码(将单张图片进行裁剪的算法)

以裁剪为60*60的图片为例

import cv2
import os

# 需要裁剪的图片路径
filename = 'D:/resource_photo/1.jpg'
# 读取图片
img = cv2.imread(filename)
# 获取图片的宽和高,并计算其能裁剪为多少张60*60的图片
width=img.shape[1]
height=img.shape[0]
if width >= height:
    a = int(width/60)
else:
    a = int(height/60)
# 创建文件夹
os.mkdir("img_crop")
filename2 = 'img_crop'

for j in range(1, a+1):
    m = j - 1
    for k in range(1, a+1):
        n = k - 1
        cropped = img[(m * 60):(j * 60), (n * 60):(k * 60)]  # 按坐标裁剪,坐标为[y0:y1, x0:x1]
        img_name2 = str(j) + str(k)
        cv2.imwrite(filename2 + "/" + img_name2 + ".jpg", cropped)

运行结果:

 

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6ZW_5byT5ZCM5a2m,size_20,color_FFFFFF,t_70,g_se,x_16

 

2.将多张图片裁剪为若干份存入多个文件夹

将上面的核心代码进行模块化,并补全给完成后的每个文件夹中图片进行重命名方便后续使用。

得到以下代码:

import cv2
import os
import sys


def crop(img,b,filename2):

    # 获取图片的宽和高,并计算其能裁剪为多少张60*60的图片
    width = img.shape[1]
    height = img.shape[0]
    if width >= height:
        a = int(width / 60)
    else:
        a = int(height / 60)

    # 对图片进行裁剪
    for j in range(1, a+1):
        m = j-1
        for k in range(1,a+1):
            n = k-1
            cropped = img[(m*60):(j*60), (n*60):(k*60)]  # 按坐标裁剪,坐标为[y0:y1, x0:x1]
            img_name2 = str(b)+'_'+str(j)+str(k)
            cv2.imwrite(filename2+"/"+img_name2+".png", cropped)

def refilename(filename,i):
    fileList = os.listdir(filename)
    currentpath = os.getcwd()
    os.chdir(filename)
    num = 1
    # 遍历文件夹中所有文件
    for fileName in fileList:
        os.rename(fileName, (str(num) + '.png'))
        num = num + 1
    print("img"+str(i)+"切割完成")
    # 改回程序运行前的工作目录
    os.chdir(currentpath)
    # 刷新
    sys.stdin.flush()

if __name__ == '__main__':

    filename = 'C:/Users/10230/Desktop/resource_photo'
    # 更改图片名称为顺序数字
    # refilename(filename)
    for i in range(0,2):
        a=i+1
        b=i+1
        img_name = str(a)
        img = cv2.imread(filename+"/"+img_name+".png")
        os.mkdir("img"+str(i+1)+"_crop")
        filename2 = 'img'+str(i+1)+"_crop"
        crop(img, b, filename2)
        refilename(filename2,i)

运行结果:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6ZW_5byT5ZCM5a2m,size_10,color_FFFFFF,t_70,g_se,x_16

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6ZW_5byT5ZCM5a2m,size_20,color_FFFFFF,t_70,g_se,x_16

 

 原图为:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6ZW_5byT5ZCM5a2m,size_16,color_FFFFFF,t_70,g_se,x_16