-
Notifications
You must be signed in to change notification settings - Fork 6
/
datafilter.py
164 lines (142 loc) · 4.28 KB
/
datafilter.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
import cv2
import os, shutil
import glob
"""
Program to create a dataset for a hairstayle image-to-image translation task
"""
def show_face_detection(image, faces):
"""
Show an image with a rectangle draw that encloses the face
Args:
image: A loaded image
faces: 1D array list with four entries that specifies the bounding box of the detected face
"""
fig, ax = plt.subplots(1)
ax.imshow(image)
for (x, y, w, h) in faces:
ax.add_patch(patches.Rectangle((x, y), w, h, color='red', fill=False))
plt.show()
def image_selected(event, figure):
"""
Display on terminal the name of the image which was "clicked"
Arg:
figure: The matplot figure object created on PlotGridImages function
"""
axlist = figure.axes
global bad_images
for i in range(len(axlist)):
if axlist[i] == event.inaxes:
print("Image: ", img_list[i], " deleted.")
bad_images.append(i)
delete_image(img_list[i]) # Delete image from directory
#del img_list[i] # Delete image from list
def plot_grid(figures, nrows = 1, ncols=1, fullsize=False):
"""
Plot a dictionary of figures.
Args:
figures : <title, figure> dictionary
ncols : number of columns of subplots wanted in the display
nrows : number of rows of subplots wanted in the figure
"""
fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
for ind, title in zip(range(len(figures)), figures):
axeslist.ravel()[ind].imshow(figures[title])
axeslist.ravel()[ind].set_axis_off()
fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0.02)
fig.canvas.mpl_connect("button_press_event", lambda event: image_selected(event, fig))
if fullsize:
mng = plt.get_current_fig_manager()
mng.resize(*mng.window.maxsize())
plt.show()
def detect_face(image):
"""
Check for valid images, that is, images that contain only one detectable face.
Args:
image: Image path
"""
try:
img = cv2.imread(image)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
except:
print("Erronous image: ", image, " deleted.")
return False
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, 2)
#print('Number of faces detected:', len(faces))
#show_face_detection(img, faces)
return len(faces) == 1
def delete_image(image):
"""
Delete an image from your data directory
Args:
image: image path
"""
os.remove(image)
def get_set_images(dirname, imgtype, nimages):
"""
Create a grid of nimages and a list with their names.
Args:
dirname: dir path where the images are
imgtype: image type e.g png, jpg, jpeg. }
nimages: number of images
"""
images = glob.glob(dirname + '/*.' + imgtype)
grid = {}
valid_images = []
if len(images) < nimages:
print("There are not enough images, only: ", len(images), " are available.")
exit()
print(len(images))
i = 0
while nimages > 0:
image = images[i]
if detect_face(image):
try:
img = cv2.imread(image)
grid[image] = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
valid_images.append(image)
nimages -= 1
print("Image ", image, " #", i, " is valid. nimages: ", nimages)
except: # Erronous image
print("Erronous image ", image, " deleted.")
delete_image(image)
else: # Not valid image
print("Invalid image ", image, " deleted.")
delete_image(image)
i += 1
return valid_images, grid
def move_clean(images, destination):
"""
Move correct images to a clean data folder
Args:
Images: List of image paths (generated by get_set_images)
destination: path to the clean directory
"""
for image in images:
shutil.move(image, destination)
dirname = './data'
imgtype = 'jpg'
nimages = 25
columns = 5
rows = 5
bad_images = [] # Global variable
img_list, grid = get_set_images(dirname, imgtype, nimages)
plot_grid(grid, columns, rows, True)
while True:
for i in bad_images:
del img_list[i]
answer = input("You want to continue [y/n]: ")
if answer == 'y':
move_clean(img_list, dirname+'/clean-data')
img_list, grid = get_set_images(dirname, imgtype, nimages)
plot_grid(grid, columns, rows, True)
bad_images = []
elif answer == 'n':
print("See you!")
exit()
else:
print("Answer no valid")