-
Notifications
You must be signed in to change notification settings - Fork 1
/
Main_window.py
2646 lines (2040 loc) · 118 KB
/
Main_window.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
import os
import re
import cv2
import sys
import vlc
import data
import time
import math
import shutil
import smtplib
import threading
import numpy as np
import language_check
import matplotlib.pyplot as plt
import speech_recognition as sr
from PyQt4 import Qt
from gtts import gTTS
from pygame import mixer
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from threading import Thread
from autocorrect import spell
from PyQt4 import QtGui,QtCore
from collections import Counter
from email.mime.text import MIMEText
from sklearn.externals import joblib
from PIL import Image,ExifTags,ImageOps
from PyPDF2 import PdfFileMerger, PdfFileReader
sys.setrecursionlimit(10000)
####################################################################################################
##### This is the main class that control all the subclass and used for layout switching #####
####################################################################################################
class App_Window(QtGui.QMainWindow):
#---------------------------------------------------------------------
# Init method for our App_Window class
def __init__(self, parent=None):
super(App_Window, self).__init__(parent)
self.setWindowTitle(data.app_name) #App Title
self.setWindowIcon(QtGui.QIcon(data.app_logo_image)) #App Icon
##Set the background of window as an image
back_img = Image.open(data.background_image)
width , height = back_img.size
self.setFixedSize(width,height)
palette = QtGui.QPalette()
palette.setBrush(QtGui.QPalette.Background,QtGui.QBrush(QtGui.QPixmap(data.background_image)))
self.setPalette(palette)
self.central_widget = QtGui.QStackedWidget()
self.setCentralWidget(self.central_widget)
main_window_widget = Main_window(self)
self.central_widget.addWidget(main_window_widget)
#----------------------------------------------------------------------
# This method is called when back button is pressed in any other window
def back_button(self):
#The below line will set the user interface to the main window
self.central_widget.setCurrentIndex(0)
#----------------------------------------------------------------------
#Processing of the photo ocr operation
def photo_ocr(self):
photo_ocr_widget = Photo_ocr_class(self)
self.central_widget.addWidget(photo_ocr_widget)
self.central_widget.setCurrentWidget(photo_ocr_widget)
#----------------------------------------------------------------------
#Processing of the pdf_scanner operation
def pdf_scanner(self):
pdf_scanner_widget = Pdf_scanner_class(self)
self.central_widget.addWidget(pdf_scanner_widget)
self.central_widget.setCurrentWidget(pdf_scanner_widget)
#----------------------------------------------------------------------
#Processing of the speech_to_text operation
def speech_to_text(self):
speech_to_text_widget = Speech_to_text_class(self)
self.central_widget.addWidget(speech_to_text_widget)
self.central_widget.setCurrentWidget(speech_to_text_widget)
#----------------------------------------------------------------------
#Processing of the text_to_speech operation
def text_to_speech(self):
text_to_speech_widget = Text_to_speech_class(self)
self.central_widget.addWidget(text_to_speech_widget)
self.central_widget.setCurrentWidget(text_to_speech_widget)
#----------------------------------------------------------------------
#Information about the developers
def about_us(self):
about_us_widget = About_us_class(self)
self.central_widget.addWidget(about_us_widget)
self.central_widget.setCurrentWidget(about_us_widget)
#----------------------------------------------------------------------
## Dialog Box to check whether the user really wants to quit
def closeEvent(self,event):
reply = QtGui.QMessageBox.question(self,data.app_name,'Are you sure to quit ' +data.app_name +' ?',QtGui.QMessageBox.Yes|QtGui.QMessageBox.No,QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
####################################################################################################
######### Class App_Window ends here ##############
####################################################################################################
####################################################################################################
##### Class containing the functionality of Photo_ocr option ##############
####################################################################################################
class Photo_ocr_class(QtGui.QWidget):
image_name = '' #Stores the name of image to be loaded
open_cv_image = '' #Used to store the image that will be shown in the QLabel
original_image = '' #Used for reset purpose
temp_image = '' #For syncing purpose between adaptive threshold and simple threshold
adaptive_thresh_value = 25
normal_thresh_value = 70
flag = 0 #Indicate that image has been rotated
inner_flag = 0 #Indicate that image has been thresholded
rotation = 0
left_rot = 0
right_rot = 0
im_copy2 = 0
cc2 = 0
rr1 = 0
rr2 = 0
def __init__(self, parent=None):
super(Photo_ocr_class, self).__init__(parent)
mainWindow = QtGui.QWidget()
self.initUI_Photo_ocr_class()
def initUI_Photo_ocr_class(self):
#Font for the text in the Pdf_scanner window
newFont = QtGui.QFont(data.font_helvetica,data.font_size,QtGui.QFont.Normal)
#--------------------------------------------------------------------------------------
self.back_button = PicButton(QtGui.QPixmap(data.back_button_unpressed_image),QtGui.QPixmap(data.back_button_hover_image),QtGui.QPixmap(data.back_button_pressed_image),self)
self.back_button.setFixedSize(72,72)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.photo_label = QtGui.QLabel(self)
self.photo_label.setFont(newFont)
self.photo_label.setFixedSize(650,600)
self.photo_label.setAlignment(QtCore.Qt.AlignCenter)
self.photo_label.setSizePolicy( QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored )
self.photo_label.setStyleSheet('color: white')
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.open_file = PicButton(QtGui.QPixmap(data.insert_photo_unpressed_image),QtGui.QPixmap(data.insert_photo_hover_image),QtGui.QPixmap(data.insert_photo_pressed_image),self)
self.open_file.setFixedSize(72,72)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.open_label = QtGui.QLabel(self)
self.open_label.setFont(newFont)
self.open_label.setText('Open Image')
self.open_label.setStyleSheet('color: white')
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.enhance_image = QtGui.QLabel(self)
self.enhance_image.setFont(newFont)
self.enhance_image.setText('Enhance Image')
self.enhance_image.setStyleSheet('color: white')
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.reset_button = PicButton(QtGui.QPixmap(data.reset_unpressed),QtGui.QPixmap(data.reset_unpressed),QtGui.QPixmap(data.reset_pressed),self)
self.reset_button.setFixedSize(72,72)
self.reset_button.setEnabled(False)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.coarse_slider_label = QtGui.QLabel(self)
self.coarse_slider_label.setFont(QtGui.QFont(data.font_helvetica,12,QtGui.QFont.Normal))
self.coarse_slider_label.setText('Coarse')
self.coarse_slider_label.setStyleSheet('color: white')
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.coarse_slider = QtGui.QSlider(Qt.Horizontal)
self.coarse_slider.setMinimum(0)
self.coarse_slider.setMaximum(50)
self.coarse_slider.setValue(25)
self.coarse_slider.setTickPosition(QSlider.TicksBelow)
self.coarse_slider.setTickInterval(10)
self.coarse_slider.valueChanged.connect(lambda: self.valuechanged(1))
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.fine_slider_label = QtGui.QLabel(self)
self.fine_slider_label.setFont(QtGui.QFont(data.font_helvetica,12,QtGui.QFont.Normal))
self.fine_slider_label.setText('Fine')
self.fine_slider_label.setStyleSheet('color: white')
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.fine_slider = QtGui.QSlider(Qt.Horizontal)
self.fine_slider.setMinimum(0)
self.fine_slider.setMaximum(255)
self.fine_slider.setValue(70)
self.fine_slider.setTickPosition(QSlider.TicksBelow)
self.fine_slider.setTickInterval(20)
self.fine_slider.valueChanged.connect(lambda: self.valuechanged(2))
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.rotate_slider_label = QtGui.QLabel(self)
self.rotate_slider_label.setFont(QtGui.QFont(data.font_helvetica,12,QtGui.QFont.Normal))
self.rotate_slider_label.setText('Rotate')
self.rotate_slider_label.setStyleSheet('color: white')
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.left_rotate = PicButton(QtGui.QPixmap(data.left_unpressed),QtGui.QPixmap(data.left_unpressed),QtGui.QPixmap(data.left_pressed),self)
self.left_rotate.setFixedSize(72,72)
self.left_rotate.setEnabled(False)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.right_rotate = PicButton(QtGui.QPixmap(data.right_unpressed),QtGui.QPixmap(data.right_unpressed),QtGui.QPixmap(data.right_pressed),self)
self.right_rotate.setFixedSize(72,72)
self.right_rotate.setEnabled(False)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.ocr_button = PicButton(QtGui.QPixmap(data.ocr_unpressed),QtGui.QPixmap(data.ocr_hover),QtGui.QPixmap(data.ocr_pressed),self)
self.ocr_button.setFixedSize(72,72)
self.ocr_button.setEnabled(False)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.ocr_label = QtGui.QLabel(self)
self.ocr_label.setFont(newFont)
self.ocr_label.setText('OCR it')
self.ocr_label.setStyleSheet('color: white')
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.save_button = PicButton(QtGui.QPixmap(data.save_button_unpressed_image),QtGui.QPixmap(data.save_button_hover_image),QtGui.QPixmap(data.save_button_pressed_image),self)
self.save_button.setFixedSize(72,72)
self.save_button.setEnabled(False)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.save_label = QtGui.QLabel(self)
self.save_label.setFont(newFont)
self.save_label.setText('Save File')
self.save_label.setStyleSheet('color: white')
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
self.progress_bar = QtGui.QProgressBar(self)
self.progress_bar.hide()
self.progress_bar.setMinimum(0)
self.progress_bar.setMaximum(0)
self.progress_bar.setFixedSize(1100,30)
self.progress_bar.setVisible(False)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz_top_Layout = QtGui.QHBoxLayout()
horz_top_Layout.addWidget(self.back_button)
horz_top_Layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)) #To add spacing in the layout
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
vert_left_Layout = QtGui.QVBoxLayout()
vert_left_Layout.addWidget(self.photo_label)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz1_Layout = QtGui.QHBoxLayout()
horz1_Layout.addWidget(self.open_file)
horz1_Layout.addWidget(self.open_label)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz2_Layout = QtGui.QHBoxLayout()
horz2_Layout.addWidget(self.enhance_image)
horz2_Layout.addWidget(self.reset_button)
horz2_Layout.setContentsMargins(0,50,0,0)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz3_Layout = QtGui.QHBoxLayout()
horz3_Layout.addWidget(self.coarse_slider_label)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz4_Layout = QtGui.QHBoxLayout()
horz4_Layout.addWidget(self.coarse_slider)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz5_Layout = QtGui.QHBoxLayout()
horz5_Layout.addWidget(self.fine_slider_label)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz6_Layout = QtGui.QHBoxLayout()
horz6_Layout.addWidget(self.fine_slider)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz7_Layout = QtGui.QHBoxLayout()
horz7_Layout.addWidget(self.rotate_slider_label)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz8_Layout = QtGui.QHBoxLayout()
horz8_Layout.addWidget(self.left_rotate)
horz8_Layout.addWidget(self.right_rotate)
horz8_Layout.setContentsMargins(0,0,0,40)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz9_Layout = QtGui.QHBoxLayout()
horz9_Layout.addWidget(self.ocr_button)
horz9_Layout.addWidget(self.ocr_label)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz10_Layout = QtGui.QHBoxLayout()
horz10_Layout.addWidget(self.save_button)
horz10_Layout.addWidget(self.save_label)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
vert_right_Layout = QtGui.QVBoxLayout()
vert_right_Layout.addLayout(horz1_Layout)
vert_right_Layout.addLayout(horz2_Layout)
vert_right_Layout.addLayout(horz3_Layout)
vert_right_Layout.addLayout(horz4_Layout)
vert_right_Layout.addLayout(horz5_Layout)
vert_right_Layout.addLayout(horz6_Layout)
vert_right_Layout.addLayout(horz7_Layout)
vert_right_Layout.addLayout(horz8_Layout)
vert_right_Layout.addLayout(horz9_Layout)
vert_right_Layout.addLayout(horz10_Layout)
vert_right_Layout.setContentsMargins(50,0,0,0)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz_medium_Layout = QtGui.QHBoxLayout()
horz_medium_Layout.addLayout(vert_left_Layout)
horz_medium_Layout.addLayout(vert_right_Layout)
horz_medium_Layout.setContentsMargins(50,0,100,50)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
horz_bottom_Layout = QtGui.QHBoxLayout()
horz_bottom_Layout.addWidget(self.progress_bar)
horz_bottom_Layout.setContentsMargins(0,0,0,20)
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
vert_main_Layout = QtGui.QVBoxLayout()
vert_main_Layout.addLayout(horz_top_Layout)
vert_main_Layout.addLayout(horz_medium_Layout)
vert_main_Layout.addLayout(horz_bottom_Layout)
self.setLayout(vert_main_Layout)
#--------------------------------------------------------------------------------------
self.reset_button.clicked.connect(self.reset_method)
self.left_rotate.clicked.connect(lambda: self.rotate_method(1))
self.right_rotate.clicked.connect(lambda: self.rotate_method(2))
self.open_file.clicked.connect(self.open_image_method)
self.ocr_button.clicked.connect(self.do_operation)
self.save_button.clicked.connect(self.save_method)
self.back_button.clicked.connect(self.parent().back_button)
#----------------------------------------------------------------------------------
def save_method(self):
name = QtGui.QFileDialog.getSaveFileName(self,'Save File')
file = open(name,'w')
temp_file = open("C:\\Github\\Multitasker\\Data\\result.txt",'r')
text = temp_file.read()
file.write(text)
temp_file.close()
os.remove("C:\\Github\\Multitasker\\Data\\result.txt")
file.close()
#----------------------------------------------------------------------------------
#----------------------------------------------------------------------------------
def reset_method(self):
self.coarse_slider.setValue(25)
self.fine_slider.setValue(70)
self.open_cv_image = self.original_image
self.show_pixmap(self.original_image)
#----------------------------------------------------------------------------------
def rotate_method(self,direction):
if direction==1 : #left rotate
angle = -90
self.left_rot +=1
if self.right_rot >0:
self.right_rot -=1
else:
angle = 90 #Right rotate
self.right_rot +=1
if self.left_rot >0:
self.left_rot -=1
(h, w) = self.open_cv_image.shape[:2]
(cX, cY) = (w // 2, h // 2)
# grab the rotation matrix (applying the negative of the angle to rotate clockwise), then grab the sine and cosine (i.e., the rotation components of the matrix)
M = cv2.getRotationMatrix2D((cX , cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
# compute the new bounding dimensions of the image
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
# adjust the rotation matrix to take into account translation
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
self.open_cv_image = cv2.warpAffine(self.open_cv_image, M, (nW, nH),cv2.INTER_LANCZOS4)
self.flag = 1
if self.left_rot == 4 or self.right_rot == 4:
self.open_cv_image = self.original_image
self.left_rot = self.right_rot = 0
self.open_cv_image = self.original_image
self.open_cv_image = cv2.adaptiveThreshold(self.open_cv_image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,self.adaptive_thresh_value)
ret,self.open_cv_image = cv2.threshold(self.open_cv_image,self.normal_thresh_value,255,cv2.THRESH_BINARY)
#show the opencv image in the Qlabel
self.show_pixmap(self.open_cv_image)
#----------------------------------------------------------------------------------
def open_image_method(self):
self.image_name = QtGui.QFileDialog.getOpenFileName(self,'Select Image','','Images(*.png *.jpg *.jpeg)')
if len(self.image_name) >0: #Check whether user has choose an image or not
try:
self.ocr_button.setEnabled(True)
self.coarse_slider.setValue(25)
self.fine_slider.setValue(70)
self.reset_button.setEnabled(True)
self.flag = 0
self.inner_flag = 0
basewidth = 650 #Desired width of the image
baseheight = 600 #Desired height of the image
image = Image.open(self.image_name)
width,height = image.size
wpercent = (basewidth/float(image.size[0]))
hpercent = (baseheight/float(image.size[1]))
hsize = int((float(image.size[1])*float(wpercent)))
wsize = int((float(image.size[0])*float(hpercent)))
if width > height:
size1 = (basewidth,hsize)
else :
size1 = (wsize,baseheight)
image.thumbnail(size1, Image.ANTIALIAS)
#Convert from PIL to opencv image
temp_image = image.convert('RGB')
self.open_cv_image = np.array(temp_image)
self.open_cv_image = self.open_cv_image[:, :, ::-1].copy()
self.open_cv_image = cv2.cvtColor(self.open_cv_image,cv2.COLOR_BGR2GRAY)
self.original_image = self.open_cv_image
self.temp_image = self.open_cv_image
#Enable left and right rotate buttons
self.left_rotate.setEnabled(True)
self.right_rotate.setEnabled(True)
#show the image on the scree
self.show_pixmap(self.temp_image)
except: pass
#----------------------------------------------------------------------------------
#----------------------------------------------------------------------------------
def valuechanged(self,option):
try:
if option == 1 and len(self.image_name):
self.adaptive_thresh_value = self.coarse_slider.value()
elif option == 2 and len(self.image_name):
self.normal_thresh_value = self.fine_slider.value()
temp_image = self.open_cv_image
if len(self.image_name)>0:
if option ==1:
temp_image = cv2.adaptiveThreshold(temp_image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,self.adaptive_thresh_value)
ret,temp_image = cv2.threshold(temp_image,self.normal_thresh_value,255,cv2.THRESH_BINARY)
else:
ret,temp_image = cv2.threshold(temp_image,self.normal_thresh_value,255,cv2.THRESH_BINARY)
temp_image = cv2.adaptiveThreshold(temp_image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,self.adaptive_thresh_value)
#show the opencv image in the Qlabel
self.show_pixmap(temp_image)
except: pass
#----------------------------------------------------------------------------------
#----------------------------------------------------------------------------------
def show_pixmap(self,image):
image = cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)
#Convert a opencv image to QImage i.e of pixmap format
height, width,channel = image.shape
bytesPerLine = 3 * width
qImg = QtGui.QImage(image, width, height, bytesPerLine, QtGui.QImage.Format_RGB888)
self.photo_label.setPixmap(QtGui.QPixmap(qImg))
#----------------------------------------------------------------------------------
def words(self,text):
return re.findall(r'\w+', text.lower())
#----------------------------------------------------------------------------------
def show_progress_bar(self):
self.progress_bar.show()
#----------------------------------------------------------------------------------
def do_operation(self):
#-------------------------------------------------------------
#Show the progress bar until the execution is not completed
thread_progress_bar = Thread(target = self.show_progress_bar)
thread_progress_bar.start()
#-------------------------------------------------------------
#-------------------------------------------------------------
thread_ocr = Thread(target =self.ocr_it_method)
thread_ocr.start()
#-------------------------------------------------------------
#----------------------------------------------------------------------------------
def ocr_it_method(self):
self.save_button.setEnabled(True)
im = cv2.imread(self.image_name,0)
clf = joblib.load(data.pickel_file)
f = open(data.text_file,'w')
im_th = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,self.adaptive_thresh_value)
ret,im_th = cv2.threshold(im_th,self.normal_thresh_value,255,cv2.THRESH_BINARY)
height,width=im.shape
row=np.zeros(height,dtype=np.int16) # no. of row = height of page
#-------------------------------------------------------------------------------
#count black pixel in reach row
for i in range(height):
for j in range(width):
if(im_th[i][j]==0):
row[i]+=1;
row_true=np.zeros(height,dtype=np.int16) # actual rows
num_row = 0
#check if height =0 is first row
if(row[0]>0):
row_true[0]=0
num_row+=1
mean_dist_row=0
#-------------------------------------------------------------------------------
# find actual rows
# row_true -> array having height of actual rows
# col_true -> array having width of actual columns
for j in range(1,height,1):
if((row[j]>0 and row[j-1]==0) or ( row[j]==0 and row[j-1]>0)):
row_true[num_row]=j
num_row+=1
if(num_row%2==0):
mean_dist_row+=row_true[num_row-1]-row_true[num_row-2]
mean_dist_row/=num_row
mean_dist_row*=2 # as actual rows= num_row/2
j=1
#-------------------------------------------------------------------------------
self.im_copy2 = im_th.copy()
first_word=1 # help to check if character is first character of word
# for detection between I and l(small l)
first_sentence=1 # help to capitalise frist letter in sentence
#-------------------------------------------------------------------------------
# dfs function
def func(c,r):
if(c<c1 or c>c2 or r<r1 or r>r2 or self.im_copy2[r][c]!=0):
return
self.im_copy2[r][c]=255
self.cc2=max(self.cc2,c)
self.rr1=min(self.rr1,r)
self.rr2=max(self.rr2,r)
roi[r-r1][c-c1]=255
func(c-1,r-1)
func(c,r-1)
func(c+1,r-1)
func(c-1,r)
func(c+1,r)
func(c-1,r+1)
func(c,r+1)
func(c+1,r+1)
#--------------------------------------------------------------------------------
def words(text):
return re.findall(r'\w+', text.lower())
WORDS = Counter(words(open(data.dictionary).read()))
#--------------------------------------------------------------------------------
# spell check functions
def P(word, N=sum(WORDS.values())):
return WORDS[word] / N
## "Most probable spelling correction for word."
#--------------------------------------------------------------------------------
def correction(word):
return max(candidates(word), key=P)
## "Generate possible spelling corrections for word."
#--------------------------------------------------------------------------------
def candidates(word):
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])
## "The subset of `words` that appear in the dictionary of WORDS."
#--------------------------------------------------------------------------------
def known(words):
return set(w for w in words if w in WORDS)
#--------------------------------------------------------------------------------
## "All edits that are one edit away from `word`."
def edits1(word):
letters = "abcdefghijklmnopqrstuvwxyz0123456789!’#$%&‘()*+,-./:;<=>?@\^_`{|}~÷"
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
## deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
## inserts = [L + c + R for L, R in splits for c in letters]
## return set(deletes + transposes + replaces + inserts)
return set(transposes+replaces)
#--------------------------------------------------------------------------------
## "All edits that are two edits away from `word`."
def edits2(word):
return (e2 for e1 in edits1(word) for e2 in edits1(e1))
#--------------------------------------------------------------------------------
word=''
word1=''
while j<num_row: # for each row
#--------------------------------------------------------------------------------
# illegal row removed
if((2*(row_true[j]-row_true[j-1]))<mean_dist_row):
num_row-=1
for k in range(j,num_row,1):
row_true[k]=row_true[k+1]
#--------------------------------------------------------------------------------
# else proceed with row
else:
if(j>1):
# write word and write new line, j>1 so that condition not checked
# for first row
#--------------------------------------------------------------------------------
# up - is first letter of word capital
if(len(word)>0):
q=len(word)
if(word[0].isupper()):
up=1
else:
up=0
# correct from first char till either ( end or first special char)
for p in range(len(word)-1,-1,-1):
if((word[p]>='a' and word[p]<='z' )or(word[p]>='A' and word[p]<='Z') ):
break
else:
q-=1
#--------------------------------------------------------------------------------
if(q==0 or word=='I'): # word contain only special character
f.write(word)
#--------------------------------------------------------------------------------
else:
for p in range(q):
if(word[p]=='1'):
word1+='l'
elif(word[p]=='0'):
if(p==0):
word1+='O'
else:
word1+='o'
elif(word[p]=='5'):
if(p==0):
word1+='S'
else:
word1+='s'
elif(word[p]=='8'):
word1+='a'
else:
word1+=word[p]
for p in range(q,len(word)-1,1):
word1+=word[p]
p=len(word)-2
if(q<(len(word))):
if(word[p+1]=='*'):
word1+='.'
else:
word1+=word[p+1]
word2 = spell(word1[0:q])
word3= correction(word2)
if(up==1):
f.write(word3[0].capitalize())
else:
f.write(word3[0])
f.write(word3[1:len(word3)])
f.write(word1[q:len(word)])
#--------------------------------------------------------------------------------
word=''
word1=''
f.write('\n')
#--------------------------------------------------------------------------------
col=np.zeros(width+1,dtype=np.int16)
col_true=np.zeros(width,dtype=np.int16)
mean_col=0
num_col=0
for i in range(width):
for k in range(row_true[j-1],row_true[j],1):
if(self.im_copy2[k,i]==0):
col[i]+=1
for k in range(width):
if(col[k]>0):
mean_col+=col[k]
num_col+=1
mean_col/=num_col
num_col=0
if(col[0]>0):
col_true[0]=0
num_col=1
flag=0
#--------------------------------------------------------------------------------
# count actual columns in row between lines row_true[j] and row_true[j-1]
for k in range(1,width,1):
if(flag==0 and col[k]>0 and col[k-1]==0):
col_true[num_col]=k
num_col+=1
flag=1
elif(flag==1 and col[k]==0 and col[k-1]>0):
col_true[num_col]=k
# remove noise
if((col_true[num_col]-col_true[num_col-1])<=(mean_dist_row/20)):
num_col-=1
flag=0
continue
num_col+=1
flag=0
k=1
r1=row_true[j-1]
r2=row_true[j]-1
#--------------------------------------------------------------------------------
while(k<num_col): # for each contour
# space and write word
if(k>2 and ((col_true[k-1]-col_true[k-2])>((r2-r1+1)/5.25))):
if(len(word)>0):
q=len(word)
if(word[0].isupper()):
up=1
else:
up=0
# correct from first char till either ( end or first special char)
for p in range(len(word)-1,-1,-1):
if((word[p]>='a' and word[p]<='z' )or(word[p]>='A' and word[p]<='Z') ):
break
else:
q-=1
if(q==0 or word=='I'): # word contain only special character
f.write(word)
else:
for p in range(q):
if(word[p]=='1'):
word1+='l'
elif(word[p]=='0'):
if(p==0):
word1+='O'
else:
word1+='o'
elif(word[p]=='5'):
if(p==0):
word1+='S'
else:
word1+='s'
elif(word[p]=='8'):
word1+='a'
else:
word1+=word[p]
for p in range(q,len(word)-1,1):
word1+=word[p]
p=len(word)-2
if(q<(len(word))):
if(word[p+1]=='*'):
word1+='.'
else:
word1+=word[p+1]
word2 = spell(word1[0:q])
word3= correction(word2)
if(up==1):
f.write(word3[0].capitalize())
else:
f.write(word3[0])
f.write(word3[1:len(word3)])
f.write(word1[q:len(word)])
word=''
word1=''
first_word=1
f.write(' ') # space
proi=np.ones((0,0))
# pr1,pr2,pc1,pc2 -> proi coordinates
pr1=10000
pr2=-1
pc1=10000
pc2=-1
merge=0
#--------------------------------------------------------------------------------
while(k<num_col): # for multiple character in contour
c1=col_true[k]
c2=col_true[k]-1
flag_c1=1
for p in range(col_true[k-1],col_true[k],1):
for q in range(r1,r2+1,1):
if(self.im_copy2[q][p]==0):
c1=p
flag_c1=0
break
if(flag_c1==0):
break
if(c1>c2):
k+=2 #no character now,print last character
if(proi.size==0):
continue;
#proi=cv2.dilate(proi,kernel,iterations = 1)
proi = cv2.resize(proi,(28,28),interpolation=cv2.INTER_AREA)
proi=proi.ravel()
for vi in range(784):
if proi[vi]>0:
proi[vi]=1
else:
proi[vi]=0
proi=proi.reshape(1,-1)
nbr = clf.predict(proi)
# pr2-pr1=height, pc2-pc1 =width
if(nbr==48 or nbr==79 or nbr==111):# 0 o O
if((pr2-pr1+1)/(pc2-pc1+1)<0.8 or (pr2-pr1+1)/(pc2-pc1+1)>1.25):
nbr=48
elif((pr2-pr1+1)>(0.6*(r2-r1+1))):
nbr=79
else:
nbr=111
if(nbr==124 or nbr==73 or nbr==108 or nbr==45 or nbr==95 or nbr==46):
if((pr2-pr1+1)/(pc2-pc1+1)>0.6 and (pr2-pr1+1)/(pc2-pc1+1)<1.67):
nbr=46 # .
elif((pr2-pr1+1)<(pc2-pc1+1)):
if(pr1>((r2-r1+1)*0.75+r1)): # _
nbr=95
else: # -
nbr=45
elif(first_word==1):
nbr=73
else:
nbr=108
if(nbr==58 or nbr==61):
if((pr2-pr1+1)/(pc2-pc1+1)>2):
nbr=58 # :
else:
nbr=61 #=
# i is merged of 2 segment,l is single segment
if(nbr==91 or nbr==93): # ] [ -> i (merge=1) ,l (merge=0)
if(merge==1):
nbr=105
else: