1、快速提取数组或者字符串元素索引
coding 效率好低
2、标签数据列表转字符串
# 列表转字符串子函数
# import numpy as np,适合转换5位大小的列表
def num2str(num):
str1 = ''
a = np.array(num)
for index, element in np.ndenumerate(a):
if index[0] == 4 :
str1 = str1 +str(element) + ' '
else:
str1 = str1 + str(element) + ','
return str1
3、提取绝对路径中的文件名 扩展名等
import os
def path2name(image_path):
filepath, tmpfilename = os.path.split(image_path)
shortname, extension = os.path.splitext(tmpfilename)
return shortname
4、按照文件名中的数字对提取到的数据集文件进行排序
注意如果路径字符串中除了文件名称之外也含有数字的话要先把文件名提取出来
import re
def find_num(str):
return (int((re.findall(r'\d+',str))[0]))
mat_paths.sort(key=lambda x:find_num(x))
5、使用python对数组进行下采样
# 采样率downrate
# 创建索引数组
num = int(len(y)/8)
index = []
for i in range(num):
indexi = 4 + i*downrate
index.append(indexi)
ds_y = []
for i in range(len(index)):
ds_y.append(y[index[i]])
嗯?为啥要写这么多,我是个憨憨哈哈哈哈
y = y[0:len(y):4]
6、制作数据集时每张图片的路径循环方法
if i < 900:
fpath = 'D:/liangningbo/YOLOV3/data/dataset/train/'
else:
fpath = 'D:/liangningbo/YOLOV3/data/dataset/test/'
if 0<=i<=9:
path = fpath + '000' + str(i) + '.jpg'
elif 10<=i<=99:
path = fpath + '00' + str(i) + '.jpg'
elif 100<=i<=999:
path = fpath + '0'+ str(i) + '.jpg'
elif i == 1000:
path = fpath + '1000.jpg'
7、检验标签数组值是否正确
from PIL import ImageDraw
from PIL import Image, ImageFont
i = 6
image = Image.open(train_paths[i]) # 打开一张图片
draw = ImageDraw.Draw(image) # 在上面画画
labels = all_labels[i]
draw.rectangle([labels[0],labels[1],labels[2],labels[3]], outline=(255,0,0)) # [左上角x,左上角y,右下角x,右下角y],outline边框颜色
image.show()
8、.mat文件读取
from scipy import io as spio
data = spio.loadmat('D:/liangningbo/wifi/txWaveform_IQ_pnoise_NLs/txWaveform_IQ_pnoise_NL1.mat',struct_as_record=True)
# 注意这里x 读取到的其实是一个矩阵
x = data['txWaveform_IQ_pnoise_NL']
# 可以转化为数组进行数据采集 不过好像区别不大 矩阵数据也可以用来采样
# y = y.tolist()
9、提取对应路径下某格式所有文件
import glob
mat_paths = glob.glob('D:/liangningbo/wifi/txWaveform_IQ_pnoise_NLs/*.mat')
10、模型标签文件 路径批量修改
# 导入包
import os
# 根目录
dir_path = 'C:\\Users\\Administrator\\Desktop\\notebooks\\'
# 旧文件名
dir_name_old = 'barker_annotations copy.txt'
# 新建文件名
dir_name_new = 'barker_annotations_new.txt'
# 路径拼接
path_old = os.path.join(dir_path,dir_name_old)
path_new = os.path.join(dir_path,dir_name_new)
# 从旧文件中按照行读取替换后的文本
file_old = open(path_old,encoding='UTF-8')
ii = 0
new_line = []
accuracy_str1 = '/home/tf2-yolov3/image/BARKER_7'
error = 'D:/19种信号生成/image/BARKER_7'
while True:
line = file_old.readline()
if not line:
break
new_line.append(accuracy_str1 + line[len(error):])
ii = ii+1
file_old.close()
# 不断按行写入文本
file_new = open(path_new,'w',encoding='UTF-8')
for i in range(len(new_line)):
str1 = new_line[i]
file_new.write(str1)
file_new.close()