forked from SouravJohar/rock-paper-scissors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gather_images.py
93 lines (73 loc) · 2.15 KB
/
gather_images.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
desc = '''Script to gather data images with a particular label.
Usage: python gather_images.py <label_name> <num_samples>
The script will collect <num_samples> number of images and store them
in its own directory.
Only the portion of the image within the box displayed
will be captured and stored.
Press 'a' to start/pause the image collecting process.
Press 'q' to quit.
'''
import cv2
import os
import sys
import glob
try:
label_name = sys.argv[1]
num_samples = int(sys.argv[2])
except:
print("Arguments missing.")
print(desc)
exit(-1)
IMG_SAVE_PATH = 'image_data'
IMG_CLASS_PATH = os.path.join(IMG_SAVE_PATH, label_name)
last_id = 0
try:
os.mkdir(IMG_SAVE_PATH)
except FileExistsError:
pass
try:
os.mkdir(IMG_CLASS_PATH)
except FileExistsError:
print("{} directory already exists.".format(IMG_CLASS_PATH))
print("All images gathered will be saved along with existing items in this folder")
list_of_files = glob.glob(os.path.join(IMG_CLASS_PATH, '*'))
def comp(file):
try :
return int(os.path.splitext(file)[0].split('\\')[-1])
except ValueError:
return 0
latest_file = max(list_of_files, key=comp)
last_id = comp(latest_file)
cap = cv2.VideoCapture(0)
start = False
count = 0
reset_nb = 3
nb=0
while True:
ret, frame = cap.read()
if not ret:
continue
if count == num_samples:
break
cv2.rectangle(frame, (100, 100), (400, 400), (255, 255, 255), 2)
if start:
if nb==0 :
roi = frame[100:400, 100:400]
save_path = os.path.join(IMG_CLASS_PATH, '{}.jpg'.format(last_id + count + 1))
cv2.imwrite(save_path, roi)
count += 1
nb = reset_nb
else :
nb -= 1
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, "Collecting {}".format(count),
(50, 30), font, 0.7, (0, 0, 255), 2, cv2.LINE_AA)
cv2.imshow("Collecting images", frame)
k = cv2.waitKey(10)
if k == ord('a'):
start = not start
if k == ord('q'):
break
print("\n{} image(s) saved to {}".format(count, IMG_CLASS_PATH))
cap.release()
cv2.destroyAllWindows()