一 无人机照片分割:
from importlib.resources import path
from lib2to3.pgen2.pgen import PgenGrammar
from cv2 import cv2
import numpy as np
import os
name = os.listdir("D:/XXX/Image")
print(name)
pic_path = 'D:/XXX/Image/'# 分割的图片的位置
pic_target = 'D:\\XXX\\Split\\' # 分割后的图片保存的文件夹
#要分割后的尺寸
cut_width = 512
cut_length = 512
#读取要分割的图片,以及其尺寸等数据
picture = cv2.imread(pic_path+name[0])
(width, length, depth) = picture.shape
#预处理生成0矩阵
pic = np.zeros((cut_width, cut_length, depth))
#计算可以划分的横纵的个数
num_width = int(width / cut_width)
num_length = int(length / cut_length)
print(num_width,num_length)
#for循环迭代生成
for n in range(len(name)):
pictures=cv2.imread(pic_path+name[n])
print(str(n)+"/"+str(name))
print(pic_path+name[n])
for i in range(0, num_width):
for j in range(0, num_length):
pic = pictures[i*cut_width : (i+1)*cut_width, j*cut_length : (j+1)*cut_length, :]
result_path = pic_target + '{}_{}_{}.jpg'.format(name2,i+1, j+1)
cv2.imwrite(result_path, pic)
print("done!!!")
源代码参照于:图片分割和图片合成(大图切割成小图,python代码)
二、划分数据集
""" Python将样本划分为训练集/验证集/测试集 """
import os, random, shutil
path = "D:/XXX/Split"
new_path = "D:/XXX/Data/Test"
n = 1
for root, dirs, files in os.walk(path):
fileNumber = len(files)
rate = 0.01
pickNumber = int(rate * fileNumber)
sample = random.sample(files, pickNumber)
for name in sample:
print(str(n)+"/"+str(pickNumber))
file_path = root + '/' + name
new_file_path = new_path + '/' + name
shutil.move(file_path, new_file_path)
n +=1