-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSpotlight.py
2458 lines (2158 loc) · 79.5 KB
/
Spotlight.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/env python
import os
import sys
import string
import copy
import pickle
import math
import struct
import time
import SpotlightCommand
import SpotlightGui
from PIL import Image
import PilProcess
try:
from commands import *
# some application builders require all plugins to be imported
# in order to correctly resolve module dependencies
import encodings.string_escape
import JpegImagePlugin
import TiffImagePlugin
import ArgImagePlugin
import BmpImagePlugin
import CurImagePlugin
import DcxImagePlugin
import EpsImagePlugin
import FliImagePlugin
import FpxImagePlugin
import GbrImagePlugin
import GifImagePlugin
import IcoImagePlugin
import ImImagePlugin
import ImtImagePlugin
#import IptcImagePlugin ####<<<<-- causes deprication warning
import JpegImagePlugin
import McIdasImagePlugin
import MicImagePlugin
import MpegImagePlugin
import MspImagePlugin
import PalmImagePlugin
import PcdImagePlugin
import PcxImagePlugin
import PdfImagePlugin
import PixarImagePlugin
import PngImagePlugin
import PpmImagePlugin
import PsdImagePlugin
import SgiImagePlugin
import SunImagePlugin
import TgaImagePlugin
import WmfImagePlugin
import XVThumbImagePlugin
import XbmImagePlugin
import XpmImagePlugin
except:
pass
#if sys.platform == 'darwin':
# import VideoReaderMac
# define globals
currentfile = ""
nextfile = "" # next numbered file
previousfile = "" # previous numbered file
lastfile = "" # previously loaded file
resultsfile = ''
imageLoaded = False
moving = False
stepsize = 1
tracking = False
frameCounter = 0
framesToTrack = 100000
scaleTool = None
scaleUserUnits = 1.0
scalePixelUnits = 1.0
pixelScale = 1.0
timeScale = 1.0
ctrlKeyDown = False
stopImmediately = False
lastAviFrame = 0
fileType = 'IMG'
stepMode = 0 # 0=frames (both fields), 1=fields (odd first), 2=fields (even first)
currentField = 0
originalMode = 'RGB'
dontAskAgain = False
skipBrokenFiles = False
workingImage = None # all image processing manipulates the workingImage
dirtyWorkingImage = 0 # set whenever working image changes
forceEveryOperationToRedisplay = 0 # 0 for speed, 1 for debugging
"return the directory where this program is installed"
def installDirectory():
return os.path.abspath(sys.path[0])
def createUserDirectory():
"""
On win32 creates a user directory following windows standards. It is
usually located in 'H:\Documents and Settings\klimek\Application Data'
directory.
"""
if sys.platform != "win32":
return
home = os.path.expanduser('~')
datadir = os.path.abspath(os.path.join(home, "Application Data"))
if os.path.exists(datadir):
userdir = os.path.abspath(os.path.join(datadir, "Spotlight-8"))
if os.path.exists(userdir):
pass # Spotlight-8 dir already exists - do nothing
else:
os.mkdir(userdir) # create dir
else:
# Application Data dir doesn't exist so can't append to it a new
# directory so do nothing
pass
def userDirectory():
""" Return the directory where the current user can write files. """
if sys.platform == "win32":
home = os.path.expanduser('~')
datadir = os.path.abspath(os.path.join(home, "Application Data"))
userdir = os.path.abspath(os.path.join(datadir, "Spotlight-8"))
if os.path.exists(userdir):
return userdir
else:
return home
else:
return os.path.expanduser('~')
### define set functions for globals
def setDontAskAgain(flag):
global dontAskAgain
dontAskAgain = flag
def setOriginalMode(d):
'preserves the depth of the file right after it was loaded in'
global originalMode
originalMode = d
def setCurrentField(field):
'sets the field currently being displayed'
global currentField
currentField = field
def setStepMode(mode):
global stepMode
stepMode = mode
def setImageType(type):
global fileType
fileType = type
def setLastAviFrame(n):
global lastAviFrame
lastAviFrame = n
def setStopImmediately(s):
global stopImmediately
stopImmediately = s
def setCtrlKeyDown(key):
global ctrlKeyDown
ctrlKeyDown = key
def setResultsfile(r):
global resultsfile
resultsfile = r
def setPixelScale(s):
global pixelScale
pixelScale = s
def setTimeScale(s):
global timeScale
timeScale = s
def setScaleUserUnits(s):
global scaleUserUnits
scaleUserUnits = s
def setScalePixelUnits(s):
global scalePixelUnits
scalePixelUnits = s
def setTracking(flag):
global tracking
tracking = flag
def setFramesToTrack(f):
global framesToTrack
framesToTrack = f
def setFrameCounter(c):
global frameCounter
frameCounter = c
def setScaleTool(s):
global scaleTool
scaleTool = s
def setImageLoadedFlag(flag):
global imageLoaded
imageLoaded = flag
def setLastFile(file):
'called by openImageFile in frame'
global lastfile
lastfile = file
def setCurrentFile(file):
'called by openImageFile() in frame as well as openImageFile() in Spotlight'
global currentfile
currentfile = file
def setNextFile(file):
global nextfile
nextfile = file
def setPreviousFile(file):
global previousfile
previousfile = file
def setMoving(flag):
global moving
moving = flag
def setStepSize(s):
global stepsize
stepsize = s
def mark(aCharacter):
""" print a mark on the terminal window immediately, for debugging """
sys.stdout.write(aCharacter)
sys.stdout.flush()
def setWorkingImage(img):
""" save the workingImage in a global variable, and schedule display for update"""
global workingImage, dirtyWorkingImage
if workingImage == None:
oldWidth, oldHeight = 0,0
else:
oldWidth, oldHeight = getWorkingImageSize()
workingImage = img
dirtyWorkingImage = 1 # this is the only place this should be set
workingImageWidth, workingImageHeight = getWorkingImageSize()
if oldWidth-workingImageWidth != 0 or oldHeight-workingImageHeight != 0:
SpotlightGui.gui.iPanel.Zoom() # recalculate scroll bars due to image size change
# force the image on the screen to be updated because the workingImage has changed
if forceEveryOperationToRedisplay: # redraws after every processing operation
SpotlightGui.gui.iPanel.updateDisplay()
SpotlightGui.gui.iPanel.Refresh()
def clearDirtyWorkingImageFlag():
global dirtyWorkingImage
dirtyWorkingImage = 0
def setForceEveryOperationToRedisplay(flag):
global forceEveryOperationToRedisplay
forceEveryOperationToRedisplay = flag
def getWorkingImageSize():
""" return the width and height of the working image """
if workingImage == None:
return (0, 0)
else:
width, height = workingImage.size[0], workingImage.size[1] # PIL dependency
return (width, height)
class AoiList:
def __init__(self):
self.currentAoi = -1
self.aoiList = [] # contains selected aoi's
self.urList = [] # undo-redo list - contains latest commands
self.lastExecuted = -1
self.allowRedo = True
def __del__(self):
self = None
def previousAoi(self):
'make the previous aoi current'
self.currentAoi = self.currentAoi - 1
if self.currentAoi <= -1:
self.currentAoi = self.getAoiListLength()-1
self.updateStatusBar0Text()
SpotlightGui.gui.iPanel.Refresh()
def nextAoi(self):
'make the next aoi current'
self.currentAoi = self.currentAoi + 1
if self.currentAoi >= self.getAoiListLength():
self.currentAoi = 0
self.updateStatusBar0Text()
SpotlightGui.gui.iPanel.Refresh()
def setNewAoi(self, aoi):
'add a new aoi to the aoi list'
self.aoiList.append(aoi) # append to end of list
self.currentAoi = self.getAoiListLength() - 1
self.updateStatusBar0Text()
SpotlightGui.gui.iPanel.Refresh()
def updateWholeImageAoi(self, aoi):
'replace first aoi with another aoi'
del self.aoiList[0]
self.aoiList.insert(0, aoi)
def deleteCurrentAoi(self):
'delete the current aoi'
del self.aoiList[self.currentAoi]
# check if the 'last' Aoi was deleted
if self.getAoiListLength() == self.currentAoi:
self.currentAoi = self.currentAoi - 1
self.updateStatusBar0Text()
SpotlightGui.gui.iPanel.Refresh()
def deleteSelectedAoi(self, aoi):
'delete the aoi thats passed in'
if not aoi.isWholeImageAoi():
self.aoiList.remove(aoi)
# check if the 'last' Aoi was deleted
if self.getAoiListLength() == self.currentAoi:
self.currentAoi = self.currentAoi - 1
self.updateStatusBar0Text()
SpotlightGui.gui.iPanel.Refresh()
def deleteAllAois(self):
'delete all aois in the list'
self.currentAoi = self.getAoiListLength() - 1
for i in range(self.currentAoi+1):
aoi = self.getCurrentAoi()
aoi.deinitialize()
if not aoi.isWholeImageAoi():
self.deleteCurrentAoi()
self.currentAoi = self.currentAoi -1
self.currentAoi = 0
SpotlightGui.gui.iPanel.Refresh()
def getAoiListLength(self):
'returns how many aois are in the list'
return len(self.aoiList)
def getCurrentAoi(self):
'returns reference to the current aoi'
if self.getAoiListLength() > 0:
return self.aoiList[self.currentAoi]
else:
return None
def setWholeImageAoiAsCurrent(self):
'sets the WholeImageAoi as the current aoi'
self.currentAoi = 0
SpotlightGui.gui.iPanel.Refresh()
def getWholeImageAoi(self):
'returns reference to the WholeImage aoi'
if self.getAoiListLength() > 0:
return self.aoiList[0]
else:
return None
def getCurrentAoiCoords(self):
'get coords of the current aoi'
if self.getAoiListLength() > 0:
aoi = self.aoiList[self.currentAoi]
x1 = aoi.x1
y1 = aoi.y1
x2 = aoi.x2
y2 = aoi.y2
return (x1, y1, x2, y2)
def updateModelessAois(self, refreshAxes=False):
'updates Histogram and Line Profile dialog boxes'
for aoi in self.aoiList:
aoi.updateModeless(refreshAxes)
def redrawAll(self, dc=None):
""" Redraw AOIs and any other graphic. """
if dc==None:
raise 'dc is None'
self.redrawAois(dc)
if scaleTool:
scaleTool.drawScale(dc)
def redrawAois(self, dc=None):
"""Redraw AOIs - current aoi with a thick line, all others will thin line"""
for aoi in self.aoiList:
if aoi == self.getCurrentAoi():
aoi.drawAoi(True, dc)
else:
aoi.drawAoi(False, dc)
def updateStatusBar0Text(self):
aoi = self.getCurrentAoi()
if aoi:
aoi.updateStatusBar0()
def OnMouseRightDown(self, pos):
'called by OnMouseRightDown()in mtImagePanel class'
aoi = self.getCurrentAoi()
if aoi:
aoi.OnMouseRightDown(pos)
def OnMouseRightDClick(self, pos):
'called by OnMouseRightDClick()in mtImagePanel class'
aoi = self.getCurrentAoi()
if aoi:
aoi.OnMouseRightDClick(pos)
def OnMouseLeftDown(self, pos):
'called by OnMouseLeftDown()in mtImagePanel class'
if scaleTool:
scaleTool.OnMouseLeftDown(pos)
else:
aoi = self.getCurrentAoi()
if aoi:
aoi.OnMouseLeftDown(pos)
def OnMouseLeftUp(self, pos):
'called by OnMouseLeftUp()in mtImagePanel class'
if scaleTool:
scaleTool.OnMouseLeftUp(pos)
else:
aoi = self.getCurrentAoi()
if aoi:
aoi.OnMouseLeftUp(pos)
def OnMouseMove(self, pos):
'called by OnMouseMove()in mtImagePanel class'
if scaleTool:
scaleTool.OnMouseMove(pos)
else:
aoi = self.getCurrentAoi()
if aoi:
aoi.OnMouseMove(pos)
#-------- UndoRedo and processing stuff --------
def do(self, command):
aoi = self.getCurrentAoi()
if self.lastExecuted < len(self.urList) - 1:
self.deleteAllAfterCurrentPosition()
self.urList.append(command)
self.lastExecuted = len(self.urList) - 1
command.initialize(aoi)
command.do(aoi)
self.allowRedo = command.isRedoable()
def undo(self):
if self.lastExecuted >= 0:
c = self.urList[self.lastExecuted]
c.undo()
self.allowRedo = True
self.lastExecuted = self.lastExecuted - 1
def redo(self):
if len(self.urList) == 0:
return
aoi = self.getCurrentAoi()
if self.lastExecuted < len(self.urList) - 1: # middle or beginning of list
self.lastExecuted = self.lastExecuted + 1
c = self.urList[self.lastExecuted]
c.do(aoi)
if self.lastExecuted < len(self.urList) - 1: # still in the middle
self.allowRedo = True
else:
self.allowRedo = c.isRedoable()
else: # last executed command is at end of list
c = self.urList[self.lastExecuted]
self.allowRedo = c.isRedoable()
if self.allowRedo:
#cCopy = copy.deepcopy(c)
cCopy = copy.copy(c)
cCopy.initialize(aoi)
cCopy.do(aoi)
self.urList.append(cCopy)
self.lastExecuted = len(self.urList) - 1
def deleteAllAfterCurrentPosition(self):
urlen = len(self.urList)
n = urlen - self.lastExecuted
deletePosition = self.lastExecuted + 1
for i in range(1, n):
del self.urList[deletePosition]
self.lastExecuted = len(self.urList) - 1
def clearURList(self):
n = len(self.urList)
deletePosition = 0
for i in range(n):
del self.urList[deletePosition]
self.lastExecuted = len(self.urList) - 1
##-------------------- ScaleTool class ----------------------------------------
class ScaleTool:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.lastPoint = (0,0)
self.leftdown = False
self.closest = 0
def initialize(self, userUnits, pixelUnits, timeUnits):
params = {}
self.dd = SpotlightGui.gui.createModelessDialog('ScaleTool', params)
self.dd.GetUserUnits().SetValue(str(userUnits))
self.dd.GetPixelUnits().SetValue(str(pixelUnits))
self.dd.GetTimeUnits().SetValue(str(timeUnits))
sh = self.dd.Show(True)
SpotlightGui.gui.iPanel.Refresh() # calls OnPaint in iPanel
def deinitialize(self):
self.dd.Destroy()
def setParams(self):
userUnits = self.dd.GetUserUnits().GetValue()
pixelUnits = self.dd.GetPixelUnits().GetValue()
timeUnits = self.dd.GetTimeUnits().GetValue()
# user units
if self.isFloat(userUnits):
setScaleUserUnits(float(userUnits))
else:
SpotlightGui.gui.messageDialog('invalid user units value')
# pixel units
if self.isFloat(pixelUnits):
setScalePixelUnits(float(pixelUnits))
else:
SpotlightGui.gui.messageDialog('invalid pixel units value')
# time units
if self.isFloat(timeUnits):
setTimeScale(float(timeUnits))
else:
SpotlightGui.gui.messageDialog('invalid time units value')
setPixelScale(scaleUserUnits / scalePixelUnits)
aList.updateStatusBar0Text()
aList.updateModelessAois()
def isFloat(self, sn):
retCode = True
try:
n = float(sn)
except ValueError:
retCode = False
return retCode
def updateStatusBar0(self):
message = 'Scale: (%3d, %3d) (%3d, %3d)' % (self.x1,self.y1,self.x2,self.y2)
SpotlightGui.gui.updateStatusBar(message, 0)
def drawScale(self, dc=None):
params = {}
pointList = []
points = []
points.append((self.x1, self.y1))
points.append((self.x2, self.y2))
pointList.append(points)
params['pointList'] = pointList
params['highlight'] = True
params['thickness'] = 1
params['lineHandles'] = True
SpotlightGui.gui.iPanel.drawAoi(params, dc)
def OnMouseMove(self, pos):
if self.leftdown:
px = pos[0]
py = pos[1]
offsetWidth = px - self.lastPoint[0]
offsetHeight = py - self.lastPoint[1]
if self.closest == 0: # move Aoi
self.x1 = self.x1 + offsetWidth
self.y1 = self.y1 + offsetHeight
self.x2 = self.x2 + offsetWidth
self.y2 = self.y2 + offsetHeight
else: # move control point
if self.closest == 1: # top left corner
if self.dist(px, py, self.x2, self.y2) > 5: # limit line length to 5 pix
self.x1 = px
self.y1 = py
elif self.closest == 3: # bottom right corner
if self.dist(self.x1, self.y1, px, py) > 5:
self.x2 = px
self.y2 = py
r = self.limitLineMovement(self.x1, self.y1, self.x2, self.y2)
self.x1 = r[0]
self.y1 = r[1]
self.x2 = r[2]
self.y2 = r[3]
self.lastPoint = (px, py)
self.updateStatusBar0()
self.updatePixelUnits()
SpotlightGui.gui.iPanel.Refresh() # calls OnPaint in iPanel
def OnMouseLeftDown(self, pos):
self.closest = self.Closest(pos)
self.leftdown = True
self.lastPoint = pos
def OnMouseLeftUp(self, event):
self.leftdown = False
def updatePixelUnits(self):
d = self.dist(self.x1, self.y1, self.x2, self.y2)
s = '%.2f' % d
self.dd.GetPixelUnits().SetValue(s)
def Closest(self, c):
clos = 0
d = 0.0
dmin = 10e10
d = self.dist(self.x1, self.y1, c[0], c[1])
if (d<dmin and d<10): # "near" is within 10 pixels
dmin = d
clos = 1
d = self.dist(self.x2, self.y2, c[0], c[1])
if (d<dmin and d<10):
dmin = d
clos = 3
return clos
def dist(self, x1, y1, x2, y2):
t1 = t2 = 0.0
t1 = x1 - x2
t2 = y1 - y2
return math.sqrt(t1*t1 + t2*t2)
def limitLineMovement(self, x1, y1, x2, y2):
imX, imY = getWorkingImageSize()
lenx = min(imX, x2-x1)
leny = min(imY, y2-y1)
minXY = 0 # left or top edge of where line can go
maxX = imX # right edge of where line can go
maxY = imY # bottom edge of where line can go
if x1 <= minXY:
x1 = minXY
if y1 == y2:
x2 = x1 + lenx
if abs(y1 - y2) == 1 and x2 < 2:
x2 = 2
if x1 > maxX-1:
x1 = maxX-1
if y1 == y2:
x2 = x1 + lenx
if abs(y1-y2) == 1 and x2 > (maxX-3):
x2 = maxX-3
if x2 < minXY:
x2 = minXY
if y1 == y2:
x1 = x2 - lenx
if abs(y1-y2) == 1 and x1 < 2:
x1 = 2
if x2 > maxX-1:
x2 = maxX-1
if y1 == y2:
x1 = x2 - lenx
if abs(y1-y2) == 1 and x1 > maxX-3:
x1 = maxX - 3
if y1 < minXY:
y1 = minXY
if x1 == x2:
y2 = y1 + leny
if abs(x1-x2) == 1 and y2 < 2:
y2 = 2
if y1 > maxY-1:
y1 = maxY-1
if x1 == x2:
y2 = y1 + leny
if abs(x1-x2) == 1 and y2 > maxY -3:
y2 = maxY - 3
if y2 < minXY:
y2 = minXY
if x1 == x2:
y1 = y2 - leny
if abs(x1-x2) == 1 and y1 < 2:
y1 = 2
if y2 > maxY-1:
y2 = maxY - 1
if x1 == x2:
y1 = y2 - leny
if abs(x1-x2) == 1 and y1 > maxY-3:
y1 = maxY-3
if x1 < minXY: x1 = minXY
if x1 > maxX-1: x1 = maxX-1
if x2 < minXY: x2 = minXY
if x2 > maxX-1: x2 = maxX-1
if y1 < minXY: y1 = minXY
if y1 > maxY-1: y1 = maxY-1
if y2 < minXY: y2 = minXY
if y2 > maxY-1: y2 = maxY-1
return (x1, y1, x2, y2)
##---------- Program Options class ---------------
class ProgramOptions:
def __init__(self):
if sys.platform == 'win32':
prefix = ''
else:
prefix = '.spotlight-'
self.optionsFile = os.path.abspath(os.path.join(userDirectory(), prefix + 'programOptions.txt'))
self.programOptions = self.getProgramOptions()
self.setPaletteDisplay(0) # set initially to off
self.setDVCorrectionType(0) # 0=force square pixels if its DV
self.setArbitraryWidth(640) # height will remain same (480 probably)
self.setPixelDisplayValues(1) # display initially as actual values
self.setDialogBoxTab(0) # initially set to display general options
def getProgramOptions(self):
'returns the latest path stored in the programOptions.txt file'
if os.path.isfile(self.optionsFile):
f = open(self.optionsFile, 'rb')
opt = pickle.load(f)
f.close()
return opt
else:
return {'backgroundColor': 'gray',
'paletteDisplay': 0, # 0=apply palette directly to image
'dvCorrectionType': 0, # 1=True, force square pixels
'arbitraryWidth': 640,
'latestLoadPath': '',
'latestSavePath': '',
'latestLUTPath': '',
'latestResultsPath': '',
'pixelValues': 1,
'expandRange': 0,
'dialogBoxTab': 0}
def setPaletteDisplay(self, paletteType):
"""Don't save the programOptions here because we want to set
the paletteDisplay to 0 on startup, i.e. the checkbox labeled
Apply Palette To Display will always come up not checked each
time the program is started up."""
self.programOptions['paletteDisplay'] = paletteType
def setDVCorrectionType(self, flag):
"""
Don't save because we want to initialize to TRUE.
NOTE: the two check boxes are converted to a single variable (named
"dvCorrectionType") in the dialog box. Essentially they are made to
act like a radio box with three fields. This simplifies the code and logic.
"""
self.programOptions['dvCorrectionType'] = flag
def setArbitraryWidth(self, flag):
"""Don't save because we want to initialize to FALSE """
self.programOptions['arbitraryWidth'] = flag
def setPixelDisplayValues(self, v):
"""Sets how pixel intensities will be displayed. 0=display normalized,
range of (0.0-1.0) and 1=display actual values, range of (0-255).
"""
self.programOptions['pixelValues'] = v
def setDialogBoxTab(self, v):
"""Don't save the programOptions here because we want the dialog box
to always come up with tab 0 each time the program is started up."""
self.programOptions['dialogBoxTab'] = v
def setBackgroundColor(self, color):
self.programOptions['backgroundColor'] = color
self.saveProgramOptions()
def setLatestLoadPath(self, p):
'Keeps track of latest directory and file for load image operation.'
self.programOptions['latestLoadPath'] = p
self.saveProgramOptions()
def setLatestSavePath(self, p):
'Keeps track of latest directory and file for save image operation.'
self.programOptions['latestSavePath'] = p
self.saveProgramOptions()
def setLatestLUTPath(self, p):
'Keeps track of latest directory and file for LUT operation.'
self.programOptions['latestLUTPath'] = p
self.saveProgramOptions()
def setLatestResultsPath(self, p):
'Keeps track of latest directory and file for LUT operation.'
self.programOptions['latestResultsPath'] = p
self.saveProgramOptions()
def saveProgramOptions(self):
'save back to disk'
f = open(self.optionsFile, 'wb')
pickle.dump(self.programOptions, f)
f.close()
##------------- Results class ----------------------------------------
class Results:
"""
This class holds and saves the output data generated by the tracking
process. The main parameter self.data is a list and each item in it is
another list, which may contain only a single item (like x trackpoint)
or may contain many items (like a histogram). Here is a sample
representing a framenumber, x, y, and a very short lineprofile (3 pts):
[[' 1 '], [' 123 '], [' 21 '], [' 12 ', ' 34 ', ' 124 ']]
"""
def __init__(self):
self.data = []
def clearData(self):
self.data = []
def clearHeader(self):
self.header = []
self.aoiHeader = []
if timeScale == 1.0:
self.header.append('| Frame |')
else:
self.header.append('| Time |')
def addScaleHeader(self):
"""adds the scale header"""
u = scaleUserUnits
p = scalePixelUnits
s = "Scale Factor - user units: %.5f image units: %.5f" % (u, p)
self.aoiHeader.append(s)
def addAoiHeader(self, header, aoicount = -1):
'adds image name and aoi type'
s = 'Aoi ' + str(aoicount+1) + ': ' + header
self.aoiHeader.append(s)
def addFilenameHeader(self):
path, file = os.path.split(nextfile)
name, ext = os.path.splitext(file)
# add the full path of first file
imgname, numb = splitExtendedFilename(os.path.abspath(nextfile))
imgPath = 'Starting Image: ' + imgname
self.aoiHeader.append(imgPath)
# add the word fileaname (next to Frame) in the header of various widths
if len(name) <= 8:
self.header.append(' filename |')
elif len(name) > 8 and len(name) <= 13:
self.header.append(' filename |')
elif len(name) > 13 and len(name) <= 19:
self.header.append(' filename |')
elif len(name) > 19 and len(name) <= 29:
self.header.append(' filename |')
else:
self.header.append(' filename |')
def addFrameNumber(self, d):
"""
Adds the frame number to first column.
"""
if timeScale == 1.0:
sn = str(d)
if stepMode == 0:
sframe = sn.rjust(5) # right justified in a string 5 wide
s = ' ' + sframe + ' '
else:
sframe = sn.rjust(5)
f = getFieldName()
if f == '':
field = ' ' # blank space
else:
field = f[13] # 13th char is either an 'o' or an 'e'
s = ' ' + sframe + ' ' + field + ' '
f = []
f.append(s)
self.data.append(f)
else:
d = d / timeScale
sn = '%.5f' % d
if stepMode == 0:
sframe = sn.rjust(12) # right justified in a string 5 wide
s = ' ' + sframe + ' '
else:
sframe = sn.rjust(12)
f = getFieldName()
if f == '':
field = ' ' # blank space
else:
field = f[13] # 13th char is either an 'o' or an 'e'
s = ' ' + sframe + ' ' + field + ' '
f = []
f.append(s)
self.data.append(f)
def addFilename(self):
"""
Adds the image filename to second column.
"""
path, file = os.path.split(currentfile)
name, ext = os.path.splitext(file)
sname = str(name)
# make width relative to the header
w = len(self.header[1]) # width of filename header
sn = sname.rjust(w-4) + ' '
f = []
f.append(sn)
self.data.append(f)
def addHeader(self, header, aoicount):
"""
Adds a one line header to the data file. The header is just a string.
"""
c = str(aoicount+1)
for i in range(len(header)):
h = header[i]
for j in range(len(h)):
s = ' ' + h[j] + ' (aoi ' + c + ')' + ' ' + '|'
self.header.append(s)
def addTrackData(self, trackPointLabel):
if trackPointLabel != (): # skip if empty
n = len(trackPointLabel)
for i in range(n):
field = trackPointLabel[i]
self.data.append(field)
def addData(self, d):
"""
Formats the self.data list. The data (d) that's passed in is a
list containing other lists.
"""
if len(d) > 0:
for item in d:
self.data.append(item)
def writeHeaderToDisk(self, file, writeAoiHeader = True):
"""
Write out the header info contained in self.aoiHeader and self.header.
The writeAoiHeader flag is for specifying when and when not to write
out the aoiHeader.
"""
f = open(file, 'a')
# write image name and aoi type
f.write('\n')
if writeAoiHeader: # needed only the first time
for i in range(len(self.aoiHeader)):
h = self.aoiHeader[i]
f.write(h + '\n')
# write a solid line
n = 0
for d in self.header:
n = n + len(d)
blanks = '_' * n
f.write(blanks + '\n')
# write the main header (processing operations)
h = ''
for i in range(len(self.header)):
h = h + self.header[i]
f.write(h + '\n' + '\n')
f.close()
def writeDataToDisk(self, file):
"""
Write out the data to disk each frame. The data has accumulated in
self.data from multiple aois and/or from multiple operations that have
an data output. The data is formatted by adding blanks where needed so
that long output data (such as histogram) line up in columns.
"""
longest = self.getLongest()
# generate an output list in which blanks are added.
outList = []
for x in range(len(self.header)):
d = self.data[x]
col = [] # one column (vertical) which will contain data and blanks
for i in range(longest):
if len(d) > i:
col.append(d[i])
else:
n = len(self.header[x])
sgap = ' ' * n
col.append(sgap)
outList.append(col)
# add a new header if frame number is not 1 (we're in continuous tracking)
# and we have a long data type (such as histogram)
if self.data[0][0] != ' 1 ' and longest > 1:
self.writeHeaderToDisk(file, False)
# write out the formatted data contained in the outList
f = open(file, 'a')
for y in range(longest):
out = ''
for d in outList:
item = d[y]
out = out + item
f.write(out + '\n')
f.close()
self.clearData() # clear out the data buffer after each frame
def getLongest(self):
"""
Get longest data element (list) in self.data - some are single data
point and others could be line profiles or histograms which have
many data points.
"""
longest = 0
for i in range(len(self.data)):
if len(self.data[i]) > longest:
longest = len(self.data[i])
return longest
##-------------- Instantiate classes ---------------------------------------
createUserDirectory()
aList = AoiList() # after AoiList class has been defined
pOptions = ProgramOptions()
results = Results() # hold and formats tracking results
resultsfile = pOptions.programOptions['latestResultsPath']
if resultsfile == '':
resultsfile = os.path.abspath(os.path.join(userDirectory(), 'results.txt'))
##-------------- Image functions --------------------------