python常⽤程序代码(持续更新收集)⽂件夹遍历和⽂件遍历
# 遍历⽂件夹和⽂件,返回⽂件的路径和对应的⽂件的名称,同时可以根据⾃⼰的应⽤需要进⾏更改
def get_img_file(file_name):
imagelist = []
for parent, dirnames, filenames in os.walk(file_name):
for filename in filenames:
if filename.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff')):
imagelist.append(os.path.join(parent, filename))
return imagelist,filenames
只遍历当前⽂件或者只遍历当前⽂件夹
def GetDirectory(path):
directory=os.listdir(path)
directory_list=[]
for dirs in directory:
if not os.path.isfile(os.path.join(path,dirs)):
directory_list.append(os.path.join(path,dirs))
return directory_list
def GetFile(path):
files=os.listdir(path)
file_list=[]
for file in files:
if os.path.isfile(os.path.join(path,file)):
file_list.append(os.path.join(path,file))
return file_list
和上段代码的功能类似,遍历根⽬录下的所有⽂件夹和⽂件,只是这个是组个遍历,可以⼈为的调整和修改:
def preprocess(src_root, dst_root):
"""
:param src_root:
:param dst_root:
:return:
"""
if not os.path.isdir(src_root):
print("[Err]: invalid source root")
return
if not os.path.isdir(dst_root):
os.makedirs(dst_root)
print("{} made".format(dst_root))
# 创建⽤于训练MOT的⽬录结构
dst_img_dir_train = dst_root + '/images/train'
dst_img_dir_test = dst_root + '/images/test'
dst_labels_with_ids = dst_root + '/labels_with_ids'
if not os.path.isdir(dst_img_dir_train):
os.makedirs(dst_img_dir_train)
if not os.path.isdir(dst_img_dir_test):
os.makedirs(dst_img_dir_test)
if not os.path.isdir(dst_labels_with_ids):
os.makedirs(dst_labels_with_ids)
# 遍历src_root, 进⼀步完善训练⽬录并拷贝⽂件
for x in os.listdir(src_root):
x_path = src_root + '/' + x
if os.path.isdir(x_path):
for y in os.listdir(x_path):
dswith('.jpg'):
y_path = x_path + '/' + y
if os.path.isfile(y_path):
# 创建⽤于训练的图⽚⽬标⽬录
dst_img1_dir = dst_img_dir_train + '/' + x + '/img1'                        if not os.path.isdir(dst_img1_dir):
os.makedirs(dst_img1_dir)
# copy image to train image dir
dst_f_path = dst_img1_dir + y
if os.path.isfile(dst_f_path):
print('{} cp to {}'.format(y, dst_img1_dir))
else:
print('{} already exists.'.format(dst_f_path))
多张图⽚⽣成视频代码
def generate_video(path,size,fps=25):
# fps = 24                  #帧率
# size = (640, 480)
videowriter = cv2.VideoWriter("./resultout/test.mp4",cv2.VideoWriter_fourcc(*'mp4v'),fps,size)
#path = r'F:/data/predict_landmark/'
for rootpath, dirs, names in os.walk(path):
names.sort()
for name in names:
img = cv2.imread(os.path.join(rootpath, name))
print("--", name)
videowriter.write(img)
generate_video('./resultout/frame/',(1920, 1080),25)
删除⽂件和⽂件夹网页设计与制作教程的出版社
需要在执⾏某些代码前清空指定的⽂件夹,如果直接⽤os.remove(),可能出现因⽂件夹中⽂件被占⽤⽽⽆法删除,解决⽅法也很简单,先强制删除⽂件夹,再重新建同名⽂件夹即可
import shutil
<('要清空的⽂件夹名')
os.mkdir('要清空的⽂件夹名')
把⼀个⽂件从⼀个⽂件夹移动到另⼀个⽂件夹,并同时重命名,⽤shutil也很简单
同理⼀个⽂件夹的⽂件复制到另⼀个⽂件夹可以使⽤下⾯的代码:
数据集元素分割
这⾥有多种⽅式,先上⼀个简单的,然后来⼀个⽐较完全的。
def main():
random.seed(0)  # 设置随机种⼦,保证随机结果可复现
files_path = "F:\\车道线⼤图"
assert ists(files_path), "path: '{}' does not exist.".format(files_path)
val_rate = 0.5
# 读取数据,并遍历图⽚名称,通过'.'进⾏分割字符串,取第⼀部分,然后排序
files_name = sorted([file.split(".")[0] for file in os.listdir(files_path)])
files_num = len(files_name)
# ⽣成随机索引,k表⽰从输⼊的序列中随机选择k个⽆重复的元素
val_index = random.sample(range(0, files_num), k=int(files_num*val_rate))
train_files = []
个人博客和个人网站的区别
val_files = []
for index, file_name in enumerate(files_name):
if index in val_index:
val_files.append(file_name)
else:
train_files.append(file_name)
linux不到命令
try:
train_f = open("", "x")
eval_f = open("", "x")
train_f.write("\n".join(train_files))
eval_f.write("\n".join(val_files))
except FileExistsError as e:
print(e)
exit(1)
'''
Description: 学习使⽤
Version: 1.0
Author: 赵守风
Email: 1583769112@qq
Date: 2021-03-24 14:17:19
python三种注释方法LastEditors: zsf
LastEditTime: 2021-03-24 17:06:01
'''
import torch
import os
import random
import shutil
import math
'''
@description: 直接切分数据集,copy数据到对应的训练集、测试集和验证集,这⾥不考虑类别的问题@param {*} datapath: 原始数据路径
@param {*} rootpath: 保存切分后的路径root
@param {*} train_rate: 训练集占总数的百分⽐
@param {*} val_rate: 验证集占总数百分⽐
@param {*} test_rate: 测试集占总数的百分⽐
@return {*}
@author: zsf
'''
linux云服务器租用
def data_split(datapath, rootpath="./data_split", train_rate=0.8, val_rate=0.1, test_rate=0.1):
for parent, dirnames, filenames in os.walk(datapath):
for parent, dirnames, filenames in os.walk(datapath):
for dirname in dirnames:
filepaths = os.listdir(os.path.join(parent, dirname))
# 删除其他的⽂件
filepaths = [x for x in filepaths if x.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff')) ]                      # 开始切分
random.shuffle(filepaths)
for i in range(len(filepaths)):
if i < math.floor(train_rate*len(filepaths)):
sub_path = os.path.join(rootpath, 'train_set', dirname)
elif i < math.floor((train_rate+val_rate)*len(filepaths)):
sub_path = os.path.join(rootpath, 'val_set', dirname)
elif i < len(filepaths):
sub_path = os.path.join(rootpath, 'test_set', dirname)
if ists(sub_path) == 0:
os.makedirs(sub_path)
'''
@description: 这⾥⽣成对应的txt⽂件不挪动图⽚
@param {*} datapath: 原始数据路径
@param {*} rootpath: 保存切分后的路径root
@param {*} train_rate: 训练集占总数的百分⽐
@param {*} val_rate: 验证集占总数百分⽐
@param {*} test_rate: 测试集占总数的百分⽐
@return {*}
@author: zsf
'''
def data_split_txt(datapath, rootpath="./data_split", train_rate=0.8, val_rate=0.1, test_rate=0.1):
for parent, dirnames, filenames in os.walk(datapath):python基础代码大全加翻译
index = 0
for dirname in dirnames:
filepaths = os.listdir(os.path.join(parent, dirname))
# 删除其他的⽂件
filepaths = [x for x in filepaths if x.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff')) ]                      # 开始切分
random.shuffle(filepaths)
for i in range(len(filepaths)):
if i < math.floor(train_rate*len(filepaths)):
txt_path = ''
elif i < math.floor((train_rate+val_rate)*len(filepaths)):
txt_path = ''
elif i < len(filepaths):
txt_path = ''
with open(os.path.join(rootpath, txt_path), mode='a') as file:
file.write(str(index) + ' ' + os.path.join(datapath, dirname, filepaths[i]) + '\n')
index += 1
⼀张图⽚均匀切割

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。