forked from sightmachine/SimpleCV
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLineScan.py
More file actions
1299 lines (974 loc) · 35.2 KB
/
Copy pathLineScan.py
File metadata and controls
1299 lines (974 loc) · 35.2 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
from SimpleCV.base import *
import scipy.signal as sps
import scipy.optimize as spo
import numpy as np
import copy, operator
class LineScan(list):
"""
**SUMMARY**
A line scan is a one dimensional signal pulled from the intensity
of a series of a pixels in an image. LineScan allows you to do a series
of operations just like on an image class object. You can also treat the
line scan as a python list object. A linescan object is automatically
generated by calling ImageClass.getLineScan on an image. You can also
roll your own by declaring a LineScan object and passing the constructor
a 1xN list of values.
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> s = img.getLineScan(y=128)
>>>> ss = s.smooth()
>>>> plt.plot(s)
>>>> plt.plot(ss)
>>>> plt.show()
"""
pointLoc = None
image = None
def __init__(self, args, **kwargs):
if isinstance(args, np.ndarray):
args = args.tolist()
list.__init__(self,args)
self.image = None
self.pt1 = None
self.pt2 = None
self.row = None
self.col = None
self.channel = -1
for key in kwargs:
if key == 'pointLocs':
if kwargs[key] is not None:
self.pointLoc = kwargs[key]
if key == 'image':
if kwargs[key] is not None:
self.img = kwargs[key]
if key == 'pt1':
if kwargs[key] is not None:
self.pt1 = kwargs[key]
if key == 'pt2':
if kwargs[key] is not None:
self.pt2 = kwargs[key]
if key == "x":
if kwargs[key] is not None:
self.col = kwargs[key]
if key == "y":
if kwargs[key] is not None:
self.row = kwargs[key]
if key == "channel":
if kwargs[key] is not None:
self.channel = kwargs[key]
if(self.pointLoc is None):
self.pointLoc = zip(range(0,len(self)),range(0,len(self)))
def __getitem__(self,key):
"""
**SUMMARY**
Returns a LineScan when sliced. Previously used to
return list. Now it is possible to use LineScanm member
functions on sub-lists
"""
if type(key) is types.SliceType: #Or can use 'try:' for speed
return LineScan(list.__getitem__(self, key))
else:
return list.__getitem__(self,key)
def __getslice__(self, i, j):
"""
Deprecated since python 2.0, now using __getitem__
"""
return self.__getitem__(slice(i,j))
def __sub__(self,other):
if len(self) == len(other):
retVal = LineScan(map(operator.sub,self,other))
else:
print 'Size mismatch'
return None
retVal._update(self)
return retVal
def __add__(self,other):
if len(self) == len(other):
retVal = LineScan(map(operator.add,self,other))
else:
print 'Size mismatch'
return None
retVal._update(self)
return retVal
def __mul__(self,other):
if len(self) == len(other):
retVal = LineScan(map(operator.mul,self,other))
else:
print 'Size mismatch'
return None
retVal._update(self)
return retVal
def __div__(self,other):
if len(self) == len(other):
try:
retVal = LineScan(map(operator.div,self,other))
except ZeroDivisionError:
print 'Second LineScan contains zeros'
return None
else:
print 'Size mismatch'
return None
retVal._update(self)
return retVal
def _update(self, linescan):
"""
** SUMMARY**
Updates LineScan's Instance Objects.
"""
self.image = linescan.image
self.pt1 = linescan.pt1
self.pt2 = linescan.pt2
self.row = linescan.row
self.col = linescan.col
self.channel = linescan.channel
self.pointLoc = linescan.pointLoc
def smooth(self,degree=3):
"""
**SUMMARY**
Perform a Gasusian simple smoothing operation on the signal.
**PARAMETERS**
* *degree* - The degree of the fitting function. Higher degree means more smoothing.
**RETURNS**
A smoothed LineScan object.
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> plt.plot(sl)
>>>> plt.plot(sl.smooth(7))
>>>> plt.show()
**NOTES**
Cribbed from http://www.swharden.com/blog/2008-11-17-linear-data-smoothing-in-python/
"""
window=degree*2-1
weight=np.array([1.0]*window)
weightGauss=[]
for i in range(window):
i=i-degree+1
frac=i/float(window)
gauss=1/(np.exp((4*(frac))**2))
weightGauss.append(gauss)
weight=np.array(weightGauss)*weight
smoothed=[0.0]*(len(self)-window)
for i in range(len(smoothed)):
smoothed[i]=sum(np.array(self[i:i+window])*weight)/sum(weight)
# recenter the signal so it sits nicely on top of the old
front = self[0:(degree-1)]
front += smoothed
front += self[-1*degree:]
retVal = LineScan(front,image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2)
retVal._update(self)
return retVal
def normalize(self):
"""
**SUMMARY**
Normalize the signal so the maximum value is scaled to one.
**RETURNS**
A normalized scanline object.
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> plt.plot(sl)
>>>> plt.plot(sl.normalize())
>>>> plt.show()
"""
temp = np.array(self, dtype='float32')
temp = temp / np.max(temp)
retVal = LineScan(list(temp[:]),image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2)
retVal._update(self)
return retVal
def scale(self,value_range=(0,1)):
"""
**SUMMARY**
Scale the signal so the maximum and minimum values are
all scaled to the values in value_range. This is handy
if you want to compare the shape of two signals that
are scaled to different ranges.
**PARAMETERS**
* *value_range* - A tuple that provides the lower and upper bounds
for the output signal.
**RETURNS**
A scaled LineScan object.
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> plt.plot(sl)
>>>> plt.plot(sl.scale(value_range(0,255)))
>>>> plt.show()
**SEE ALSO**
"""
temp = np.array(self, dtype='float32')
vmax = np.max(temp)
vmin = np.min(temp)
a = np.min(value_range)
b = np.max(value_range)
temp = (((b-a)/(vmax-vmin))*(temp-vmin))+a
retVal = LineScan(list(temp[:]),image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2)
retVal._update(self)
return retVal
def minima(self):
"""
**SUMMARY**
The function the global minima in the line scan.
**RETURNS**
Returns a list of tuples of the format:
(LineScanIndex,MinimaValue,(image_position_x,image_position_y))
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> minima = sl.smooth().minima()
>>>> plt.plot(sl)
>>>> for m in minima:
>>>> plt.plot(m[0],m[1],'ro')
>>>> plt.show()
"""
# all of these functions should return
# value, index, pixel coordinate
# [(index,value,(pix_x,pix_y))...]
minvalue = np.min(self)
idxs = np.where(np.array(self)==minvalue)[0]
minvalue = np.ones((1,len(idxs)))*minvalue # make zipable
minvalue = minvalue[0]
pts = np.array(self.pointLoc)
pts = pts[idxs]
pts = [(p[0],p[1]) for p in pts] # un numpy this
return zip(idxs,minvalue,pts)
def maxima(self):
"""
**SUMMARY**
The function finds the global maxima in the line scan.
**RETURNS**
Returns a list of tuples of the format:
(LineScanIndex,MaximaValue,(image_position_x,image_position_y))
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> maxima = sl.smooth().maxima()
>>>> plt.plot(sl)
>>>> for m in maxima:
>>>> plt.plot(m[0],m[1],'ro')
>>>> plt.show()
"""
# all of these functions should return
# value, index, pixel coordinate
# [(index,value,(pix_x,pix_y))...]
maxvalue = np.max(self)
idxs = np.where(np.array(self)==maxvalue)[0]
maxvalue = np.ones((1,len(idxs)))*maxvalue # make zipable
maxvalue = maxvalue[0]
pts = np.array(self.pointLoc)
pts = pts[idxs]
pts = [(p[0],p[1]) for p in pts] # un numpy
return zip(idxs,maxvalue,pts)
def derivative(self):
"""
**SUMMARY**
This function finds the discrete derivative of the signal.
The discrete derivative is simply the difference between each
succesive samples. A good use of this function is edge detection
**RETURNS**
Returns the discrete derivative function as a LineScan object.
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> plt.plot(sl)
>>>> plt.plot(sl.derivative())
>>>> plt.show()
"""
temp = np.array(self,dtype='float32')
d = [0]
d += list(temp[1:]-temp[0:-1])
retVal = LineScan(d,image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2)
#retVal.image = self.image
#retVal.pointLoc = self.pointLoc
return retVal
def localMaxima(self):
"""
**SUMMARY**
The function finds local maxima in the line scan. Local maxima
are defined as points that are greater than their neighbors to
the left and to the right.
**RETURNS**
Returns a list of tuples of the format:
(LineScanIndex,MaximaValue,(image_position_x,image_position_y))
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> maxima = sl.smooth().maxima()
>>>> plt.plot(sl)
>>>> for m in maxima:
>>>> plt.plot(m[0],m[1],'ro')
>>>> plt.show()
"""
temp = np.array(self)
idx = np.r_[True, temp[1:] > temp[:-1]] & np.r_[temp[:-1] > temp[1:], True]
idx = np.where(idx==True)[0]
values = temp[idx]
pts = np.array(self.pointLoc)
pts = pts[idx]
pts = [(p[0],p[1]) for p in pts] # un numpy
return zip(idx,values,pts)
def localMinima(self):
"""""
**SUMMARY**
The function the local minima in the line scan. Local minima
are defined as points that are less than their neighbors to
the left and to the right.
**RETURNS**
Returns a list of tuples of the format:
(LineScanIndex,MinimaValue,(image_position_x,image_position_y))
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> minima = sl.smooth().minima()
>>>> plt.plot(sl)
>>>> for m in minima:
>>>> plt.plot(m[0],m[1],'ro')
>>>> plt.show()
"""
temp = np.array(self)
idx = np.r_[True, temp[1:] < temp[:-1]] & np.r_[temp[:-1] < temp[1:], True]
idx = np.where(idx==True)[0]
values = temp[idx]
pts = np.array(self.pointLoc)
pts = pts[idx]
pts = [(p[0],p[1]) for p in pts] # un numpy
return zip(idx,values,pts)
def resample(self,n=100):
"""
**SUMMARY**
Resample the signal to fit into n samples. This method is
handy if you would like to resize multiple signals so that
they fit together nice. Note that using n < len(LineScan)
can cause data loss.
**PARAMETERS**
* *n* - The number of samples to resample to.
**RETURNS**
A LineScan object of length n.
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> plt.plot(sl)
>>>> plt.plot(sl.resample(100))
>>>> plt.show()
"""
signal = sps.resample(self,n)
pts = np.array(self.pointLoc)
# we assume the pixel points are linear
# so we can totally do this better manually
x = linspace(pts[0,0],pts[-1,0],n)
y = linspace(pts[0,1],pts[-1,1],n)
pts = zip(x,y)
retVal = LineScan(list(signal),image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2)
retVal._update(self)
return retVal
# this needs to be moved out to a cookbook or something
#def linear(xdata,m,b):
# return m*xdata+b
# need to add polyfit too
#http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html
def fitToModel(self,f,p0=None):
"""
**SUMMARY**
Fit the data to the provided model. This can be any arbitrary
2D signal. Return the data of the model scaled to the data.
**PARAMETERS**
* *f* - a function of the form f(x_values, p0,p1, ... pn) where
p is parameter for the model.
* *p0* - a list of the initial guess for the model parameters.
**RETURNS**
A LineScan object where the fitted model data replaces the
actual data.
**EXAMPLE**
>>>> def aLine(x,m,b):
>>>> return m*x+b
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> fit = sl.fitToModel(aLine)
>>>> plt.plot(sl)
>>>> plt.plot(fit)
>>>> plt.show()
"""
yvals = np.array(self,dtype='float32')
xvals = range(0,len(yvals),1)
popt,pcov = spo.curve_fit(f,xvals,yvals,p0=p0)
yvals = f(xvals,*popt)
retVal = LineScan(list(yvals),image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2)
retVal._update(self)
return retVal
def getModelParameters(self,f,p0=None):
"""
**SUMMARY**
Fit a model to the data and then return
**PARAMETERS**
* *f* - a function of the form f(x_values, p0,p1, ... pn) where
p is parameter for the model.
* *p0* - a list of the initial guess for the model parameters.
**RETURNS**
The model parameters as a list. For example if you use a line
model y=mx+b the function returns the m and b values that fit
the data.
**EXAMPLE**
>>>> def aLine(x,m,b):
>>>> return m*x+b
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> p = sl.getModelParameters(aLine)
>>>> print p
"""
yvals = np.array(self,dtype='float32')
xvals = range(0,len(yvals),1)
popt,pcov = spo.curve_fit(f,xvals,yvals,p0=p0)
return popt
def convolve(self,kernel):
"""
**SUMMARY**
Convolve the line scan with a one dimenisional kernel stored as
a list. This allows you to create an arbitrary filter for the signal.
**PARAMETERS**
* *kernel* - An Nx1 list or np.array that defines the kernel.
**RETURNS**
A LineScan feature with the kernel applied. We crop off
the fiddly bits at the end and the begining of the kernel
so everything lines up nicely.
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> smooth_kernel = [0.1,0.2,0.4,0.2,0.1]
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> out = sl.convolve(smooth_kernel)
>>>> plt.plot(sl)
>>>> plt.plot(out)
>>>> plt.show()
**SEE ALSO**
"""
out = np.convolve(self,np.array(kernel,dtype='float32'),'same')
retVal = LineScan(out,image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2,channel=self.channel)
return retVal
def fft(self):
"""
**SUMMARY**
Perform a Fast Fourier Transform on the line scan and return
the FFT output and the frequency of each value.
**RETURNS**
The FFT as a numpy array of irrational numbers and a one dimensional
list of frequency values.
**EXAMPLE**
>>>> import matplotlib.pyplot as plt
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(y=128)
>>>> fft,freq = sl.fft()
>>>> plt.plot(freq,fft.real,freq,fft.imag)
>>>> plt.show()
"""
signal = np.array(self,dtype='float32')
fft = np.fft.fft(signal)
freq = np.fft.fftfreq(len(signal))
return (fft,freq)
def ifft(self,fft):
"""
**SUMMARY**
Perform an inverse fast Fourier transform on the provided
irrationally valued signal and return the results as a
LineScan.
**PARAMETERS**
* *fft* - A one dimensional numpy array of irrational values
upon which we will perform the IFFT.
**RETURNS**
A LineScan object of the reconstructed signal.
**EXAMPLE**
>>>> img = Image('lenna')
>>>> sl = img.getLineScan(pt1=(0,0),pt2=(300,200))
>>>> fft,frq = sl.fft()
>>>> fft[30:] = 0 # low pass filter
>>>> sl2 = sl.ifft(fft)
>>>> import matplotlib.pyplot as plt
>>>> plt.plot(sl)
>>>> plt.plot(sl2)
"""
signal = np.fft.ifft(fft)
retVal = LineScan(signal.real)
retVal.image = self.image
retVal.pointLoc = self.pointLoc
return retVal
def createEmptyLUT(self,defaultVal=-1):
"""
**SUMMARY**
Create an empty look up table (LUT).
If default value is what the lut is intially filled with
if defaultVal == 0
the array is all zeros.
if defaultVal > 0
the array is set to default value. Clipped to 255.
if defaultVal < 0
the array is set to the range [0,255]
if defaultVal is a tuple of two values:
we set stretch the range of 0 to 255 to match
the range provided.
**PARAMETERS**
* *defaultVal* - See above.
**RETURNS**
A LUT.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> lut = ls.createEmptyLUT()
>>>> ls2 = ls.applyLUT(lut)
>>>> plt.plot(ls)
>>>> plt.plot(ls2)
>>>> plt.show()
"""
lut = None
if( isinstance(defaultVal,list) or
isinstance(defaultVal,tuple)):
start = np.clip(defaultVal[0],0,255)
stop = np.clip(defaultVal[1],0,255)
lut = np.around(np.linspace(start,stop,256),0)
lut = np.array(lut,dtype='uint8')
lut = lut.tolist()
elif( defaultVal == 0 ):
lut = np.zeros([1,256]).tolist()[0]
elif( defaultVal > 0 ):
defaultVal = np.clip(defaultVal,1,255)
lut = np.ones([1,256])*defaultVal
lut = np.array(lut,dtype='uint8')
lut = lut.tolist()[0]
elif( defaultVal < 0 ):
lut = np.linspace(0,256,256)
lut = np.array(lut,dtype='uint8')
lut = lut.tolist()
return lut
def fillLUT(self,lut,idxs,value=255):
"""
**SUMMARY**
Fill up an existing LUT (look up table) at the indexes specified
by idxs with the value specified by value. This is useful for picking
out specific values.
**PARAMETERS**
* *lut* - An existing LUT (just a list of 255 values).
* *idxs* - The indexes of the LUT to fill with the value.
This can also be a sample swatch of an image.
* *value* - the value to set the LUT[idx] to
**RETURNS**
An updated LUT.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> lut = ls.createEmptyLUT()
>>>> swatch = img.crop(0,0,10,10)
>>>> ls.fillLUT(lut,swatch,255)
>>>> ls2 = ls.applyLUT(lut)
>>>> plt.plot(ls)
>>>> plt.plot(ls2)
>>>> plt.show()
"""
# for the love of god keep this small
# for some reason isInstance is being persnickety
if(idxs.__class__.__name__ == 'Image' ):
npg = idxs.getGrayNumpy()
npg = npg.reshape([npg.shape[0]*npg.shape[1]])
idxs = npg.tolist()
value = np.clip(value,0,255)
for idx in idxs:
if(idx >= 0 and idx < len(lut)):
lut[idx]=value
return lut
def threshold(self,threshold=128,invert=False):
"""
**SUMMARY**
Do a 1D threshold operation. Values about the threshold
will be set to 255, values below the threshold will be
set to 0. If invert is true we do the opposite.
**PARAMETERS**
* *threshold* - The cutoff value for our threshold.
* *invert* - if invert is false values above the threshold
are set to 255, if invert is True the are set to 0.
**RETURNS**
The thresholded linescan operation.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> ls2 = ls.threshold()
>>>> plt.plot(ls)
>>>> plt.plot(ls2)
>>>> plt.show()
"""
out = []
high = 255
low = 0
if( invert ):
high = 0
low = 255
for pt in self:
if( pt < threshold ):
out.append(low)
else:
out.append(high)
retVal = LineScan(out,image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2)
retVal._update(self)
return retVal
def invert(self,max=255):
"""
**SUMMARY**
Do an 8bit invert of the signal. What was black is now
white, what was 255 is now zero.
**PARAMETERS**
* *max* - The maximum value of a pixel in the image, usually 255.
**RETURNS**
The inverted LineScan object.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> ls2 = ls.invert()
>>>> plt.plot(ls)
>>>> plt.plot(ls2)
>>>> plt.show()
"""
out = []
for pt in self:
out.append(255-pt)
retVal = LineScan(out,image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2)
retVal._update(self)
return retVal
def mean(self):
"""
**SUMMARY**
Computes the statistical mean of the signal.
**RETURNS**
The mean of the LineScan object.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> avg = ls.mean()
>>>> plt.plot(ls)
>>>> plt.axhline(y = avg)
>>>> plt.show()
"""
return float(sum(self))/len(self)
def variance(self):
"""
**SUMMARY**
Computes the variance of the signal.
**RETURNS**
The variance of the LineScan object.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> var = ls.variance()
>>>> var
"""
mean = float(sum(self))/len(self)
summation = 0
for num in self:
summation += (num - mean)**2
return summation/len(self)
def std(self):
"""
**SUMMARY**
Computes the standard deviation of the signal.
**RETURNS**
The standard deviation of the LineScan object.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> avg = ls.mean()
>>>> std = ls.std()
>>>> plt.plot(ls)
>>>> plt.axhline(y = avg)
>>>> plt.axhline(y = avg - std, color ='r')
>>>> plt.axhline(y = avg + std, color ='r')
>>>> plt.show()
"""
mean = float(sum(self))/len(self)
summation = 0
for num in self:
summation += (num - mean)**2
return np.sqrt(summation/len(self))
def median(self,sz=5):
"""
**SUMMARY**
Do a sliding median filter with a window size equal to size.
**PARAMETERS**
* *sz* - the size of the median filter.
**RETURNS**
The linescan after being passed through the median filter.
The last index where the value occurs or None if none is found.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> ls2 = ls.median(7)
>>>> plt.plot(ls)
>>>> plt.plot(ls2)
>>>> plt.show()
"""
if( sz%2==0 ):
sz = sz+1
skip = int(np.floor(sz/2))
out = self[0:skip]
vsz = len(self)
for idx in range(skip,vsz-skip):
val = np.median(self[(idx-skip):(idx+skip)])
out.append(val)
for pt in self[-1*skip:]:
out.append(pt)
retVal = LineScan(out,image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2)
retVal._update(self)
return retVal
def findFirstIdxEqualTo(self,value=255):
"""
**SUMMARY**
Find the index of the first element of the linescan that has
a value equal to value. If nothing is found None is returned.
**PARAMETERS**
* *value* - the value to look for.
**RETURNS**
The first index where the value occurs or None if none is found.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> idx = ls.findFIRSTIDXEqualTo()
"""
vals = np.where(np.array(self)==value)[0]
retVal = None
if( len(vals) > 0 ):
retVal = vals[0]
return retVal
def findLastIdxEqualTo(self,value=255):
"""
**SUMMARY**
Find the index of the last element of the linescan that has
a value equal to value. If nothing is found None is returned.
**PARAMETERS**
* *value* - the value to look for.
**RETURNS**
The last index where the value occurs or None if none is found.
**EXAMPLE**
>>>> ls = img.getLineScan(x=10)
>>>> idx = ls.findLastIDXEqualTo()
"""
vals = np.where(np.array(self)==value)[0]
retVal = None
if( len(vals) > 0 ):
retVal = vals[-1]
return retVal
def findFirstIdxGreaterThan(self,value=255):