-
Notifications
You must be signed in to change notification settings - Fork 1
/
Fabric_Defects_Detector.py
536 lines (466 loc) · 22.2 KB
/
Fabric_Defects_Detector.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 5.6
# in conjunction with Tcl version 8.6
# Nov 03, 2020 03:26:47 AM IST platform: Windows NT
import sys
import cv2
import numpy as np
import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk
from tkinter import messagebox, filedialog
import Support_Module
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
Support_Module.set_Tk_var()
top = Toplevel1(root)
Support_Module.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(rt, *args, **kwargs):
'''Starting point when module is imported by another module.
Correct form of call: 'create_Toplevel1(root, *args, **kwargs)' .'''
global w, w_win, root
#rt = root
root = rt
w = tk.Toplevel(root)
Support_Module.set_Tk_var()
top = Toplevel1(w)
Support_Module.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
# Declare global vars
global img
global cap
global minPiece, pxcm
global count, loss, total
global hasStarted
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
top.geometry("500x660+400+9")
top.minsize(120, 1)
top.maxsize(1370, 749)
top.resizable(0, 0)
top.title("Fabric Defect Detector")
top.configure(background="#d9d9d9")
top.configure(highlightbackground="#d9d9d9")
top.configure(highlightcolor="black")
self.ImgBoxInput = tk.Label(top)
self.ImgBoxInput.place(relx=0.12, rely=0.015, height=380, width=380)
self.ImgBoxInput.configure(activebackground="#f9f9f9")
self.ImgBoxInput.configure(activeforeground="black")
self.ImgBoxInput.configure(background="#b4b4b4")
self.ImgBoxInput.configure(disabledforeground="#a3a3a3")
self.ImgBoxInput.configure(foreground="#000000")
self.ImgBoxInput.configure(highlightbackground="#d9d9d9")
self.ImgBoxInput.configure(highlightcolor="black")
self.ImgBoxInput.configure(text='''No Input''')
self.Frame1 = tk.Frame(top)
self.Frame1.place(relx=0.12, rely=0.606,
relheight=0.061, relwidth=0.76)
self.Frame1.configure(relief='groove')
self.Frame1.configure(borderwidth="2")
self.Frame1.configure(relief="groove")
self.Frame1.configure(background="#d9d9d9")
self.Frame1.configure(highlightbackground="#d9d9d9")
self.Frame1.configure(highlightcolor="black")
self.RadRGB = tk.Radiobutton(self.Frame1)
self.RadRGB.place(relx=0.1, rely=0.2,
relheight=0.65, relwidth=0.2)
self.RadRGB.configure(activebackground="#d9d9d9")
self.RadRGB.configure(activeforeground="#000000")
self.RadRGB.configure(background="#d9d9d9")
self.RadRGB.configure(disabledforeground="#a3a3a3")
self.RadRGB.configure(foreground="#000000")
self.RadRGB.configure(highlightbackground="#d9d9d9")
self.RadRGB.configure(highlightcolor="black")
self.RadRGB.configure(justify='left')
self.RadRGB.configure(text='''RGB''')
self.RadRGB.configure(value=0)
self.RadRGB.configure(anchor="w")
self.RadRGB.configure(
variable=Support_Module.radColor)
self.RadGray = tk.Radiobutton(self.Frame1)
self.RadGray.place(relx=0.4, rely=0.2,
relheight=0.65, relwidth=0.2)
self.RadGray.configure(activebackground="#d9d9d9")
self.RadGray.configure(activeforeground="#000000")
self.RadGray.configure(background="#d9d9d9")
self.RadGray.configure(disabledforeground="#a3a3a3")
self.RadGray.configure(foreground="#000000")
self.RadGray.configure(highlightbackground="#d9d9d9")
self.RadGray.configure(highlightcolor="black")
self.RadGray.configure(justify='left')
self.RadGray.configure(text='''Grayscale''')
self.RadGray.configure(value=1)
self.RadGray.configure(anchor="w")
self.RadGray.configure(
variable=Support_Module.radColor)
self.RadBinary = tk.Radiobutton(self.Frame1)
self.RadBinary.place(relx=0.7, rely=0.2,
relheight=0.65, relwidth=0.2)
self.RadBinary.configure(activebackground="#d9d9d9")
self.RadBinary.configure(activeforeground="#000000")
self.RadBinary.configure(background="#d9d9d9")
self.RadBinary.configure(disabledforeground="#a3a3a3")
self.RadBinary.configure(foreground="#000000")
self.RadBinary.configure(highlightbackground="#d9d9d9")
self.RadBinary.configure(highlightcolor="black")
self.RadBinary.configure(justify='left')
self.RadBinary.configure(text='''Binary''')
self.RadBinary.configure(value=2)
self.RadBinary.configure(anchor="w")
self.RadBinary.configure(
variable=Support_Module.radColor)
self.Frame2 = tk.Frame(top)
self.Frame2.place(relx=0.12, rely=0.674,
relheight=0.061, relwidth=0.76)
self.Frame2.configure(relief='groove')
self.Frame2.configure(borderwidth="2")
self.Frame2.configure(relief="groove")
self.Frame2.configure(background="#d9d9d9")
self.Frame2.configure(highlightbackground="#d9d9d9")
self.Frame2.configure(highlightcolor="black")
self.RadOriginal = tk.Radiobutton(self.Frame2)
self.RadOriginal.place(relx=0.1, rely=0.2,
relheight=0.625, relwidth=0.2)
self.RadOriginal.configure(activebackground="#d9d9d9")
self.RadOriginal.configure(activeforeground="#000000")
self.RadOriginal.configure(background="#d9d9d9")
self.RadOriginal.configure(disabledforeground="#a3a3a3")
self.RadOriginal.configure(foreground="#000000")
self.RadOriginal.configure(highlightbackground="#d9d9d9")
self.RadOriginal.configure(highlightcolor="black")
self.RadOriginal.configure(justify='left')
self.RadOriginal.configure(text='''Original''')
self.RadOriginal.configure(value=1)
self.RadOriginal.configure(anchor="w")
self.RadOriginal.configure(
variable=Support_Module.radType)
self.RadDefects = tk.Radiobutton(self.Frame2)
self.RadDefects.place(relx=0.4, rely=0.2,
relheight=0.625, relwidth=0.2)
self.RadDefects.configure(activebackground="#d9d9d9")
self.RadDefects.configure(activeforeground="#000000")
self.RadDefects.configure(background="#d9d9d9")
self.RadDefects.configure(disabledforeground="#a3a3a3")
self.RadDefects.configure(foreground="#000000")
self.RadDefects.configure(highlightbackground="#d9d9d9")
self.RadDefects.configure(highlightcolor="black")
self.RadDefects.configure(justify='left')
self.RadDefects.configure(text='''Defects''')
self.RadDefects.configure(value=0)
self.RadDefects.configure(anchor="w")
self.RadDefects.configure(
variable=Support_Module.radType)
self.RadWastage = tk.Radiobutton(self.Frame2)
self.RadWastage.place(relx=0.7, rely=0.2,
relheight=0.625, relwidth=0.2)
self.RadWastage.configure(activebackground="#d9d9d9")
self.RadWastage.configure(activeforeground="#000000")
self.RadWastage.configure(background="#d9d9d9")
self.RadWastage.configure(disabledforeground="#a3a3a3")
self.RadWastage.configure(foreground="#000000")
self.RadWastage.configure(highlightbackground="#d9d9d9")
self.RadWastage.configure(highlightcolor="black")
self.RadWastage.configure(justify='left')
self.RadWastage.configure(text='''Wastage''')
self.RadWastage.configure(value=2)
self.RadWastage.configure(anchor="w")
self.RadWastage.configure(
variable=Support_Module.radType)
self.Frame3 = tk.Frame(top)
self.Frame3.place(relx=0.12, rely=0.742,
relheight=0.242, relwidth=0.76)
self.Frame3.configure(relief='groove')
self.Frame3.configure(borderwidth="2")
self.Frame3.configure(relief="groove")
self.Frame3.configure(background="#d9d9d9")
self.Frame3.configure(highlightbackground="#d9d9d9")
self.Frame3.configure(highlightcolor="black")
self.txtPxCm = tk.Entry(self.Frame3)
self.txtPxCm.place(relx=0.421, rely=0.063, height=20, width=150)
self.txtPxCm.configure(background="white")
self.txtPxCm.configure(disabledforeground="#a3a3a3")
self.txtPxCm.configure(font="TkFixedFont")
self.txtPxCm.configure(foreground="#000000")
self.txtPxCm.configure(highlightbackground="#d9d9d9")
self.txtPxCm.configure(highlightcolor="black")
self.txtPxCm.configure(insertbackground="black")
self.txtPxCm.configure(selectbackground="blue")
self.txtPxCm.configure(selectforeground="white")
self.Label1 = tk.Label(self.Frame3)
self.Label1.place(relx=0.053, rely=0.063, height=21, width=130)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''Pixels per unit length:''')
self.Label1.configure(anchor="w")
self.Label2 = tk.Label(self.Frame3)
self.Label2.place(relx=0.053, rely=0.25, height=21, width=130)
self.Label2.configure(activebackground="#f9f9f9")
self.Label2.configure(activeforeground="black")
self.Label2.configure(background="#d9d9d9")
self.Label2.configure(disabledforeground="#a3a3a3")
self.Label2.configure(foreground="#000000")
self.Label2.configure(highlightbackground="#d9d9d9")
self.Label2.configure(highlightcolor="black")
self.Label2.configure(text='''Minimum piece length:''')
self.Label2.configure(anchor="w")
self.txtPiece = tk.Entry(self.Frame3)
self.txtPiece.place(relx=0.421, rely=0.25, height=21, width=150)
self.txtPiece.configure(background="white")
self.txtPiece.configure(disabledforeground="#a3a3a3")
self.txtPiece.configure(font="TkFixedFont")
self.txtPiece.configure(foreground="#000000")
self.txtPiece.configure(highlightbackground="#d9d9d9")
self.txtPiece.configure(highlightcolor="black")
self.txtPiece.configure(insertbackground="black")
self.txtPiece.configure(selectbackground="blue")
self.txtPiece.configure(selectforeground="white")
self.btnStart = tk.Button(self.Frame3)
self.btnStart.place(relx=0.737, rely=0.781, height=24, width=80)
self.btnStart.configure(activebackground="#ececec")
self.btnStart.configure(activeforeground="#000000")
self.btnStart.configure(background="#d9d9d9")
self.btnStart.configure(command=self.btnStart_OnClick)
self.btnStart.configure(disabledforeground="#a3a3a3")
self.btnStart.configure(foreground="#000000")
self.btnStart.configure(highlightbackground="#d9d9d9")
self.btnStart.configure(highlightcolor="black")
self.btnStart.configure(pady="0")
self.btnStart.configure(relief="groove")
self.btnStart.configure(text='''Start''')
self.Label3 = tk.Label(self.Frame3)
self.Label3.place(relx=0.83, rely=0.25, height=21, width=40)
self.Label3.configure(activebackground="#f9f9f9")
self.Label3.configure(activeforeground="black")
self.Label3.configure(background="#d9d9d9")
self.Label3.configure(disabledforeground="#a3a3a3")
self.Label3.configure(foreground="#000000")
self.Label3.configure(highlightbackground="#d9d9d9")
self.Label3.configure(highlightcolor="black")
self.Label3.configure(text='''(units)''')
self.Label3.configure(anchor="w")
self.Label4 = tk.Label(self.Frame3)
self.Label4.place(relx=0.053, rely=0.438, height=21, width=130)
self.Label4.configure(activebackground="#f9f9f9")
self.Label4.configure(activeforeground="black")
self.Label4.configure(background="#d9d9d9")
self.Label4.configure(disabledforeground="#a3a3a3")
self.Label4.configure(foreground="#000000")
self.Label4.configure(highlightbackground="#d9d9d9")
self.Label4.configure(highlightcolor="black")
self.Label4.configure(text='''Number of defects:''')
self.Label4.configure(anchor="w")
self.Label5 = tk.Label(self.Frame3)
self.Label5.place(relx=0.053, rely=0.625, height=21, width=130)
self.Label5.configure(activebackground="#f9f9f9")
self.Label5.configure(activeforeground="black")
self.Label5.configure(background="#d9d9d9")
self.Label5.configure(disabledforeground="#a3a3a3")
self.Label5.configure(foreground="#000000")
self.Label5.configure(highlightbackground="#d9d9d9")
self.Label5.configure(highlightcolor="black")
self.Label5.configure(text='''Total units wasted:''')
self.Label5.configure(anchor="w")
self.lblDefects = tk.Label(self.Frame3)
self.lblDefects.place(relx=0.421, rely=0.438, height=21, width=150)
self.lblDefects.configure(activebackground="#f9f9f9")
self.lblDefects.configure(activeforeground="black")
self.lblDefects.configure(background="#d9d9d9")
self.lblDefects.configure(disabledforeground="#a3a3a3")
self.lblDefects.configure(foreground="#000000")
self.lblDefects.configure(highlightbackground="#d9d9d9")
self.lblDefects.configure(highlightcolor="black")
self.lblDefects.configure(text='''_''')
self.lblDefects.configure(anchor="w")
self.lblLoss = tk.Label(self.Frame3)
self.lblLoss.place(relx=0.421, rely=0.625, height=21, width=150)
self.lblLoss.configure(activebackground="#f9f9f9")
self.lblLoss.configure(activeforeground="black")
self.lblLoss.configure(background="#d9d9d9")
self.lblLoss.configure(disabledforeground="#a3a3a3")
self.lblLoss.configure(foreground="#000000")
self.lblLoss.configure(highlightbackground="#d9d9d9")
self.lblLoss.configure(highlightcolor="black")
self.lblLoss.configure(text='''_''')
self.lblLoss.configure(anchor="w")
# Initialize
self.img = None
self.hasStarted = False
def btnStart_OnClick(self):
# Check if a process is already running => If true, stop the process
if self.hasStarted:
self.hasStarted = False
else:
# Validation
val = True
try:
self.pxcm = int(self.txtPxCm.get())
except ValueError:
messagebox.showerror("Error", "Invalid pixels per unit length")
val = False
try:
self.minPiece = float(self.txtPiece.get())
except ValueError:
messagebox.showerror("Error", "Invalid minimum piece length")
val = False
if val == False:
return
# Show openFileDialog
filename = filedialog.askopenfilename(
initialdir="/", title="Select file", filetypes=(("Video files", ".jpg .mp4"), ("all files", "*.*")))
# Convert minPiece to number of pixels
self.minPiece = self.minPiece * self.pxcm
# Initialize
self.count = self.loss = self.total = 0
self.cap = cv2.VideoCapture(filename)
self.btnStart.configure(text='''Stop''')
self.hasStarted = True
self.detect()
def detect(self):
# Check if 'Stop' is pressed
if not self.hasStarted:
self.btnStart.configure(text='''Start''')
self.cap.release()
return
# Read a frame
ret, frame = self.cap.read()
# Image color => RGB (0), Gray (1), Binary (2)
imgColor = Support_Module.radColor.get()
# Image type => Defects (0), Original (1), Wastage (2)
imgType = Support_Module.radType.get()
# Check if the end of stream
if not ret:
print("Receiving frames failed. Exiting.")
self.btnStart.configure(text='''Start''')
self.cap.release()
self.hasStarted = False
return
# Get height, width of the frame
hh, ww = frame.shape[:2]
# Calc mid points
mid_l = int(hh / 2)
mid_u = mid_l + 20
# Convert to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Apply blur
blur = cv2.GaussianBlur(gray, (3, 3), 1)
# Convert to binary
thresh = cv2.threshold(blur, 100, 255, cv2.THRESH_BINARY_INV)[1]
# Apply morphological close operation
kernel = np.ones((13, 13), np.uint8)
clean = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# Calc contours
contours = cv2.findContours(
clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
# Create a copy based on the image color
if imgColor == 0:
fill_img = frame.copy()
elif imgColor == 1:
fill_img = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB)
else:
fill_img = cv2.cvtColor(thresh, cv2.COLOR_GRAY2RGB)
# Initialize
y11 = y12 = y21 = y22 = -1
l = len(contours) - 1
for i in range(l, -1, -1):
# Get the bounding rectangle
rect = cv2.boundingRect(contours[i])
x, y, w, h = rect
# Assign the values to y11, y12 if it is the first iterartion
if i == l:
y11, y12 = y, y + h
else:
# Assign the values to y21, y22
y21, y22 = y, y + h
# Check if the contour is inside or closer (based on minimum piece size) to the previoud contour. If true, merge the contours
if (y12 >= y21 and y22 > y12) or (y12 + self.minPiece) >= y21:
y12 = y22
else:
# Calc the center of the contour
center = int((y11+y12)/2)
# If the selected image type is 'Wastage'
if imgType == 2:
# Fill the rectangle
cv2.rectangle(fill_img, (0, y11),
(ww, y12), (255, 255, 255) if imgColor == 2 else (0, 0, 0), -1)
# Fill the center circle
cv2.circle(fill_img, (int(ww/2), center),
3, (0, 0, 255), -1)
# Check if the center of the contour is in between the mid points. If true, increase the count and calc the total wastage
if mid_l <= center < mid_u:
self.count = self.count + 1
self.loss = self.loss + y12 - y11
# Goto the next contour
y11, y12 = y21, y22
# Check if the selected image type is 'Defects'
if imgType == 0:
# Calc minimum rectangle area (rotated rectange) => center, size, angle
rotrect = cv2.minAreaRect(contours[i])
# Calc the box points
boxpts = np.int0(cv2.boxPoints(rotrect))
# Draw the box points
cv2.drawContours(fill_img, [boxpts], 0, (0, 255, 0), 2)
# Show a text next to the defect
if rect[2] > 10 and rect[3] > 10:
cv2.putText(fill_img, 'Defect Detected',
(x, y), 0, 0.3, (0, 0, 255))
# Check if the selected image type is 'Wastage'
elif imgType == 2:
# Fill the rectangle
cv2.rectangle(fill_img, (0, y11), (ww, y12), (255, 255, 255)
if imgColor == 2 else (0, 0, 0), -1)
# Calc the center of the contour
center = int((y11+y12)/2)
# Fill the center circle if a defect exists
if(center != -1):
cv2.circle(fill_img, (int(ww/2), center),
3, (0, 0, 255), -1)
# Draw the center line if the selected image type is not 'Original'
if imgType != 1:
cv2.line(fill_img, (0, mid_l), (ww, mid_l), (0, 0, 255))
# Calc the center of the contour
center = int((y11+y12)/2)
# Check if the center of the contour is in between the mid points. If true, increase the count and calc the total wastage
if mid_l <= center <= mid_u:
self.count = self.count + 1
self.loss = self.loss + y12 - y11
# Convert the image to RGBA so it can be displayed on the window
frameRGB = cv2.cvtColor(fill_img, cv2.COLOR_BGR2RGBA)
# Create Image object from the converted image (numpy array)
self.img = Image.fromarray(frameRGB)
# Resize
resized = self.img.resize((380, 380), Image.ANTIALIAS)
# Display the image
imgtk = ImageTk.PhotoImage(image=resized)
self.ImgBoxInput.imgtk = imgtk
self.ImgBoxInput.configure(image=imgtk)
# Display count and the total wastage
self.lblDefects.configure(text=self.count)
self.lblLoss.configure(text=(str(self.loss / self.pxcm) + ' units'))
# Run the method after 100ms
if self.hasStarted:
self.ImgBoxInput.after(100, self.detect)
if __name__ == '__main__':
vp_start_gui()