forked from HunterCQu/AITools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
img2train_with_check_img.py
69 lines (53 loc) · 1.71 KB
/
img2train_with_check_img.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-
# Author : Andy Liu
# Last modified: 2018-8-15
# This tool is used to create VOC-like txt file by reading image folder
# input: python create_txt_list.py "/home/andy/Data/img"
# output:
# ./train.txt
# ./val.txt
import argparse
import os,sys
import random
from os import listdir, getcwd
from os.path import join
import cv2
from tqdm import tqdm
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('srcdir', help='file directory', type=str)
args = parser.parse_args()
return args
def makelist(srcdir):
srcdir = os.path.abspath(srcdir)
if srcdir[-1] == "/":
srcdir = srcdir[:-1]
train_path_txt = "./train.txt"
val_path_txt = "./val.txt"
train_file=open(train_path_txt,'w+') # 'w+' rewrite, 'a' add
val_file=open(val_path_txt,'w+')
filelist = os.listdir(srcdir)
trainset = random.sample(filelist, int(len(filelist)*0.8))
for file in tqdm(filelist):
file_name,file_extend=os.path.splitext(file)
img_path = srcdir + "/" + file
img = cv2.imread(img_path)
if img is None:
print("%s can't read!"%file)
continue
if file in trainset:
train_file.write(srcdir+"/"+file+'\n')
else:
val_file.write(srcdir+"/"+file+'\n')
train_file.close()
val_file.close()
print("Path of train text = ",os.path.abspath(train_path_txt))
print("Path of valid text = ",os.path.abspath(val_path_txt))
if __name__ == '__main__':
args = parse_args()
srcdir = args.srcdir
if not os.path.exists(srcdir):
print("Error !!! %s is not exists, please check the parameter"%srcdir)
sys.exit(0)
makelist(srcdir)
print("Done!")