-
Notifications
You must be signed in to change notification settings - Fork 0
/
GUI.py
3899 lines (3232 loc) · 188 KB
/
GUI.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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
import csv
import time
from tesserocr import PyTessBaseAPI, RIL, iterate_level
from tkFileDialog import askopenfilename, askdirectory
import Levenshtein # may or may not be used
import cv2
import numpy as np
from PIL import ImageTk, Image
from scipy import ndimage as ndi
from skimage import feature
from skimage.filters import threshold_adaptive
import re
import collections
import pprint
import os
import pickle
import Segmentation # requires you to download Segmentation.py from our github repository
from random import shuffle
import math
class simpleapp_tk(Tkinter.Tk):
def __init__(self, parent): # constructor
Tkinter.Tk.__init__(self, parent)
self.parent = parent # keep track of our parent
self.initialize()
self.asn_data = []
self.match_instance = 0
self.ASN_loaded = False
def setMatcher(self, matcher_instance):
self.match_instance = matcher_instance
def initialize(self): # will be used for creating all the widgets
self.width = 400
self.height = 400
self.method = "Hybrid" # default
self.grid() # add things here later
# button for loading input images
button1 = Tkinter.Button(self, text=u"Load image !", command=self.OnButtonClickLoad)
button1.grid(column=0, row=1)
# button for loading Advance Shipment Notice
button3 = Tkinter.Button(self, text=u"Load ASN !", command=self.OnButtonClickASN)
button3.grid(column=2, row=1)
# label for displaying raw images
img = np.zeros((self.height, self.width), dtype='uint8') # default is just a black image
img = Image.fromarray(img)
img = ImageTk.PhotoImage(img)
self.label1 = Tkinter.Label(self, image=img)
self.label1.image = img
self.label1.grid(column=0, row=0)
# label for displaying processed image
self.label2 = Tkinter.Label(self, image=img)
self.label2.image = img
self.label2.grid(column=1, row=0)
# label for displaying text output
# self.displayVar = Tkinter.StringVar()
# self.displayVar.set("OCR output will be displayed here!")
self.label3 = Tkinter.Label(self, text="OCR output will be displayed here!") # text vs textvariable
self.label3.grid(column=2, row=0)
# label for displaying candidates
# self.displayCands = Tkinter.StringVar()
# self.displayCands.set("Candidates will be displayed here! (to be implemented)")
self.label4 = Tkinter.Label(self, text="Candidates will be displayed here!")
self.label4.grid(column=0, row=2)
# dropdown menu for selecting image processing procedure
optionList = ["Hybrid", "PrintedBoxesFullSystem", "Adaptive Thresholding", "WholeBoxReprocessSA", "WholeBoxWithKNN", "SARemoveIC", "cv2AdaptiveMean", "cv2AdaptiveGaussian", "AccItemCTest", "AdaptiveParameterExperiment", "HybridItemCTest", "AdaptiveWholeBoxTest", "ReprocessSA", "Advanced", "Basic", "ContourGaussianKernelOtsu", "GaussianKernelAndOtsu", "Otsu"] # add more later
self.dropVar = Tkinter.StringVar()
self.dropVar.set("Hybrid") # default
self.dropMenu1 = Tkinter.OptionMenu(self, self.dropVar, *optionList, command=self.func)
self.dropMenu1.grid(column=1, row=1)
self.grid_columnconfigure(0, weight=1)
self.resizable(True, False)
self.update()
self.geometry(self.geometry())
def OnButtonClickASN(self):
CSVName = askopenfilename()
loader = CSVLoader(CSVName)
self.asn_data = loader.Load() # what is the data needed for?
if len(self.asn_data) > 0:
self.ASN_loaded = True
self.match_instance = matcher(self.asn_data)
def OnButtonClickLoad(self):
filename = askopenfilename() # prompts user to choose a file
self.filename = filename
img2 = Image.open(filename) # what if user cancelled?
img2 = img2.resize((self.width, self.height), Image.ANTIALIAS)
img2 = ImageTk.PhotoImage(img2)
self.label1.config(image=img2)
self.label1.image = img2
processor = img_processor(self.filename) # need to pass on filename
if self.method in "Basic":
text, img = processor.Benchmark() # will later update to use the method chosen in drop-down menu
self.DisplayProcessed(img.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text) # implement later
elif self.method in "Advanced":
text, img = processor.Advanced()
self.DisplayProcessed(img.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text)
elif self.method in "Otsu":
text, img = processor.Otsu()
self.DisplayProcessed(img.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text)
elif self.method in "GaussianKernelAndOtsu":
text, img = processor.GaussianKernelAndOtsu()
self.DisplayProcessed(img.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text)
elif self.method in "ContourGaussianKernelOtsu":
text, img = processor.ContourGaussianKernelOtsu()
self.DisplayProcessed(img.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text)
elif self.method in "Hybrid":
text, boxes, img = processor.Hybrid() # and what to do about the iterator?
img_pic = Image.fromarray(img)
self.DisplayProcessed(img_pic.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text)
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
# at this point, want to look for candidates, but only if the ASN has already been loaded
# keep it optional for now to load ASN, in order to faciliate testing
if self.ASN_loaded:
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(text, categories)
# itemcode_cands, itemcode_indeces = self.match_instance.boxFinder(text, categories, img, boxes)
# print itemcode_cands
# self.DisplayCands(itemcode_cands)
index_solid = categories['Solidcode']
edge_adjustment = 10 # pixels # introduces issues of out of bound of arrays in rare cases
coordinates = boxes[index_solid]
x_top_left = 0
# x_top_left = max(coordinates[0] - edge_adjustment, 0)
y_top_left = max(coordinates[1] - edge_adjustment, 0)
x_bottom_right = img.shape[0]
# x_bottom_right = min(coordinates[2] + edge_adjustment, img.shape[0])
y_bottom_right = min(coordinates[3] + edge_adjustment, img.shape[1])
img = cv2.imread(filename)
solidcode_arr = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right, :]
Image.fromarray(solidcode_arr).save('solidslice.png')
elif self.method in "Adaptive Thresholding":
text, boxes, img = processor.AdaptiveThresholding()
img_pic = Image.fromarray(img)
self.DisplayProcessed(img_pic.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text)
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
if self.ASN_loaded:
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(text, categories)
# itemcode_cands, itemcode_indeces = self.match_instance.boxFinder(text, categories, img, boxes)
# print itemcode_cands
# self.DisplayCands(itemcode_cands)
if skip_segmentation:
solidassort = text[categories['Solidcode']]
print "Solid/assort code: " + str(solidassort)
print solidassort_indeces
print itemcode_indeces
# print which line from ASN it corresponds to.
for element in solidassort_indeces:
if element in itemcode_indeces:
print element
print "Found the box"
else: # will need to do segmentation
print "Itemcode indeces: "
print itemcode_indeces
index_solid = categories['Solidcode']
edge_adjustment = 10 # pixels # introduces issues of out of bound of arrays in rare cases
coordinates = boxes[index_solid]
# x_top_left = max(coordinates[0] - edge_adjustment, 0)
x_top_left = 0
y_top_left = max(coordinates[1] - edge_adjustment, 0)
# x_bottom_right = min(coordinates[2] + edge_adjustment, img.shape[0])
x_bottom_right = img.shape[0]
y_bottom_right = min(coordinates[3] + edge_adjustment, img.shape[1])
img = cv2.imread(filename)
solidcode_arr = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right, :]
Image.fromarray(solidcode_arr).save('solidslice.png')
elif self.method in "HybridItemCTest":
if self.ASN_loaded:
directory = askdirectory()
count_attempts = 0
count_correct = 0
count_correct_not_unique = 0
errors = []
not_unique_but_correct = []
for filename in os.listdir(directory):
if filename.endswith(".JPG"):
count_attempts += 1
# img_read = cv2.imread(os.path.join(directory,filename))
processor = img_processor(os.path.join(directory, filename))
text, boxes, img = processor.Hybrid()
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(text,
categories) # need to add accuracy check
correct_index = self.match_instance.correctFinder(filename)
# print itemcode_indeces
# print "Correct index: " + str(correct_index)
if (correct_index in itemcode_indeces) and unique_ic:
count_correct += 1
elif (correct_index in itemcode_indeces) and not unique_ic:
count_correct_not_unique += 1
not_unique_but_correct.append(filename)
else:
errors.append(filename)
print "Categories: "
print categories
print "Text: "
print text
print "Images processed: " + str(count_attempts)
print "Correctly determined the itemcode: " + str(count_correct)
print "Line level accuracy solid code: " + str(100.0 * count_correct / count_attempts)
print "Overall, the number of ICs that were not uniquely determined was: " + str(
count_correct_not_unique)
print "This was applicable to the following images: "
print not_unique_but_correct
print "May want to look into the following files: "
print errors
else:
print "Please load ASN before doing accuracy tests m8"
elif self.method in "WholeBoxWithKNN":
pick_path = "/Users/sigurdandersberg/PycharmProjects/proj1/Tests/picklewithlist.pickle"
if self.ASN_loaded:
directory = askdirectory()
order = pickle.load(open(pick_path))
count_attempts = 0
count_correct_ic = 0
count_correct_sa = 0
count_correct_box = 0
not_unique_but_correct = []
# errors = []
count_correct_not_unique = 0
errors_ic = []
errors_sa = []
for filename in order:
count_attempts += 1
processor = img_processor(os.path.join(directory, filename))
text, boxes, img = processor.AdaptiveThresholding()
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(
text, categories) # need to add accuracy check
correct_index = self.match_instance.correctFinder(filename)
index_ic = categories['Itemcode']
index_sa = categories['Solidcode']
# need to make adjustments, taking blank text lines into account and their missing bounding rectangles.
index_sa_adjusted = index_sa
sa_adjustment = 0
for x in xrange(0, index_sa):
line_before = text[x].replace("\n", "")
if len(line_before) == 0:
sa_adjustment += 1
index_sa_adjusted = index_sa - sa_adjustment
# find the IC adjustment next:
ic_adjustment = 0
for x in xrange(0, index_ic):
line_before = text[x].replace("\n", "")
if len(line_before) == 0:
ic_adjustment += 1
# index_ic_for_comparison = index_ic - sa_adjustment
index_ic_for_comparison = index_ic - ic_adjustment
index_sa = index_sa_adjusted # make sure that text is not being accessed after this point!
coordinates = boxes[index_sa]
x_top_left = 0
y_top_left = coordinates[1]
x_bottom_right = img.shape[1] # assuming x,y are reversed (order) by cv2 image reader.
y_bottom_right = coordinates[3] + int(0.01 * img.shape[0]) # too much?
# also needed: improved logic for finding the proper index of SA
# check: any lines w/ small vertical height near the IC?
if type(categories['Itemcode']) is not bool:
ic_height = boxes[categories['Itemcode']][3] - boxes[categories['Itemcode']][1]
height_threshold = int(0.30 * ic_height)
else:
height_threshold = 20
if (index_sa - index_ic_for_comparison) > 1:
if (boxes[index_sa - 1][3] - boxes[index_sa - 1][1]) < height_threshold:
y_top_left = boxes[index_sa - 1][1]
if (index_sa - index_ic_for_comparison) > 2:
if (boxes[index_sa - 2][3] - boxes[index_sa - 2][1]) < height_threshold:
y_top_left = boxes[index_sa - 2][1]
if (index_sa - index_ic_for_comparison) > 3:
if (boxes[index_sa - 3][3] - boxes[index_sa - 3][1]) < height_threshold:
y_top_left = boxes[index_sa - 3][1]
elif index_sa - index_ic_for_comparison == 1: # i.e. directly belwo
pass
else:
print "SA above IC is impossible, something has gone wrong upstream!" # set to index_ic + 1 as default "best guess"
index_sa = index_ic_for_comparison + 1
y_top_left = boxes[index_sa][1]
y_bottom_right = boxes[index_sa][3]
img_snipped = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right]
Image.fromarray(img_snipped).save("solidslice.png")
# dimension_y, dimension_x = img.shape
# background = np.zeros((dimension_y, dimension_x), dtype='float32')
# background[y_top_left:y_bottom_right, x_top_left:x_bottom_right] = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right]
img_snipped_binary = img[y_top_left:y_bottom_right,
x_top_left:x_bottom_right] # in numpy array form
img_snipped_binary_for_tess = Image.fromarray(img_snipped_binary)
repro = reprocessor(img_snipped_binary_for_tess)
text_solid_assort = repro.SingleLineTess() # contains a single guess for the value
feed = []
feed.append(text_solid_assort)
sa_indices, min_dist = self.match_instance.saReprocessed(feed, itemcode_indeces)
if min_dist < 0.35: # need to adjust, and to make consistent along all the checks
skip_segmentation = True
# check repro against the ASN.
# here, update skip_segmentation (boolean), based on the output from the reprocessing of SA line
feed = []
feed.append(text[categories['Solidcode']])
sa_indices_original, dist_original = self.match_instance.saReprocessed(feed, itemcode_indeces)
# split into two streams, based on whether segmentation can be skipped or not
if not skip_segmentation:
solidcands = Segmentation.Fujisawa('solidslice.png')
print solidcands
sa_indices_from_segmentation, min_dist_from_segmentation = self.match_instance.saReprocessed(
solidcands, itemcode_indeces)
if (dist_original <= min_dist) and (dist_original <= min_dist_from_segmentation):
sa_verdict = sa_indices_original
elif (min_dist <= dist_original) and (min_dist <= min_dist_from_segmentation):
sa_verdict = sa_indices
else:
sa_verdict = sa_indices_from_segmentation
else:
if dist_original <= min_dist:
sa_verdict = sa_indices_original
else:
sa_verdict = sa_indices
print itemcode_indeces
print sa_verdict
# now, want to return the guesses of item code, solid/assort code and the entire box
unique_sa = self.match_instance.uniqueSA(itemcode_indeces, sa_verdict)
# sa_verdict contains all the indices we are looking for. Use matcher for this
if (correct_index in itemcode_indeces) and unique_ic:
count_correct_ic += 1
print "Found the correct Itemcode"
if (correct_index in sa_verdict) and unique_sa:
count_correct_box += 1
print "Found correct SKU!"
if (correct_index in sa_verdict) and unique_sa:
count_correct_sa += 1
if correct_index not in itemcode_indeces:
errors_ic.append(filename)
if correct_index not in sa_verdict:
errors_sa.append(filename)
# accuracies if don't want uniqueness:
if (correct_index in itemcode_indeces) and (correct_index in sa_verdict) and (not unique_sa or not unique_ic):
count_correct_not_unique += 1
not_unique_but_correct.append(filename)
print str(filename)
self.match_instance.removeDoneBox(correct_index)
print "Ended, awaiting next input"
print "Test completed! "
print "Correct IC: " + str(count_correct_ic) + " "
print "Correct SA: " + str(count_correct_sa) + " "
print "Correct overall, uniquely determined: " + str(count_correct_box) + " "
print "The corresponding accuracy is: " + str((1.0 * count_correct_box / count_attempts)) + " "
print "Correct overall but not unique: " + str(count_correct_not_unique) + " "
print "Errors IC: "
print errors_ic
print "Errors SA: "
print errors_sa
print "Not unique but correct: "
print not_unique_but_correct
elif self.method in "AdaptiveParameterExperiment":
offset_values = [8, 10, 12]
block_size_values = [161]
area_threshold_values = [300, 350, 400, 450, 500]
if self.ASN_loaded:
directory = askdirectory() # only ask once
for bs_val in block_size_values:
for os_val in offset_values:
for area_val in area_threshold_values:
time_begin = time.clock()
count_attempts = 0
count_correct = 0
count_correct_not_unique = 0
errors = []
not_unique_but_correct = []
for filename in os.listdir(directory):
if filename.endswith(".JPG"):
count_attempts += 1
# img_read = cv2.imread(os.path.join(directory,filename))
processor = img_processor(os.path.join(directory, filename))
text, boxes, img = processor.AdaptiveThresholdingExperiment(bs_val, os_val, area_val)
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(text,
categories) # need to add accuracy check
correct_index = self.match_instance.correctFinder(filename)
# print itemcode_indeces
# print "Correct index: " + str(correct_index)
if (correct_index in itemcode_indeces) and unique_ic:
count_correct += 1
elif (correct_index in itemcode_indeces) and not unique_ic:
count_correct_not_unique += 1
not_unique_but_correct.append(filename)
else:
errors.append(filename)
print "Categories: "
print categories
print "Text: "
print text
print "Images processed: " + str(count_attempts)
print "Correctly determined the itemcode: " + str(count_correct)
print "Line level accuracy solid code: " + str(100.0 * count_correct / count_attempts)
print "Overall, the number of ICs that were not uniquely determined was: " + str(
count_correct_not_unique)
print "This was applicable to the following images: "
print not_unique_but_correct
print "May want to look into the following files: "
print errors
time_end = time.clock()
time_taken = time_begin - time_end
# collecting the results:
with open("output.txt", "a") as outputfile:
outputfile.write("Overall correct: " + str(count_correct))
outputfile.write("\n")
outputfile.write("Overall correct but not unique: " + str(count_correct_not_unique))
outputfile.write("\n")
outputfile.write("Value for block size " + str(bs_val))
outputfile.write("\n")
outputfile.write("Value for offset: " + str(os_val))
outputfile.write("\n")
outputfile.write("Number of images read: " + str(count_attempts))
outputfile.write("\n")
outputfile.write("Accuracy in %: " + str(100.0*count_correct / count_attempts))
outputfile.write("\n")
outputfile.write("Time taken: " + str(time_taken))
outputfile.write("\n")
outputfile.write("Not unique but correct: ")
outputfile.writelines(not_unique_but_correct)
outputfile.write("\n")
outputfile.write("Errors: ")
outputfile.writelines(errors)
pickle_name = "errors_" + str(bs_val) + "_" + str(os_val) + "_" + str(area_val)
with open(os.path.join(os.curdir, pickle_name + ".pickle"), "wb") as f:
pickle.dump(errors, f)
f.close()
else:
print "Please load ASN before doing accuracy tests m8"
elif self.method in "AccItemCTest": # for now, use AdaptiveThresholding for Image processing
if self.ASN_loaded:
directory = askdirectory()
count_attempts = 0
count_correct = 0
count_correct_not_unique = 0
errors = []
not_unique_but_correct = []
for filename in os.listdir(directory):
if filename.endswith(".JPG"):
count_attempts += 1
# img_read = cv2.imread(os.path.join(directory,filename))
processor = img_processor(os.path.join(directory, filename))
text, boxes, img = processor.AdaptiveThresholding()
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
#categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(text, categories) # need to add accuracy check
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checkerNoText(text, categories)
correct_index = self.match_instance.correctFinder(filename)
# print itemcode_indeces
# print "Correct index: " + str(correct_index)
if (correct_index in itemcode_indeces) and unique_ic:
count_correct += 1
elif (correct_index in itemcode_indeces) and not unique_ic:
count_correct_not_unique += 1
not_unique_but_correct.append(filename)
else:
errors.append(filename)
print "Categories: "
print categories
print "Text: "
print text
print "Images processed: " + str(count_attempts)
print "Correctly determined the itemcode: " + str(count_correct)
print "Line level accuracy solid code: " + str(100.0 * count_correct / count_attempts)
print "Overall, the number of ICs that were not uniquely determined was: " + str(count_correct_not_unique)
print "This was applicable to the following images: "
print not_unique_but_correct
print "May want to look into the following files: "
print errors
else:
print "Please load ASN before doing accuracy tests m8"
elif self.method in "AdaptiveWholeBoxTest":
if self.ASN_loaded:
directory = askdirectory()
count_attempts = 0
count_correct_ic = 0
count_correct_sa = 0
count_correct_box = 0
not_unique_but_correct = []
errors = []
count_correct_not_unique = 0
for filename in os.listdir(directory): # note: skip_segmentation's requirement is too strict currently. Try without it at all
if filename.endswith(".JPG"):
if self.match_instance.inPrintedList(filename): # then do adaptive thresholding
count_attempts += 1
processor = img_processor(os.path.join(directory, filename))
text, boxes, img = processor.AdaptiveThresholding()
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(
text, categories) # need to add accuracy check
correct_index = self.match_instance.correctFinder(filename)
if (correct_index in itemcode_indeces) and unique_ic:
count_correct_ic += 1
elif (correct_index in itemcode_indeces) and not unique_ic:
count_correct_not_unique += 1
not_unique_but_correct.append(filename)
else:
pass
# errors.append(filename)
if correct_index in solidassort_indeces:
count_correct_sa += 1
if (correct_index in itemcode_indeces) and (correct_index in solidassort_indeces):
count_correct_box += 1
print "Found the box!"
else:
errors.append(filename)
print "Results so far: "
print "Overall accuracy" + str(1.0*count_correct_box/count_attempts)
print "Tried " + str(count_attempts) + " boxes so far!"
# print results:
print "Overall accuracy: " + str(1.0*count_correct_box/count_attempts)
print "Itemcode accuracy: " + str(1.0*count_correct_ic/count_attempts)
print "Solidassort accuracy" + str(1.0*count_correct_sa/count_attempts)
print "Got these wrong:"
print errors
elif self.method in "ReprocessSA":
text, boxes, img = processor.AdaptiveThresholding()
img_pic = Image.fromarray(img)
self.DisplayProcessed(img_pic.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text)
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
# analyze the bounding boxes
# find the mean and sd of the heights of the lines
heights = []
for rectangle in boxes:
heights.append(rectangle[3]-rectangle[1]) # height of the line
heights = np.asarray(heights) # may not be needed
# mean_height, sd_height = cv2.meanStdDev(heights) # will not be used yet
if self.ASN_loaded:
#categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(text, categories)
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checkerNoText(text, categories)
# next, want to extract the S/A code and reprocess it, with a smaller whitelist
# have boxes from above, and have img still
correct_index = self.match_instance.correctFinder(self.filename) # for testing purposes only
# needd a match instance to find the solidassort indices that fit best.
index_ic = categories['Itemcode']
index_sa = categories['Solidcode']
# need to make adjustments, taking blank text lines into account and their missing bounding rectangles.
index_sa_adjusted = index_sa
sa_adjustment = 0
for x in xrange(0, index_sa):
line_before = text[x].replace("\n", "")
if len(line_before) == 0:
sa_adjustment += 1
index_sa_adjusted = index_sa - sa_adjustment
# find the IC adjustment next:
ic_adjustment = 0
for x in xrange(0, index_ic):
line_before = text[x].replace("\n", "")
if len(line_before) == 0:
ic_adjustment += 1
# index_ic_for_comparison = index_ic - sa_adjustment
index_ic_for_comparison = index_ic - ic_adjustment
index_sa = index_sa_adjusted # make sure that text is not being accessed after this point!
coordinates = boxes[index_sa]
# to implement: better logic for extracting the solid/assort code
# based on...vertical thickness of lines
# position of IC, PCS info, Carton No, text description
# handle empty line text outputs (check their bounding boxes on line level, are the vertical heights close to 0? )
x_top_left = 0
y_top_left = coordinates[1]
x_bottom_right = img.shape[1] # assuming x,y are reversed (order) by cv2 image reader.
y_bottom_right = coordinates[3] + int(0.01*img.shape[0]) # too much?
# also needed: improved logic for finding the proper index of SA
# check: any lines w/ small vertical height near the IC?
if type(categories['Itemcode']) is not bool:
ic_height = boxes[categories['Itemcode']][3] - boxes[categories['Itemcode']][1]
height_threshold = int(0.30*ic_height)
else:
height_threshold = 20
if (index_sa - index_ic_for_comparison) > 1:
if (boxes[index_sa - 1][3]-boxes[index_sa - 1][1]) < height_threshold:
y_top_left = boxes[index_sa-1][1]
if (index_sa - index_ic_for_comparison) > 2:
if (boxes[index_sa - 2][3] - boxes[index_sa - 2][1]) < height_threshold:
y_top_left = boxes[index_sa-2][1]
if (index_sa - index_ic_for_comparison) > 3:
if (boxes[index_sa - 3][3] - boxes[index_sa - 3][1]) < height_threshold:
y_top_left = boxes[index_sa-3][1]
elif index_sa - index_ic_for_comparison == 1: # i.e. directly belwo
pass
else:
print "SA above IC is impossible, something has gone wrong upstream!" # set to index_ic + 1 as default "best guess"
index_sa = index_ic_for_comparison + 1
y_top_left = boxes[index_sa][1]
y_bottom_right = boxes[index_sa][3]
img_snipped = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right]
# img_rgb = cv2.imread(self.filename)
# img_snipped = img_rgb[y_top_left:y_bottom_right, x_top_left:x_bottom_right] # region may be too small
# Image.fromarray(img_snipped).show() # then pass it on
Image.fromarray(img_snipped).save("solidslice.png")
# try: reprocess with Tesseract the extracted Solid/Assort regions
# for now, assume SOLID
dimension_y, dimension_x = img.shape
print dimension_y
print dimension_x
# background = np.zeros((dimension_y, dimension_x), dtype='float32')
# background[y_top_left:y_bottom_right, x_top_left:x_bottom_right] = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right]
img_snipped_binary = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right] # in numpy array form
img_snipped_binary_for_tess = Image.fromarray(img_snipped_binary)
# img_snipped_binary_for_tess.show()
# Image.fromarray(background).show()
repro = reprocessor(img_snipped_binary_for_tess)
text_solid_assort = repro.SingleLineTess() # contains a single guess for the value
feed = []
feed.append(text_solid_assort)
# should do substrings also, often a redundant digit '1' is added at the front of the output from this stage, while the remaining SC is correct
sa_indices, min_dist = self.match_instance.saReprocessed(feed, itemcode_indeces)
# want the absolute value of the minimum distance also for the purpose of checking whether segmentation is needed or not
if min_dist < 0.35:
skip_segmentation = True
# check repro against the ASN.
# here, update skip_segmentation (boolean), based on the output from the reprocessing of SA line
feed = []
feed.append(text[categories['Solidcode']])
sa_indices_original, dist_original = self.match_instance.saReprocessed(feed, itemcode_indeces)
# split into two streams, based on whether segmentation can be skipped or not
if not skip_segmentation:
solidcands = Segmentation.Fujisawa('solidslice.png')
print solidcands
sa_indices_from_segmentation, min_dist_from_segmentation = self.match_instance.saReprocessed(solidcands, itemcode_indeces)
if (dist_original <= min_dist) and (dist_original <= min_dist_from_segmentation):
sa_verdict = sa_indices_original
elif (min_dist <= dist_original) and (min_dist <= min_dist_from_segmentation):
sa_verdict = sa_indices
else:
sa_verdict = sa_indices_from_segmentation
else:
if dist_original <= min_dist:
sa_verdict = sa_indices_original
else:
sa_verdict = sa_indices
print itemcode_indeces
print sa_verdict
# compare all the 3 rounds of SA guesses and their min distances to ASN -> form guess about which box it is.
# now, want to return the guesses of item code, solid/assort code and the entire box
print str(self.filename)
print "Ended, awaiting next input"
elif self.method in "SARemoveIC":
text, boxes, img = processor.AdaptiveThresholding()
img_pic = Image.fromarray(img)
self.DisplayProcessed(img_pic.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text)
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
# analyze the bounding boxes
# find the mean and sd of the heights of the lines
heights = []
for rectangle in boxes:
heights.append(rectangle[3] - rectangle[1]) # height of the line
heights = np.asarray(heights)
# mean_height, sd_height = cv2.meanStdDev(heights) # will not be used yet
if self.ASN_loaded:
# categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(text, categories)
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checkerNoText(
text, categories)
# next, want to extract the S/A code and reprocess it, with a smaller whitelist
# have boxes from above, and have img still
index_ic = categories['Itemcode']
index_sa = categories['Solidcode']
# need to make adjustments, taking blank text lines into account and their missing bounding rectangles.
index_sa_adjusted = index_sa
sa_adjustment = 0
for x in xrange(0, index_sa):
line_before = text[x].replace("\n", "")
if len(line_before) == 0:
sa_adjustment += 1
index_sa_adjusted = index_sa - sa_adjustment
index_ic_for_comparison = index_ic - sa_adjustment
index_sa = index_sa_adjusted # make sure that text is not being accessed after this point!
coordinates = boxes[index_sa]
# to implement: better logic for extracting the solid/assorrt code
# based on...vertical thickness of lines
# position of IC, PCS info, Carton No, text description
# handle empty line text outputs (check their bounding boxes on line level, are the vertical heights close to 0? )
x_top_left = 0
y_top_left = coordinates[1]
x_bottom_right = img.shape[1] # assuming x,y are reversed (order) by cv2 image reader.
y_bottom_right = coordinates[3] + int(0.01 * img.shape[0]) # too much?
# also needed: improved logic for finding the proper index of SA
# check: any lines w/ small vertical height near the IC?
if type(categories['Itemcode']) is not bool:
ic_height = boxes[categories['Itemcode']][3] - boxes[categories['Itemcode']][1]
height_threshold = int(0.30 * ic_height)
else:
height_threshold = 20
if (index_sa - index_ic_for_comparison) > 1:
if (boxes[index_sa - 1][3] - boxes[index_sa - 1][1]) < height_threshold:
y_top_left = boxes[index_sa - 1][1]
if (index_sa - index_ic_for_comparison) > 2:
if (boxes[index_sa - 2][3] - boxes[index_sa - 2][1]) < height_threshold:
y_top_left = boxes[index_sa - 2][1]
if (index_sa - index_ic_for_comparison) > 3:
if (boxes[index_sa - 3][3] - boxes[index_sa - 3][1]) < height_threshold:
y_top_left = boxes[index_sa - 3][1]
elif index_sa - index_ic_for_comparison == 1: # i.e. directly belwo
pass
else:
print "SA above IC is impossible, something has gone wrong upstream!" # then what to do in this case?
# could set to IC + 1 by default?
index_sa = index_ic_for_comparison + 1
y_top_left = boxes[index_sa][1]
y_bottom_right = boxes[index_sa][3]
# x-coords should be unaffected
img_snipped = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right] # black text on white background
# img_rgb = cv2.imread(self.filename)
# img_snipped = img_rgb[y_top_left:y_bottom_right, x_top_left:x_bottom_right] # region may be too small
Image.fromarray(img_snipped).show() # then pass it on
Image.fromarray(img_snipped).save("solidslice.png")
# try: reprocess with Tesseract the extracted Solid/Assort regions
# for now, assume SOLID
dimension_y, dimension_x = img.shape
print dimension_y
print dimension_x
# background = np.zeros((dimension_y, dimension_x), dtype='float32')
# background[y_top_left:y_bottom_right, x_top_left:x_bottom_right] = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right]
img_snipped_binary = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right] # in numpy array form
img_snipped_binary_for_tess = Image.fromarray(img_snipped_binary)
# img_snipped_binary_for_tess.show()
# Image.fromarray(background).show()
# should first remove all traces of the item code from the extracted region before feeding for reprocessing.
repro = reprocessor(img_snipped_binary_for_tess)
repro.SingleLineTess()
print "Ended, awaiting next input"
elif self.method in "WholeBoxReprocessSA":
if self.ASN_loaded:
directory = askdirectory()
count_attempts = 0
count_correct_ic = 0
count_correct_sa = 0
count_correct_box = 0
not_unique_but_correct = []
errors = []
count_correct_not_unique = 0
for filename in os.listdir(directory): # note: skip_segmentation's requirement is too strict currently. Try without it at all
if filename.endswith(".JPG"):
if self.match_instance.inPrintedList(filename): # then do adaptive thresholding
print str(filename)
count_attempts += 1
processor = img_processor(os.path.join(directory, filename))
text, boxes, img = processor.AdaptiveThresholding()
# the following 3 lines are optional - if want to redruce processing time, then cut them out
img_pic = Image.fromarray(img)
self.DisplayProcessed(img_pic.resize((self.width, self.height), Image.ANTIALIAS))
self.DisplayOCRText(text)
interpreter = outputInterpreter()
text, categories = interpreter.categorizeLines(text)
categories, text, itemcode_indeces, unique_ic, skip_segmentation, solidassort_indeces = self.match_instance.checker(
text, categories) # need to add accuracy check
correct_index = self.match_instance.correctFinder(filename)
# solidassort_line_no = int(categories['Solidcode']) # integer conversion can cause trouble of there is no index found for S/A line?
if type(categories['Solidcode']) is not bool:
solidassort_line_no = int(categories['Solidcode'])
else:
solidassort_line_no = 1 + categories['Itemcode']
print "Did not have any OG index for SA line"
coordinates = boxes[solidassort_line_no]
x_top_left = 0
y_top_left = coordinates[1]
x_bottom_right = img.shape[1] # assuming x,y are reversed (order) by cv2 image reader.
y_bottom_right = coordinates[3]
if (y_bottom_right - y_top_left) > (
0.60 * (boxes[int(categories['Itemcode'])][3] - boxes[int(categories['Itemcode'])][1])):
pass
# img = cv2.imread(self.filename)
# img_snipped = img[y_top_left:y_bottom_right, x_top_left:x_bottom_right]
# Image.fromarray(img_snipped).show() # then pass it on
# Image.fromarray(img_snipped).save("solidslice.png")
else:
print "Would not extract S/A code since the bounding rect was not found satisfactory"
img_rgb = cv2.imread(self.filename)
img_snipped = img_rgb[y_top_left:y_bottom_right, x_top_left:x_bottom_right]
# Image.fromarray(img_snipped).show() # then pass it on
Image.fromarray(img_snipped).save("solidslice.png")
img_snipped_binary = img[y_top_left:y_bottom_right,
x_top_left:x_bottom_right] # in numpy array form
img_snipped_binary_for_tess = Image.fromarray(img_snipped_binary)
# img_snipped_binary_for_tess.show()
repro = reprocessor(img_snipped_binary_for_tess)
text_sa_reprocessed = repro.SingleLineTess() # text
# from here, want to find the best candidate for S/A code based on text_sa_reprocessed~
sa_indeces_reprocessed = self.match_instance.solidAssortReprocessed(text_sa_reprocessed, itemcode_indeces)
solidassort_indeces = sa_indeces_reprocessed # comment out this line if don't want to use the reprocessed text
# at this point, may have a set of ICs (i.e. not uniquely determined)
if (correct_index in itemcode_indeces) and unique_ic:
count_correct_ic += 1
elif (correct_index in itemcode_indeces) and not unique_ic:
count_correct_not_unique += 1
not_unique_but_correct.append(filename)
else:
pass
# errors.append(filename)
if correct_index in solidassort_indeces:
count_correct_sa += 1
# the below may not be rigorous enough if have several candidates for SKU
if (correct_index in itemcode_indeces) and (correct_index in solidassort_indeces):
count_correct_box += 1
print "Found the box! To see if uniquely determined, need to do further checks! "
else:
errors.append(filename)
print "Results so far: "
print "Overall accuracy" + str(1.0*count_correct_box/count_attempts)
print "Tried " + str(count_attempts) + " boxes so far!"
# print results:
print "Overall accuracy: " + str(1.0*count_correct_box/count_attempts)
print "Itemcode accuracy: " + str(1.0*count_correct_ic/count_attempts)
print "Solidassort accuracy" + str(1.0*count_correct_sa/count_attempts)
print "Got these wrong:"
print errors
elif self.method in "PrintedBoxesFullSystem": # the most up-to-date method as of 04/08/2017
if self.ASN_loaded:
directory = askdirectory()
# randomize all the files in the directory, and store the order for future reference.
name_list = []
for filename in os.listdir(directory):
if filename.endswith(".JPG"):
name_list.append(filename)
shuffle(name_list)
with open("name_list.pickle", "wb") as f: # the pickle will get crowded over time if the new lists are written on top of the previous ones
pickle.dump(name_list, f)
count_attempts = 0
count_correct_ic = 0
count_correct_sa = 0
count_correct_box = 0
not_unique_but_correct = []
# errors = []
count_correct_not_unique = 0
errors_ic = []
errors_sa = []
correct_ic_vals = []
output_ic_vals = []
for filename in name_list:
if filename.endswith(".JPG"): # conditions for initiating table removal
if self.match_instance.inPrintedList(filename): # don't do if not printed
count_attempts += 1