-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpostProcessing.py
More file actions
executable file
·1668 lines (1503 loc) · 71.3 KB
/
postProcessing.py
File metadata and controls
executable file
·1668 lines (1503 loc) · 71.3 KB
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/env python3
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
HerbASAP - Herbarium Application for Specimen Auto-Processing
performs post processing steps on raw format images of natural history
specimens. Specifically designed for Herbarium sheet images.
"""
__author__ = "Caleb Powell, Dakila Ledesma, Jacob Motley, Jason Best"
__credits__ = ["Caleb Powell", "Dakila Ledesma", "Jacob Motley", "Jason Best",
"Hong Qin", "Joey Shaw"]
__email__ = "calebadampowell@gmail.com"
__status__ = "Alpha"
__version__ = 'v0.2.0-beta'
import time
from datetime import date
import os
import platform
import sys
import string
import glob
import re
from shutil import move as shutil_move
# UI libs
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QDialog, QSizePolicy
from PyQt5.QtCore import (QSettings, Qt, QObject, QThreadPool, QEventLoop)
# image libs
import rawpy
from rawpy import LibRawNonFatalError, LibRawFatalError
import cv2
import numpy as np
# internal libs
from ui.styles import darkorange
from ui.postProcessingUI import Ui_MainWindow
from ui.noBcDialogUI import Ui_Dialog_noBc
from ui.technicianNameDialogUI import Ui_technicianNameDialog
from ui.imageDialogUI import Ui_Dialog_image
from libs.bcRead import bcRead
from libs.eqRead import eqRead
from libs.blurDetect import blurDetect
from libs.ccRead import ColorchipRead, ColorChipError, SquareFindingFailed
from libs.folderMonitor import Folder_Watcher
from libs.folderMonitor import New_Image_Emitter
from libs.boss_worker import (Boss, BCWorkerData, BlurWorkerData, EQWorkerData,
Job, BossSignalData, WorkerSignalData,
WorkerErrorData, SaveWorkerData)
from libs.metaRead import MetaRead
from libs.scaleRead import ScaleRead
from libs.settingsWizard import SettingsWizard
if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
class Canvas(QtWidgets.QLabel):
def __init__(self, im, parent=None):
super().__init__()
# pixmap = QtGui.QPixmap(600, 300)
# self.setPixmap(pixmap)
self.parent = parent
self.setObjectName("canvas")
self.backDrop, self.correction = self.genPixBackDrop(im)
self.setPixmap(self.backDrop)
self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.end = QtCore.QPoint()
# the box_size, is the point of the entire canvas.
# The scale corrected larger dim of the annotated rect
def genPixBackDrop(self, im):
# if it is oriented in landscape, rotate it
h, w = im.shape[0:2]
rotated = False
if w < h:
im = np.rot90(im, 3) # 3 or 1 would be equally appropriate
h, w = w, h # swap the variables after rotating
rotated = True
bytesPerLine = 3 * w
# odd bug here, must use .copy() to avoid a mem error.
# see: https://stackoverflow.com/questions/48639185/pyqt5-qimage-from-numpy-array
qImg = QtGui.QImage(im.copy(), w, h, bytesPerLine,
QtGui.QImage.Format_RGB888)
pixmap = QtGui.QPixmap.fromImage(qImg)
width = 120
height = 120
pixmap = pixmap.scaled(width, height,
QtCore.Qt.KeepAspectRatio,
Qt.FastTransformation)
# corrections are doubled due to display image bieng opened at half res
h_correction = h / height
w_correction = w / width
if rotated:
correction = (w_correction, h_correction)
else:
correction = (h_correction, w_correction)
return pixmap, correction
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.drawEllipse(40, 40, 400, 400)
qp.drawPixmap(self.rect(), self.backDrop)
qp.setPen(QtGui.QPen(Qt.green, 1, Qt.SolidLine))
qp.drawEllipse(self.end.x() - 3, self.end.y() - 3, 6, 6)
def mousePressEvent(self, event):
# dialog = self.exec()
self.end = event.pos()
width = self.width()
height = self.height()
end_point = event.pos()
# ensure the annotations are "inside the lines"
e_x = end_point.x()
if e_x < 0:
end_point.setX(0)
elif e_x > width:
end_point.setX(width)
e_y = end_point.y()
if e_y < 0:
end_point.setY(0)
elif e_y > height:
end_point.setY(height)
self.end = end_point
self.update()
self.updateWP()
def updateWP(self):
# qpoint is formatted as (xpos, ypos)
# x col, y row
# save the scale corrected start / end points
x_corr, y_corr = self.correction
e_x = self.end.x()
e_y = self.end.y()
# determine the end (e) points, adjusted for scale
se_x, se_y= int(e_x * x_corr), int(e_y * y_corr)
# update the seed_point attribute in the parent dialog
#self.parent.seed_point = (se_y, se_x)
self.parent.seed_point = (se_x, se_y)
class ImageDialog(QDialog):
def __init__(self, img_array_object):
super().__init__()
self.init_ui(img_array_object)
# set an initial seed_point which fails an if check
self.seed_point = None
def init_ui(self, img_array_object):
mb = Ui_Dialog_image()
mb.setupUi(self)
_translate = QtCore.QCoreApplication.translate
mb.label_dialog.setText(_translate("White Point",
"Failed to determine the white point from the CRC. Please CLICK THE WHITE POINT."))
canv = Canvas(im=img_array_object, parent=self)
mb.gridLayout.replaceWidget(mb.label_Image, canv)
def ask_user_for_seed(self):
dialog = self.exec()
if dialog:
result = self.seed_point
print(result)
return result
else:
return None
class BcDialog(QDialog):
"""
a simple user dialog, for asking what the user to enter a barcode value.
"""
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.mb = Ui_Dialog_noBc()
self.mb.setupUi(self)
self.mb.lineEdit_userBC.setFocus(True)
def ask_for_bc(self):
dialog = self.exec()
if dialog:
result = self.mb.lineEdit_userBC.text()
return result
else:
return None
class TechnicianNameDialog(QDialog):
"""
a UI element to display & and edit the list of stored technician names.
"""
def __init__(self, nameList=[]):
super().__init__()
self.init_ui(nameList)
def init_ui(self, nameList):
self.dialog = Ui_technicianNameDialog()
self.dialog.setupUi(self)
self.dialog.lineEdit_newTechnician.setFocus(True)
# populate the listwidget with nameList passed on creation
listWidget_technicianNames = self.dialog.listWidget_technicianNames
for i, name in enumerate(nameList):
# save the item
listWidget_technicianNames.addItem(name)
# now that it exists set the flag as editable
item = listWidget_technicianNames.item(i)
item.setFlags(item.flags() | Qt.ItemIsEditable)
def edit_technician_list(self):
dialog = self.exec()
if dialog:
result = self.retrieve_technician_names()
else:
result = None
return result
def retrieve_technician_names(self):
"""
harvests all unique technician names
"""
listWidget_technicianNames = self.dialog.listWidget_technicianNames
# Is there no better way to get everything from a listWidget?
names = listWidget_technicianNames.findItems('', Qt.MatchContains)
# alphabetize unique values and return a list
names = list(set(x.text() for x in names))
if '' not in names:
names = [''] + names
return names
def add_item(self):
""" connected to pushButton_add """
listWidget_technicianNames = self.dialog.listWidget_technicianNames
lineEdit_newTechnician = self.dialog.lineEdit_newTechnician
newName = lineEdit_newTechnician.text()
if len(newName) > 0: # if something is written add it to list
listWidget_technicianNames.addItem(newName)
lineEdit_newTechnician.clear()
else: # otherwise, drop a hint: focus on lineEdit_newTechnician
self.dialog.lineEdit_newTechnician.setFocus(True)
def remove_item(self):
""" connected to pushButton_remove """
listWidget_technicianNames = self.dialog.listWidget_technicianNames
selection = listWidget_technicianNames.currentRow()
listWidget_technicianNames.takeItem(selection)
#item = None
class Image_Complete_Emitter(QtCore.QObject):
"""
used to alert when image processing is complete
"""
completed = QtCore.pyqtSignal()
class Timer_Emitter(QtCore.QObject):
"""
used to alert start and stop for entire processing time
"""
timerStart = QtCore.pyqtSignal()
timerStop = QtCore.pyqtSignal()
class appWindow(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.mainWindow = Ui_MainWindow()
self.mainWindow.setupUi(self)
# set up a threadpool
self.threadPool = QThreadPool().globalInstance()
# determine & assign a safe quantity of threads 75% of resources
maxThreads = max([1, int(self.threadPool.maxThreadCount() * .75)])
self.threadPool.setMaxThreadCount(maxThreads)
print(f"Multithreading with maximum "
f"{self.threadPool.maxThreadCount()} threads")
# initiate the persistant settings
# todo update this when name is decided on
self.settings = QSettings('HerbASAP', 'HerbASAP')
self.setWindowIcon(QtGui.QIcon('docs/imgresources/icon_a.ico'))
self.settings.setFallbacksEnabled(False) # File only, no fallback to registry.
# populate the settings based on the previous preferences
self.populateSettings() # this also loads in the settings profile
# restore window geometry & state.
saved_win_geom = self.get("geometry", "")
if saved_win_geom != '':
self.restoreGeometry(saved_win_geom)
saved_win_state = self.get("windowState", "")
if saved_win_state != '':
self.restoreGeometry(saved_win_state)
###
# signaling for the to process image queue
###
self.image_queue = []
self.New_Image_Emitter = New_Image_Emitter()
self.Image_Complete_Emitter = Image_Complete_Emitter()
self.Image_Complete_Emitter.completed.connect(self.process_from_queue)
# using signals to start/stop timers
self.Timer_Emitter = Timer_Emitter()
self.Timer_Emitter.timerStart.connect(self.start_timer)
self.Timer_Emitter.timerStop.connect(self.stop_timer)
self.timer_start = time.time()
# set up classes which do not need re init upon profile loading
self.blurDetect = blurDetect(parent=self.mainWindow)
self.colorchipDetect = ColorchipRead(parent=self.mainWindow)
# Establish base working condition
self.reset_working_variables()
###
# job manaager "boss_thread", it starts itself and is running the __boss_function
###
self.boss_thread = Boss(self.threadPool)
# setup Boss's signals
self.boss_thread.signals.boss_started.connect(self.handle_boss_started)
self.boss_thread.signals.boss_closed.connect(self.handle_boss_finished)
self.boss_thread.signals.job_started.connect(self.handle_job_started)
self.boss_thread.signals.job_finished.connect(self.handle_job_finished)
self.boss_thread.signals.job_result.connect(self.handle_job_result)
self.boss_thread.signals.job_error.connect(self.handle_job_error)
# start the boss thread's "event loop"
# https://doc.qt.io/qt-5/qthread.html#start
self.boss_thread.start(priority=QtCore.QThread.TimeCriticalPriority)
# setup static UI buttons
self.mainWindow.toolButton_delPreviousImage.pressed.connect(self.delete_previous_image)
self.mainWindow.toolButton_editTechnicians.pressed.connect(self.edit_technician_list)
self.versionCheck()
def versionCheck(self):
""" checks the github repo's latest release version number against
local and offers the user to visit the new release page if different"""
# be sure to only do this once a day.
today = str(date.today())
lastChecked = self.get('date_versionCheck', today)
# save the new version check date
self.settings.setValue("date_versionCheck", today)
self.saveSettings()
if today != lastChecked:
import requests
from requests.exceptions import ConnectionError
import webbrowser
apiURL = 'https://api.github.com/repos/CapPow/HerbASAP/releases/latest'
try:
apiCall = requests.get(apiURL)
status = str(apiCall)
except ConnectionError:
# if no internet, don't bother the user.
return
result = apiCall.json()
if '200' in status: # if the return looks bad, don't bother user
url = result['html_url']
version = result['tag_name']
if version.lower() != __version__.lower():
message = f'A new version ( {version} ) of HerbASAP has been released. Would you like to visit the release page?'
title = 'HerbASAP Version'
answer = self.userAsk(message, title)
if answer:# == QMessageBox.Yes:
link=url
self.showMinimized() # hide the app about to pop up.
# instead display a the new release
webbrowser.open(link,autoraise=1)
def closeEvent(self, event):
"""
Reimplimentation of closeEvent handling. This will be run when the user
closes the program.
"""
# check if any critical processes are running
len_queue = len(self.image_queue)
qty_save_jobs = self.working_save_jobs
criticalConditions = [len_queue > 0,
qty_save_jobs > 0,
self.processing_image]
if any(criticalConditions):
# if anything important is running
if len_queue < 2:
# if the queue is short just wait for it to finish
while len_queue > 0:
# could add a status bar update here if we use a status bar
len_queue = len(self.image_queue) # the update variable
time.sleep(1) # a long wait time avoids slowing processing
else:
# if the queue is longer then ask about force quitting.
text = 'Currently Processing Images! Interrupt the running tasks?'
title = "Halt Processing?"
detailText = (
'Closing will interrupt image processing for all queued tasks!\n'
f'Items queued for processing: {len_queue}\n'
f'Qty save jobs running: {qty_save_jobs}\n'
)
user_agree = self.userAsk(text, title, detailText)
if not user_agree:
# user does not want to exit.
return
# if above conditions did not prematurely return then start shutdown.
if self.folder_watcher.is_monitoring:
# if the folder watcher is running, go ahead and stop it.
self.toggle_folder_monitoring()
# save the current window state & location
self.settings.setValue("geometry", self.saveGeometry())
self.settings.setValue("windowState", self.saveState())
# save the current settings
self.saveSettings()
QMainWindow.closeEvent(self, event)
def start_timer(self):
self.timer_start = time.time()
def stop_timer(self):
end_time = time.time()
run_time = round(end_time - self.timer_start, 3)
self.mainWindow.label_processtime.setText(str(run_time))
print(f'Elapsed runtime: {run_time}')
# give app a moment to update
app.processEvents()
def setup_Folder_Watcher(self, raw_image_patterns=None):
"""
initiates self.foldeR_watcher with user inputs.
"""
if not raw_image_patterns:
raw_image_patterns = ['*.tmp', '*.TMP',
'*.cr2', '*.CR2',
'*.tiff', '*.TIFF',
'*.nef', '*.NEF',
'*.orf', '*.ORF']
lineEdit_inputPath = self.profile.get('inputPath', '')
self.folder_watcher = Folder_Watcher(lineEdit_inputPath,
raw_image_patterns)
self.folder_watcher.emitter.new_image_signal.connect(self.queue_image)
self.mainWindow.pushButton_toggleMonitoring.clicked.connect(
self.toggle_folder_monitoring)
def toggle_folder_monitoring(self):
pushButton = self.mainWindow.pushButton_toggleMonitoring
if self.folder_watcher.is_monitoring:
pushButton.setText('Begin folder monitoring')
self.folder_watcher.stop()
else: # if somehow no input path, end early.
if self.profile.get('inputPath', '') == '':
return
pushButton.setText(' Stop folder monitoring')
self.folder_watcher.run()
self.update_session_stats()
def setup_Output_Handler(self):
"""
initiates self.save_output_handler with user inputs.
"""
# each key is a file extension
# each value is a tuple containing (bool if checked, dst path)
self.output_map = {
'.jpg': (self.profile.get('saveProcessedJpg', False), self.profile.get('pathProcessedJpg', '')),
'.raw': (self.profile.get('keepUnalteredRaw', False), self.profile.get('pathUnalteredRaw', ''))}
dupNamingPolicy = self.profile.get('dupNamingPolicy')
# establish self.suffix_lookup according to dupNamingPolicy
# given an int (count of how many files have exact matching names,
# returns an appropriate file name suffix)
if dupNamingPolicy == 'LOWER case letter':
self.suffix_lookup = lambda x: {n+1: ch for n, ch in enumerate(string.ascii_lowercase)}.get(x)
elif dupNamingPolicy == 'UPPER case letter':
self.suffix_lookup = lambda x: {n+1: ch for n, ch in enumerate(string.ascii_uppercase)}.get(x)
elif dupNamingPolicy == 'Number with underscore':
self.suffix_lookup = lambda x: f'_{x}'
elif dupNamingPolicy == 'OVERWRITE original':
self.suffix_lookup = lambda x: ''
else:
self.suffix_lookup = False
def update_metadata(self):
exif_dict = {
# the program's name and verison number
'software': f'HerbASAP, {__version__} ({platform.system()})',
'settingProfile': self.mainWindow.comboBox_profiles.currentText(),
# settings metadata
'collectionName': self.profile.get('collectionName', ''),
'collectionURL': self.profile.get('collectionURL', ''),
'contactEmail': self.profile.get('contactEmail', ''),
'contactName': self.profile.get('contactName', ''),
'copywriteLicense': self.profile.get('copywriteLicense', ''),
# session metadata
'scientificName': self.mainWindow.lineEdit_taxonName.text(),
'recordedBy': self.mainWindow.lineEdit_collectorName.text(),
'imagedBy': self.mainWindow.comboBox_technician.currentText()
}
self.metaRead.update_static_exif(exif_dict)
def save_output_images(self, im, im_base_names, orig_img_path, orig_im_ext,
meta_data=None):
"""
Function that saves processed images to the appropriate format and
locations.
:param im: Processed Image array to be saved.
:type im: cv2 Array
:param im_base_names: the destination file(s) base names. Usually a
catalog number. Passed in as a list of strings.
:type im_base_names: list
:param orig_img_path: Path to the original image
:type orig_img_path: str, path object
:param ext: Extension of the original image with the "."
:type ext: str
:param meta_data: Optional, metadata dictionary organized with
keys as destination metadata tag names, values as key value.
:type meta_data: dict
"""
# disable the toolButton_delPreviousImage button until this is done
self.mainWindow.toolButton_delPreviousImage.setEnabled(False)
im = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)
# reset recently_produced_images
self.recently_produced_images = [orig_img_path]
# see setup_Output_Handler() for details concerning self.output_map
output_map = self.output_map
# breakout output_map into a list of tuples containing (ext, path)
to_save = [(x, y[1]) for x, y in output_map.items() if y[0]]
# store how many save_jobs are expected to global variable
self.working_save_jobs = len(im_base_names) * len(to_save)
# retrieve the source image exif data
# add Additional user comment details for the metadata
h, w = im.shape[0:2]
addtl_user_comments = {
'avgWhiteRGB': str(self.cc_avg_white),
'barcodeValues': self.bc_code,
'isBlurry': str(self.is_blurry),
'origHeight':str(h),
'origWidth':str(w),
'ccQuadrant': str(self.cc_quadrant),
'ccLocation': str(self.cc_location),
'pixelsPerMM': str(self.ppmm),
'pixelsPerMMConfidence': str(self.ppmm_uncertainty)
}
self.meta_data = self.metaRead.retrieve_src_exif(orig_img_path,
addtl_user_comments)
if self.working_save_jobs < 1: # condition when no outputs saved
# treat this process as if it was passed to boss_worker
self.handle_save_result(orig_img_path)
else:
# for each bc_value or file name passed in...
for bc in im_base_names:
for ext, path in to_save:
# not sure of slick way to avoid checking ext twice
if ext == '.raw':
ext = orig_im_ext
file_list = glob.glob(f'{path}//{bc}*{ext}')
file_quantity = len(file_list)
file_suffixes = set()
if file_quantity > 0:
for filename in file_list:
suffix = os.path.basename(filename).replace(bc, '').replace(ext, '')
file_suffixes.add(suffix)
duplicate_naming_policy = self.profile.get('dupNamingPolicy')
new_file_suffix = ''
if duplicate_naming_policy == 'LOWER case letter':
letters = list(string.ascii_lowercase)
while new_file_suffix in file_suffixes:
new_file_suffix += 'a'
for letter in letters:
new_file_suffix = new_file_suffix[:-1]
new_file_suffix += letter
if new_file_suffix not in file_suffixes:
break
elif duplicate_naming_policy == 'UPPER case letter':
letters = list(string.ascii_uppercase)
while new_file_suffix in file_suffixes:
new_file_suffix += 'A'
for letter in letters:
new_file_suffix = new_file_suffix[:-1]
new_file_suffix += letter
if new_file_suffix not in file_suffixes:
break
elif duplicate_naming_policy == 'Number with underscore':
num = 0
while new_file_suffix in file_suffixes:
if new_file_suffix not in file_suffixes:
break
new_file_suffix = f"_{num}"
num += 1
# print(f"File suffixes: {file_suffixes}")
# print(f"New file suffix: {new_file_suffix}")
new_file_base_name = f'{bc}{new_file_suffix}'
new_file_name = f'{path}//{new_file_base_name}{ext}'
if ext == orig_im_ext:
# if it is a raw move just perform it
try:
shutil_move(orig_img_path, new_file_name)
# treat this process as if it was passed to boss_worker
self.handle_save_result(new_file_name)
except FileNotFoundError:
# condition when multiple bcs try to move > once.
# treat this process as if it was passed to boss_worker
self.handle_save_result(False)
else:
# if it a cv2 save function pass it to boss_worker
save_worker_data = SaveWorkerData(new_file_name, im)
save_job = Job('save_worker',
save_worker_data, self._cv2_save)
self.boss_thread.request_job(save_job)
# re-enable the toolButton_delPreviousImage
self.mainWindow.toolButton_delPreviousImage.setEnabled(True)
def _cv2_save(self, new_file_name, im):
"""
cv2.imwrite helper, returns the path if it succeeds, otherwise false.
Exists so that self.handle_save_result recieves filepath if save_job in
save_output_images is properly executed. This is necessary to build the
"self.recently_produced_images" list used in self.delete_previous_image
This could be cleaner, but it'll take a lot of reworking boss_worker.
"""
if cv2.imwrite(new_file_name, im):
return new_file_name
else:
return False
def delete_previous_image(self):
"""
called by pushButton_delPreviousImage, will remove the raw input image
and ALL derived images.
"""
text = ("PERMANENTLY DELETE the most recently captured image AND any "
"images derived from it?")
title = "DELETE Last Image?"
# generate a textual, newline seperated list of items to be removed.
fileList = '\n' + '\n'.join(self.recently_produced_images)
detailText = f'This will permanently the following files:{fileList}'
user_agree = self.userAsk(text, title, detailText)
if user_agree:
self.reset_preview_details()
for imgPath in self.recently_produced_images:
if os.path.isfile(imgPath): # does it exist?
os.remove(imgPath) # if so, remove the file
# disable toolButton_delPreviousImage
self.mainWindow.toolButton_delPreviousImage.setEnabled(False)
self.recently_produced_images = []
if self.folder_watcher.is_monitoring:
# if the folder_watcher is on, subtract removed image from the count
self.folder_watcher.img_count -= 1
self.update_session_stats()
def reset_diagnostic_details(self):
"""
resets the diagnostic texts.
"""
self.mainWindow.label_processtime.setText('')
self.mainWindow.label_barcodes.setText('')
self.mainWindow.label_runtime.setText('')
self.mainWindow.label_whitergb.setText('')
self.mainWindow.label_isBlurry.setText('')
self.mainWindow.label_lapnorm.setText('')
def reset_preview_details(self):
"""
resets the image specific GUI elements.
"""
self.mainWindow.label_imPreview.clear()
self.mainWindow.label_cc_image.clear()
self.reset_diagnostic_details()
def handle_blur_result(self, result):
is_blurry = result['isblurry']
if is_blurry:
# update preview for the coming notice.
if self.im is None:
self.update_preview_img(self.reduced_img)
else:
self.update_preview_img(self.im)
notice_title = 'Blurry Image Warning'
if self.bc_code:
notice_text = f'Warning, {self.bc_code} is blurry.'
else:
notice_text = f'Warning, {self.img_path} is blurry.'
notice_text = notice_text + ('\n\nConsider deleting the image '
'(using the trash can icon), '
'adjusting focus, and retaking the '
'image.')
# lapNorm = laplacian / imVar
detail_text = (
"Normalized laplacian is the variance of openCV's "
"Laplacian operator divided by the variance of the "
"image. Higher values are less blurry. A threshold can be "
"set in the settings tab to determine when this dialog "
"should appear."
f"\n\nlaplacian={result['laplacian']}"
f"\nImg variance ={result['imVar']}\nnormalized "
f"laplacian={result['lapNorm']}")
self.userNotice(notice_text, notice_title, detail_text)
self.is_blurry = is_blurry
self.mainWindow.label_isBlurry.setText(str(is_blurry))
self.mainWindow.label_lapnorm.setText(str(round(result['lapNorm'], 3)))
def handle_save_result(self, result):
""" called when the the save_worker finishes up """
# if result is a path to a new file...
if result:
# for now can only save meta data on jpgs
if result.lower().endswith('.jpg'):
# Add that path to the class variable storing the most recent products.
self.recently_produced_images.append(result)
# Apply the metadata to that saved object
self.metaRead.set_dst_exif(self.meta_data,
result)
# tick off one working_save_job
self.working_save_jobs -= 1
# if we're down to 0 then wrap up
if self.working_save_jobs < 1:
# inform the app when image processing is complete
self.processing_image = False
# reset the stored meta_data
self.meta_data = None
# these are happening too soon
self.Image_Complete_Emitter.completed.emit()
self.Timer_Emitter.timerStop.emit()
def alert_blur_finished(self):
""" called when the results are in from blur detection. """
def handle_bc_result(self, result):
if not result:
# update preview for the coming dialog.
if self.im is None:
self.update_preview_img(self.reduced_img)
else:
self.update_preview_img(self.im)
userDialog = BcDialog()
result = [userDialog.ask_for_bc()]
if result in [[None], ['']]:
result = [self.base_file_name]
self.bc_code = result
self.mainWindow.label_barcodes.setText(', '.join(result))
def alert_bc_finished(self):
""" called when the results are in from bcRead."""
def handle_eq_result(self, result):
# this is returning the corrected image array
self.im = result
def alert_eq_finished(self):
""" called when the results are in from eqRead."""
# boss signal handlers
def handle_boss_started(self, boss_signal_data):
pass
def handle_boss_finished(self, boss_signal_data):
pass
def handle_job_started(self, boss_signal_data):
pass
def handle_job_finished(self, boss_signal_data):
pass
def handle_job_result(self, boss_signal_data):
if boss_signal_data is not None and isinstance(boss_signal_data,
BossSignalData):
if isinstance(boss_signal_data.signal_data, WorkerSignalData):
worker_signal_data = boss_signal_data.signal_data
if worker_signal_data.worker_name == 'bc_worker':
self.handle_bc_result(worker_signal_data.signal_data)
elif worker_signal_data.worker_name == 'blur_worker':
self.handle_blur_result(worker_signal_data.signal_data)
elif worker_signal_data.worker_name == 'eq_worker':
self.handle_eq_result(worker_signal_data.signal_data)
elif worker_signal_data.worker_name == 'save_worker':
self.handle_save_result(worker_signal_data.signal_data)
def handle_job_error(self, boss_signal_data):
if boss_signal_data is not None and isinstance(boss_signal_data,
BossSignalData):
if isinstance(boss_signal_data.signal_data, WorkerSignalData):
worker_signal_data = boss_signal_data.signal_data
print(f'error in worker: {worker_signal_data.worker_name}')
print(f'caught exception: {worker_signal_data.signal_data.exception}')
print(f'error type: {worker_signal_data.signal_data.exctype}')
if worker_signal_data.signal_data is WorkerErrorData:
worker_error_data = worker_signal_data.signal_data
print('error data:')
print(f'exception type: {str(worker_error_data.exctype)}')
print(f'value: {str(worker_error_data.value)}')
print(f'formatted exception: {str(worker_error_data.format_exc)}')
def scale_images_with_info(self, im, largest_dim=1875):
"""
Function that scales images proportionally, and returns both the original image size as a tuple of image
dimensions, and the scaled down image.
:param im: Image to be scaled down.
:type im: cv2 Image
:param largest_dim: The largest dimension to be scaled down to.
:type largest_dim: int
:return: Returns both the original image dimensions as a tuple and the scaled image.
:rtype: tuple, cv2 Image
"""
image_height, image_width = im.shape[0:2]
if image_width > image_height:
reduced_im = cv2.resize(im,
(largest_dim,
round((largest_dim / image_width) * image_height)),
interpolation=cv2.INTER_NEAREST)
else:
reduced_im = cv2.resize(im,
(round((largest_dim / image_height) * image_width),
largest_dim),
interpolation=cv2.INTER_NEAREST)
return (image_width, image_height), reduced_im
def queue_image(self, imgPath):
"""
adds an image path to self.image_queue. Called when a new image is
queued for processing. After adding the item it also attempts to
process_from_queue. If self.processing_image == False it starts the
process.
"""
self.image_queue.append(imgPath)
self.process_from_queue()
def process_from_queue(self):
"""
attempts to process an image in self.image_queue
"""
if not self.processing_image:
# if processing is not ongoing reset_working_variables
self.reset_working_variables()
if len(self.image_queue) > 0:
to_process = self.image_queue.pop(0)
self.processImage(to_process)
def reset_working_variables(self):
"""
sets all class variables relevant to the current working image to None.
"""
self.img_path = None
self.base_file_name = None
self.flip_value = 0
self.ext = None
self.im = None
self.cc_avg_white = None
self.bc_code = []
self.is_blurry = None # could be helpful for 'line item warnings'
self.cc_quadrant = None
self.cc_location = None
self.cropped_cc = None
self.working_save_jobs = 0
self.processing_image = False
self.ppmm = 'N/A'
self.ppmm_uncertainty = 'N/A'
try:
if self.raw_base: # try extra hard to free up these resources.
print('manually forcing closure')
self.raw_base.close()
# reset the image preview text
self.mainWindow.label_imPreview.setText('')
# if some failure occurred attempt to restart the queue.
except AttributeError:
pass # occasion where no raw images have been unpacked yet
self.raw_base = None
def processImage(self, img_path):
"""
given a path to an unprocessed image, performs the appropriate
processing steps.
"""
self.processing_image = True
# reset the diagnostic details
self.reset_preview_details()
# retrieve the profile as a local variable
profile = self.profile
#self.reset_diagnostic_details()
self.mainWindow.label_imPreview.setText('...working')
# give app a moment to update
app.processEvents()
self.Timer_Emitter.timerStart.emit()
self.img_path = img_path
file_name, self.ext = os.path.splitext(img_path)
self.base_file_name = os.path.basename(file_name)
try:
im = self.openImageFile(img_path)
except (LibRawFatalError, LibRawNonFatalError) as e:
# prepare to wipe the slate clean and exit (this function)
self.reset_working_variables()
# attempt to recover from the error
self.process_from_queue()
# if the folder_watcher is operating, update session stats
if self.folder_watcher.is_monitoring:
self.folder_watcher.img_count += 1
self.update_session_stats()
return
print(f'processing: {img_path}')
# converting to greyscale
grey = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
if profile.get('renameByBarcode', True):
# retrieve the barcode values from image
bc_worker_data = BCWorkerData(grey)
bc_job = Job('bc_worker', bc_worker_data, self.bcRead.decodeBC)
self.boss_thread.request_job(bc_job)
if profile.get('blurDetection', True):
# test for bluryness
blur_threshold = profile.get('blurThreshold', 0.045)
blur_worker_data = BlurWorkerData(grey, blur_threshold, True)
blur_job = Job('blur_worker',
blur_worker_data, self.blurDetect.blur_check)
self.boss_thread.request_job(blur_job)
# reduce the image for the cnn, store it incase of problem dialogs
original_size, reduced_img = self.scale_images_with_info(im)
self.reduced_img = reduced_img
# currently this is always returning True as it does not exist in self.profile
scaleDetermination = profile.get('scaleDetermination', False)
verifyRotation = profile.get('verifyRotation', False)
performWhiteBalance = profile.get('performWhiteBalance', False)
if any([scaleDetermination, verifyRotation, performWhiteBalance]):
# colorchecker functions
try:
crc_type = profile.get('crcType', "ISA ColorGauge Nano")
if crc_type == "ISA ColorGauge Nano": # aka small crc
partition_size = profile.get('partition_size', 125)
cc_location, cropped_cc, cc_crop_time = \
self.colorchipDetect.process_colorchip_small(reduced_img,
original_size,
high_precision=True,
partition_size=partition_size)
elif crc_type == 'Tiffen / Kodak Q-13 (8")':
cc_location, cropped_cc, cc_crop_time = self.colorchipDetect.process_colorchip_big(im, pp_fix=1)
else:
cc_location, cropped_cc, cc_crop_time = self.colorchipDetect.process_colorchip_big(im)
x1, y1, x2, y2 = cc_location
if scaleDetermination:
# scale determination code
full_res_cc = im[y1:y2, x1:x2]
# lookup the patch area and seed function
patch_mm_area, seed_func, to_crop = self.scaleRead.scale_params.get(crc_type)
self.ppmm, self.ppmm_uncertainty = self.scaleRead.find_scale(full_res_cc,
patch_mm_area,
seed_func,
to_crop)
print(f"Pixels per mm for {os.path.basename(img_path)}: {self.ppmm}, +/- {self.ppmm_uncertainty}")
self.cc_quadrant = self.colorchipDetect.predict_color_chip_quadrant(original_size, cc_location)
self.cropped_cc = cropped_cc
if performWhiteBalance:
try:
self.cc_avg_white, self.cc_blk_point = self.colorchipDetect.predict_color_chip_whitevals(cropped_cc, crc_type)
# if colorchipDetect fails it will raise a SquareFindingFailed error
except SquareFindingFailed:
# catch it and call the imageDialog
seedDialog = ImageDialog(self.cropped_cc)
seed_pt = seedDialog.ask_user_for_seed()
if seed_pt:
self.cc_avg_white, self.cc_blk_point = self.colorchipDetect.predict_color_chip_whitevals(cropped_cc, crc_type, seed_pt=seed_pt)
else:
raise ColorChipError