python:从众多.txt文件中删除 符合条件的指定行。np.loadtxt, np.savetxt

# -*- coding: utf-8 -*-
"""
将标签为1 的 person 删除

Created on Thu Feb 21 10:51:09 2019

@author: QinLong
"""

import os
import numpy as np 

label_path = 'F:\\Object_Detection\\Annotations\\txt\\'
new_label = 'F:\\Object_Detection\\Annotations\\delete_person\\'
label_name = os.listdir(label_path) #返回列表
new_name = label_name
label_data = []

for i in range(len(label_name)):
    new_name = label_name[i]
    label_name[i] = label_path + label_name[i]
    label_data = np.loadtxt(label_name[i])
    new_name = new_label + new_name
    
    if label_data.ndim == 1: #单行值 或 空文件
        if label_data.size > 0:#单行值
            if label_data[0] == 1:           
                with open(new_name,"a+") as f:
                   pass #记录

    else:
        d = []
        for j in range(len(label_data)):
            if label_data[j][0] == 1:
                d.append(j)
                
        if len(d): #非空
            label_data = np.delete(label_data, d, axis=0 )  #删除      
            with open(new_name,"a+") as f:
                #fmt : 设置多列保存格式
                np.savetxt(new_name,label_data,fmt=''.join(['%d'] + [' %0.6f']*4),delimiter='  ')               
                          

处理的数据是C语言版本的yolov3 的标签。将原先的三种类别减少为二种。因为排序问题:
三类别:

  1. traffic signs
  2. person
  3. car

改为二类别:

  1. traffic signs
  2. car

故先删除标签为1 的 person,然后将标签为2 的car 改为标签为1 。(yolo里面的设定如此)

你可能感兴趣的:(python,DL)