-
Notifications
You must be signed in to change notification settings - Fork 1
/
discscsp.py
2180 lines (1722 loc) · 84.4 KB
/
discscsp.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
"""Discrete Scale Space and Scale-Space Derivative Toolbox for Python
For computing discrete scale-space smoothing by convolution with the discrete
analogue of the Gaussian kernel and for computing discrete derivative approximations
by applying central difference operators to the smoothed data. Then, different
types of feature detectors can be defined, by combining discrete analogues of the
Gaussian derivative operators into differential expressions.
This code is the result of porting a subset of the routines in the Matlab packages
discscsp and discscspders to Python, however, with different interfaces for some
of the functions.
Note: The scale normalization does not explicitly compensate for the additional
variance 1/12 for the integrated Gaussian kernel or the additional variance 1/6
for the linearly integrated Gaussian kernel at coarser scales.
References:
Lindeberg (1990) "Scale-space for discrete signals", IEEE Transactions on
Pattern Analysis and Machine Intelligence, 12(3): 234-254.
Lindeberg (1993a) "Discrete derivative approximations with scale-space properties:
A basis for low-level feature detection", Journal of Mathematical Imaging and
Vision, 3(4): 349-376.
Lindeberg (1993b) Scale-Space Theory in Computer Vision, Springer.
Lindeberg (1998a) "Feature detection with automatic scale selection",
International Journal of Computer Vision, vol 30(2): 77-116.
Lindeberg (1998b) "Edge detection and ridge detection with automatic scale selection",
International Journal of Computer Vision, vol 30(2): 117-154.
Lindeberg (2009) "Scale-space". In: B. Wah (Ed.) Wiley Encyclopedia of Computer
Science and Engineering, John Wiley & Sons, pp. 2495-2504.
Lindeberg (2015) "Image matching using generalized scale-space interest points",
Journal of Mathematical Imaging and Vision, 52(1): 3-36.
Limitations:
Compared to the original Matlab code, the following implementation is reduced
in the following ways:
- much fewer functions of the N-jet have so far been implemented,
- there is no passing of additional parameters to functions of the N-jet,
- this reimplementation has not been thoroughly tested.
"""
from math import sqrt, exp, ceil, pi, cos, sin
from typing import NamedTuple, Union, List
import numpy as np
from scipy.ndimage import correlate1d, correlate
from scipy.special import ive, erf, erfcinv
class ScSpMethod(NamedTuple):
"""Object for storing the parameters of a scale-space discretization method,
which can be of either of the types 'discgauss', 'samplgauss', 'normsamplgauss',
'intgauss' or 'linintgauss'
"""
methodname: str
epsilon: float
class ScSpNormDerMethod(NamedTuple):
"""Object for storing the parameters of a discretization method for computing
scale-normalized derivatives, including also the necessary parameters of the
underlying method for discrete approximation of the Gaussian smoothing operation.
"""
scspmethod: ScSpMethod
normdermethod: str # either 'nonormalization' or 'varnorm'
def scspnormdermethodobject(
scspmethod : str = 'discgauss',
normdermethod : str = 'varnorm',
epsilon : float = 0.00000001
) -> ScSpNormDerMethod :
"""Creates an object that contains the parameters of discretization method
for computing scale-normalized derivatives, with default values for a preferred
choice.
"""
return ScSpNormDerMethod(ScSpMethod(scspmethod, epsilon), normdermethod)
def scspconv(
inpic,
sigma : float,
scspmethod : Union[str, ScSpMethod] = 'discgauss',
epsilon : float = 0.00000001
) -> np.ndarray :
"""Computes the scale-space representation of the 2-D image inpic (or a 1-D signal)
at scale level sigma in units of the standard deviation of the Gaussian kernel,
that is approximated discretely with the method scspmethod, and with the formally
infinite convolution operation truncated at the tails with a relative approximation
error less than epsilon.
The following discrete approximation methods have been implemented:
'discgauss' - the discrete analogue of the Gaussian kernel
'samplgauss' - the sampled Gaussian kernel
'normsamplgauss' - the normalized sampled Gaussian kernel
'intgauss' - the integrated Gaussian kernel
'linintgauss' - the linearily interpolated and integrated Gaussian kernel
The discrete analogue of the Gaussian kernel has the best theoretical properties
of these kernels, in the sense that it obeys both (i) non-enhancement of local
extrema over a 2-D spatial domain and (ii) non-creation of local extrema from
any finer to any coarser level of scale for any 1-D signal. The filter coefficents
are (iii) guaranteed to be in the interval [0, 1] and do (iv) exactly sum to one
for an infinitely sized filter. (v) The spatial standard deviation of the discrete
kernel is also equal to the sigma value.
The different methods have the possible advantages (+) and disadvantages (-):
'discgauss' + guarantees non-enhancement of local extrema over a 2-D image domain
+ guarantees non-creation of new extrema from any finer to any
coarser level of scale over a 1-D signal domain
+ the kernel values are guaranteed to be in the interval [0, 1]
+ the kernel values are guaranteed to sum to 1 over an infinite domain
+ no scale offset at all in the spatial discretization
'samplgauss' + good approx of continuous model for sufficiently large scale values
+ no added scale offset in the spatial discretization
- the kernel values may become greater than 1 for small values of sigma
- the kernel values do not sum up to one
- for very small values of sigma, the kernels have a too narrow shape
'normsamplgauss' + no added scale offset in the spatial discretization
+ formally the kernel values are guaranteed to be in the
interval [0, 1]
+ formally the kernel values are guaranteed to sum up to 1
- the complementary normalization of the kernel is ad hoc
- for very small values of sigma, the kernels have a too narrow
shape
'intgauss' + the kernel values are guaranteed to be in the interval [0, 1]
+ the kernel values are guaranteed to sum up to 1 over an infinite domain
- the box integration introduces a scale offset of 1/12 at coarser scales
'linintgauss' + the kernel values are guaranteed to be in the interval [0, 1]
- the triangular window integration introduces a scale offset of 1/6
at coarser scales
Besides being a string, the argument scspmethod may also be an object
having the attributes scspmethod.methodname and scspmethod.epsilon.
The parameter epsilon specifies an upper bound on the relative truncation error
for separable filtering over a D-dimensional domain.
"""
if isinstance(scspmethod, str):
scspmethodname = scspmethod
else:
scspmethodname = scspmethod.methodname
epsilon = scspmethod.epsilon
if scspmethodname == 'discgauss':
outpic = discgaussconv(inpic, sigma, epsilon)
elif scspmethodname == 'samplgauss':
outpic = samplgaussconv(inpic, sigma, epsilon)
elif scspmethodname == 'normsamplgauss':
outpic = normsamplgaussconv(inpic, sigma, epsilon)
elif scspmethodname == 'intgauss':
outpic = intgaussconv(inpic, sigma, epsilon)
elif scspmethodname == 'linintgauss':
outpic = linintgaussconv(inpic, sigma, epsilon)
else:
raise ValueError(f'Scale space method {scspmethodname} not implemented')
return outpic
def scspconv_mult(
inpic,
sigmavec : List[float],
scspmethod : Union[str, ScSpMethod] = 'discgauss',
epsilon : float = 0.00000001
) -> np.ndarray :
"""Performs a similar function as the function scscpconv, with the
difference that an array of sigma values can be provided instead of a
single value, and that the cascade smoothing property of Gaussian
convolution is then made use of to perform the computational more
efficiently than if applying the scspconv function for each
scale level separately.
Note, however, that the cascade smoothing property works best when
using the discrete analogue of the Gaussian kernel 'discgauss', for
which the cascade smoothing property holds exactly in the ideal
case of an infinite image domain with kernels the smoothing kernels
having infinite support. For the other ways of approximating the
Gaussian kernel discretely, there may be deviations depending on
the scale values.
The output will be an array of one dimension more than for the
function scspconv.
Note that the scale values in the list sigmavec must be in
increasing order.
"""
ndim = inpic.ndim
if ndim == 1:
outpic = np.zeros((len(sigmavec), len(inpic)))
smoothpic = scspconv(inpic, sigmavec[0], scspmethod, epsilon)
outpic[0, :] = smoothpic[:]
for i in range(1, len(sigmavec)):
sigmainc = sqrt(sigmavec[i] ** 2 - sigmavec[i-1] ** 2)
smoothpic = scspconv(smoothpic, sigmainc, scspmethod, epsilon)
outpic[i, :] = smoothpic[:]
elif ndim == 2:
outpic = np.zeros((len(sigmavec),) + inpic.shape)
smoothpic = scspconv(inpic, sigmavec[0], scspmethod, epsilon)
outpic[0, :, :] = smoothpic[:, :]
for i in range(1, len(sigmavec)):
sigmainc = sqrt(sigmavec[i] ** 2 - sigmavec[i-1] ** 2)
smoothpic = scspconv(smoothpic, sigmainc, scspmethod, epsilon)
outpic[i, :, :] = smoothpic[:, :]
elif ndim == 3:
outpic = np.zeros((len(sigmavec),) + inpic.shape)
smoothpic = scspconv(inpic, sigmavec[0], scspmethod, epsilon)
outpic[0, :, :, :] = smoothpic[:, :, :]
for i in range(1, len(sigmavec)):
sigmainc = sqrt(sigmavec[i] ** 2 - sigmavec[i-1] ** 2)
smoothpic = scspconv(smoothpic, sigmainc, scspmethod, epsilon)
outpic[i, :, :, :] = smoothpic[:, :, :]
else:
raise ValueError(f'Cannot handle images of dimensionality {ndim}')
return outpic
def scaleoffset_variance(
scspmethod : Union[str, ScSpMethod] = 'discgauss'
) -> float :
"""Returns the scale offset that the scale-space discretization method
scspmethod gives rise to at coarser scales. At finer scales, however,
the added offset may be lower.
Note that this scale offset is given in units of the variance s = sigma^2
of the kernel, as opposed to the standard deviation sigma, motivated by
the additive property of variances under convolution of non-negative kernels.
"""
if isinstance(scspmethod, str):
scspmethodname = scspmethod
else:
scspmethodname = scspmethod.methodname
if scspmethodname == 'discgauss':
scaleoffset = 0.0
elif scspmethodname == 'samplgauss':
scaleoffset = 0.0
elif scspmethodname == 'normsamplgauss':
scaleoffset = 0.0
elif scspmethodname == 'intgauss':
scaleoffset = 1/12
elif scspmethodname == 'linintgauss':
scaleoffset = 1/6
else:
raise ValueError(f'Scale space method {scspmethodname} not implemented')
return scaleoffset
def discgaussconv(
inpic,
sigma : float,
epsilon : float = 0.00000001
) -> np.ndarray :
"""Convolves the 2-D image inpic (or a 1-D signal) with the discrete analogue of
the Gaussian kernel with standard deviation sigma and relative truncation error
less than epsilon.
Convolution with this kernel corresponds to solving a spatially discretized version
of the diffusion equation with the time variable = sigma^2 being continuous.
Over a 2-D spatial domain, the resulting scale-space representation obeys
non-enhancement of local extrema, meaning that the intensity value at any
spatial maximum is guaranteed to not increase with scale and that the
intensity value at any spatial minimum is guaranteed to not decrease.
Over a 1-D spatial domain, the resulting scale-space representation does
also obey non-creation of local extrema, meaning that the number of local
extrema in the smoothed signal is guaranteed to not increase with scale.
The spatial standard deviation of the resulting kernel is exactly equal
to the scale parameter sigma over an infinite spatial domain. These kernel
values do also in the ideal infinite case exactly sum up to one, and are
also confined in the interval [0, 1].
Reference: Lindeberg (1990) "Scale-space for discrete signals", IEEE Transactions
on Pattern Analysis and Machine Intelligence, 12(3): 234-254.
"""
ndim = inpic.ndim
sep1Dfilter = make1Ddiscgaussfilter(sigma, epsilon, ndim)
if ndim == 1:
outpic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter)
elif ndim == 2:
tmppic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter, 0)
outpic = correlate1d(tmppic, sep1Dfilter, 1)
elif ndim == 3:
# Treat as multilayer image
outpic = np.zeros(inpic.shape)
for layer in range(0, inpic.shape[2]):
outpic[:, :, layer] = discgaussconv(inpic[:, :, layer], sigma, epsilon)
else:
raise ValueError(f'Cannot handle images of dimensionality {ndim}')
return outpic
def make1Ddiscgaussfilter(
sigma : float,
epsilon : float = 0.00000001,
D : int = 1
) -> np.ndarray :
"""Generates a 1-D discrete analogue of the Gaussian kernel at scale level sigma
in units of the standard deviation of the kernel and with relative truncation error
not exceeding epsilon as a relative number over a D-dimensional spatial domain.
"""
s = sigma*sigma
tmpvecsize = ceil(1 + 1.5*gaussfiltsize(sigma, epsilon, D))
# Generate filter coefficients from the modified Bessel functions
longhalffiltvec = ive(np.arange(0, tmpvecsize+1), s)
halffiltvec = truncfilter(longhalffiltvec, truncerrtransf(epsilon, D))
filtvec = mirrorhfilter(halffiltvec)
return filtvec
def samplgaussconv(
inpic,
sigma : float,
epsilon : float = 0.00000001
) -> np.ndarray :
"""Convolves the 2-D image inpic (or a 1-D signal) with the sampled Gaussian
kernel with standard deviation sigma and relative truncation error less than
epsilon.
The transformation from the input image will always be a scale-space transformation,
in the sense that for a 1-D signal the number of local extrema in the smoothed
signal are guaranteed to not exceed the number of local extrema in the input image.
The transformation between adjacent scale levels is, however, not guaranteed to
be a scale-space transformation.
For sufficiently large values of the scale parameter, the sampled Gaussian kernel
leads to good approximations of the continuous scale-space model. For smaller values
of sigma, the kernel values do not, however, sum to one, and they may even go
outside the interval [0, 1], which are not a desirable properties.
For a theoretical explanations of these properties, see Section VII.A in
Lindeberg (1990) "Scale-space for discrete signals", IEEE Transactions on
Pattern Analysis and Machine Intelligence, 12(3): 234-254.
or Section 3.6.1 in
Lindeberg (1993b) Scale-Space Theory in Computer Vision, Springer.
"""
ndim = inpic.ndim
sep1Dfilter = make1Dsamplgaussfilter(sigma, epsilon, ndim)
if ndim == 1:
outpic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter)
elif ndim == 2:
tmppic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter, 0)
outpic = correlate1d(tmppic, sep1Dfilter, 1)
elif ndim == 3:
# Treat as multilayer image
outpic = np.zeros(inpic.shape)
for layer in range(0, inpic.shape[2]):
outpic[:, :, layer] = samplgaussconv(inpic[:, :, layer], sigma, epsilon)
else:
raise ValueError(f'Cannot handle images of dimensionality {ndim}')
return outpic
def make1Dsamplgaussfilter(
sigma : float,
epsilon : float = 0.00000001,
D : int = 1
) -> np.ndarray :
"""Generates a sampled Gaussian kernel with standard deviation sigma, given an
upper bound on the relative truncation error epsilon over a D-dimensional domain.
"""
vecsize = ceil(1.1*gaussfiltsize(sigma, epsilon, D))
x = np.linspace(-vecsize, vecsize, 1+2*vecsize)
return gauss(x, sigma)
def gauss(x : np.ndarray, sigma : float = 1.0) -> np.ndarray :
"""Computes a Gaussian function given a set of spatial x-coordinates and sigma
value specifying the standard deviation of the kernel.
"""
return 1/(sqrt(2*pi)*sigma)*np.exp(-(x**2/(2*sigma**2)))
def normsamplgaussconv(
inpic,
sigma : float,
epsilon : float = 0.00000001
) -> np.ndarray :
"""Convolves the 2-D image inpic (or a 1-D signal) with the normalized
sampled Gaussian kernel with standard deviation sigma and relative truncation
error less than epsilon.
The transformation from the input image will always be a scale-space transformation,
in the sense that for a 1-D signal the number of local extrema in the smoothed
signal are guaranteed to not exceed the number of local extrema in the input image.
The transformation between adjacent scale levels is, however, not guaranteed to
be a scale-space transformation.
By a normalization of the discrete sampled Gaussian filter to unit l_1-norm,
this approach avoids the problems that the regular sampled Gaussian kernel
may assume values greater than 1 and the kernel values do not sum to 1.
The resulting filter kernel will, however, still be too narrow at very
fine scale, meaning that the normalization does not really solve the
real problems with the sampled Gaussian kernel at very fine scales.
For a theoretical explanations of the properties of the regular sampled
Gaussian kernel, see Section VII.A in
Lindeberg (1990) "Scale-space for discrete signals", IEEE Transactions on
Pattern Analysis and Machine Intelligence, 12(3): 234-254.
or Section 3.6.1 in
Lindeberg (1993b) Scale-Space Theory in Computer Vision, Springer.
"""
ndim = inpic.ndim
sep1Dfilter = make1Dnormsamplgaussfilter(sigma, epsilon, ndim)
if ndim == 1:
outpic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter)
elif ndim == 2:
tmppic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter, 0)
outpic = correlate1d(tmppic, sep1Dfilter, 1)
elif ndim == 3:
# Treat as multilayer image
outpic = np.zeros(inpic.shape)
for layer in range(0, inpic.shape[2]):
outpic[:, :, layer] = normsamplgaussconv(inpic[:, :, layer], sigma, epsilon)
else:
raise ValueError(f'Cannot handle images of dimensionality {ndim}')
return outpic
def make1Dnormsamplgaussfilter(
sigma : float,
epsilon : float = 0.00000001,
D : int = 1
) -> np.ndarray :
"""Generates a normalized sampled Gaussian kernel with standard deviation sigma,
given an upper bound on the relative truncation error epsilon over a D-dimensional
domain.
"""
prelfilter = make1Dsamplgaussfilter(sigma, epsilon, D)
return prelfilter/np.sum(prelfilter)
def intgaussconv(
inpic,
sigma : float,
epsilon : float = 0.00000001
) -> np.ndarray :
"""Convolves the 2-D image inpic (or a 1-D signal) with the box integrated
Gaussian kernel with standard deviation sigma and relative truncation error less
than epsilon, according to Equation (3.89) on page 97 in Lindeberg (1993)
Scale-Space Theory in Computer Vision, published by Springer.
The transformation from the input image will always be a scale-space transformation,
in the sense that for a 1-D signal the number of local extrema in the smoothed
signal are guaranteed to not exceed the number of local extrema in the input image.
The transformation between adjacent scale levels is, however, not guaranteed to
be a scale-space transformation.
The kernel values of the resulting discrete approximation of the Gaussian kernel
do in the ideal infinite case exactly sum up to one, and are also confined in the
interval [0, 1]. The spatial integration of the Gaussian kernel over the support
region of each pixel does, however, add a scale offset of 1/12 in units of the
variance equal to the squared standard deviation of the kernel at coarser scales.
This added variance corresponds to the spatial variance of a box filter over the
support region of the image pixel over which the continuous Gaussian kernel is
integrated.
For a theoretical explanation of these properties, see Section 3.6.3 in
Lindeberg (1993b) Scale-Space Theory in Computer Vision, Springer.
"""
ndim = inpic.ndim
sep1Dfilter = make1Dintgaussfilter(sigma, epsilon, ndim)
if ndim == 1:
outpic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter)
elif ndim == 2:
tmppic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter, 0)
outpic = correlate1d(tmppic, sep1Dfilter, 1)
elif ndim == 3:
# Treat as multilayer image
outpic = np.zeros(inpic.shape)
for layer in range(0, inpic.shape[2]):
outpic[:, :, layer] = intgaussconv(inpic[:, :, layer], sigma, epsilon)
else:
raise ValueError(f'Cannot handle images of dimensionality {ndim}')
return outpic
def make1Dintgaussfilter(
sigma : float,
epsilon : float = 0.00000001,
D : int = 1
) -> np.ndarray :
"""Generates a box integrated Gaussian kernel with standard deviation sigma,
according to Equation (3.89) on page 97 in Lindeberg (1993) Scale-Space Theory
in Computer Vision (published by Springer), given an upper bound on the
relative truncation error epsilon over a D-dimensional domain.
Remark: Adds additional spatial variance 1/12 to the kernel at coarser scales.
"""
vecsize = ceil(1.1*gaussfiltsize(sigma, epsilon, D))
x = np.linspace(-vecsize, vecsize, 1+2*vecsize)
return scaled_erf(x + 0.5, sigma) - scaled_erf(x - 0.5, sigma)
def scaled_erf(x : np.ndarray, sigma : float = 1.0) -> np.ndarray :
"""Computes the scaled error function (as depending on a scale parameter sigma)
given an array of x-coordinates.
"""
return 1/2*(1 + erf(x/(sqrt(2)*sigma)))
def linintgaussconv(
inpic,
sigma : float,
epsilon : float = 0.00000001
) -> np.ndarray :
"""Convolves the 2-D image inpic (or a 1-D signal) with the linearily
integrated Gaussian kernel with standard deviation sigma and relative
truncation error less than epsilon, according to Equation (3.89) on
page 97 in Lindeberg (1993) Scale-Space Theory in Computer Vision,
published by Springer.
The transformation from the input image will always be a scale-space transformation,
in the sense that for a 1-D signal the number of local extrema in the smoothed
signal are guaranteed to not exceed the number of local extrema in the input image.
The transformation between adjacent scale levels is, however, not guaranteed to
be a scale-space transformation.
The kernel values of the resulting discrete approximation of the Gaussian kernel
are confined in the interval [0, 1]. The spatial integration of the Gaussian kernel
over the support region of each pixel does, however, add a scale offset of 1/6 in
units of the variance equal to the squared standard deviation of the kernel at
coarser scales. This added variance corresponds to the spatial variance of a
triangular extending to the neigbouring pixels, which is used as spatial window
function when integrating the continuous Gaussian kernel. That triangular filter
does in turn correspond to the convolution of a box filter over a pixel
support region by itself, thus explaining the doubling of the scale offset
in relation to the scale offset for the integrated Gaussian kernel.
For a theoretical explanation of these properties, see Section 3.6.3 in
Lindeberg (1993b) Scale-Space Theory in Computer Vision, Springer.
"""
ndim = inpic.ndim
sep1Dfilter = make1Dlinintgaussfilter(sigma, epsilon, ndim)
if ndim == 1:
outpic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter)
elif ndim == 2:
tmppic = correlate1d(np.array(inpic).astype('float'), sep1Dfilter, 0)
outpic = correlate1d(tmppic, sep1Dfilter, 1)
elif ndim == 3:
# Treat as multilayer image
outpic = np.zeros(inpic.shape)
for layer in range(0, inpic.shape[2]):
outpic[:, :, layer] = linintgaussconv(inpic[:, :, layer], sigma, epsilon)
else:
raise ValueError(f'Cannot handle images of dimensionality {ndim}')
return outpic
def make1Dlinintgaussfilter(
sigma : float,
epsilon : float = 0.00000001,
D : int = 1
) -> np.ndarray :
"""Generates a linearily integrated Gaussian kernel with standard deviation
sigma, given an upper bound on the relative truncation error epsilon over a
D-dimensional domain.
Remark: Adds additional spatial variance 1/6 to the kernel at coarser scales.
"""
vecsize = ceil(1.1*gaussfiltsize(sigma, epsilon, D))
x = np.linspace(-vecsize, vecsize, 1+2*vecsize)
# The following equation is the result of a closed form integration of
# the expression for the filter coefficients in Eq (3.90) on page 97
# in Lindeberg (1993) Scale-Space Theory in Computer Vision, Springer.
return x_scaled_erf(x + 1, sigma) - 2*x_scaled_erf(x, sigma) + \
x_scaled_erf(x - 1, sigma) + \
sigma**2 * (gauss(x + 1, sigma) - 2*gauss(x, sigma) + \
gauss(x - 1, sigma))
def x_scaled_erf(x : np.ndarray, sigma : float = 1.0):
"""Computes the product of the x-coordinate and the scaled error
function (as depending on a scale parameter sigma) given an array of x-coordinates.
"""
return x * scaled_erf(x, sigma)
def gaussfiltsize(sigma : float, epsND : float, D : int) -> float :
"""Estimates the necessary size to truncate a Gaussian kernel with
standard deviation sigma to a relative truncation epsND over a D-dimensional
domain.
"""
s = sigma*sigma
eps1D = truncerrtransf(epsND, D)
N = sqrt(2*s)*erfcinv(eps1D)
return N
def truncerrtransf(epsND : float, D : int) -> float :
"""Converts a relative truncation error epsND over a D-dimensional domain to
a relative truncation error over a 1-D domain when using separable convolution.
"""
eps1D = 1 - (1 - epsND)**(1/D)
return eps1D
def truncfilter(longhalffilter : np.ndarray, epsilon : float) -> np.ndarray :
"""Truncates a filter with overestimated size to a more compact size, to save
computational work in the spatial convolutions that are to follow.
"""
length = longhalffilter.shape[0]
filtersum = longhalffilter[0]
i = 1
while ((filtersum < 1-epsilon) and (i < length)):
filtersum = filtersum + 2*longhalffilter[i]
i += 1
return longhalffilter[0:i]
def mirrorhfilter(halffilter : np.ndarray) -> np.ndarray :
"""Extends a one-sided spatial filter to a symmetric filter by spatial mirroring.
"""
length = halffilter.shape[0]
revfilter = halffilter[::-1]
return np.append(revfilter[0:length-1], halffilter)
def deltafcn(xsize : int, ysize : int) -> np.ndarray :
"""Generates a discrete delta function of size xsize x ysize pixels.
"""
pic = np.zeros([xsize, ysize])
if xsize % 2:
xc = round((xsize - 1)/2)
else:
xc = round(xsize/2)
if ysize % 2:
yc = round((ysize - 1)/2)
else:
yc = round(ysize/2)
pic[xc, yc] = 1.0
return pic
def dxmask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the first-order
derivative in the x-direction.
"""
return np.array([[-1/2, 0, +1/2]])
def dymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the first-order
derivative in the y-direction.
"""
return np.array([[+1/2], \
[ 0], \
[-1/2]])
def dxxmask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the second-order
derivative in the x-direction.
"""
return np.array([[1, -2, 1]])
def dxymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the mixed second-order
derivative in the x- and y-directions.
"""
return np.array([[-1/4, 0, +1/4], \
[ 0, 0, 0], \
[+1/4, 0, -1/4]])
def dyymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the second-order
derivative in the y-direction.
"""
return np.array([[+1], \
[-2], \
[+1]])
def dxxxmask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the third-order
derivative in the x-direction.
"""
return np.array([[-1/2, +1, 0, -1, 1/2]])
def dxxymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the mixed third-order
derivative corresponding to a second-order derivative in the x-direction
and a first-order derivative in the y-direction.
"""
return np.array([[+1/2, -1, +1/2], \
[ 0, 0, 0], \
[-1/2, +1, -1/2]])
def dxyymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the mixed third-order
derivative corresponding to a first-order derivative in the x-direction
and a second-order derivative in the y-direction.
"""
return np.array([[-1/2, 0, +1/2], \
[ +1, 0, -1], \
[-1/2, 0, +1/2]])
def dyyymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the third-order
derivative in the y-direction.
"""
return np.array([[+1/2], \
[ -1], \
[ 0], \
[ +1], \
[-1/2]])
def dxxxxmask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the fourth-order
derivative in the x-direction.
"""
return np.array([[1, -4, 6, -4, 1]])
def dxxxymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the mixed fourth-order
derivative corresponding to a third-order derivative in the x-direction and
a first-order derivative in the y-direction.
"""
return np.array([[-1/4, +1/2, 0, -1/2, +1/4], \
[ 0, 0, 0, 0, 0], \
[+1/4, -1/2, 0, +1/2, -1/4]])
def dxxyymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the mixed fourth-order
derivative corresponding to a second-order derivatives in the x- and y-directions.
"""
return np.array([[+1, -2, +1], \
[-2, +4, -2], \
[+1, -2, +1]])
def dxyyymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the mixed fourth-order
derivative corresponding to a first-order derivative in the x-direction and
a third-order derivative in the y-direction.
"""
return np.array([[-1/4, 0, +1/4], \
[+1/2, 0, -1/2], \
[ 0, 0, 0], \
[-1/2, 0, +1/2], \
[+1/4, 0, -1/4]])
def dyyyymask() -> np.ndarray :
"""Defines a (minimal) mask for discrete approximation of the fourth-order
derivative in the y-direction.
"""
return np.array([[+1], \
[-4], \
[+6], \
[-4], \
[+1]])
def computeNjetfcn(
inpic,
njetfcn : str,
sigma : float,
normdermethod : Union[str, ScSpNormDerMethod] = 'discgauss',
gamma : float = 1.0
) -> np.ndarray :
"""Computes an N-jet function in terms of scale-normalized Gaussian derivatives
of the image inpic at scale level sigma in units of the standard deviation of
the Gaussian kernel, and using the scale normalization method normdermethod.
Implemented N-jet functions:
'L' - smoothed scale-space representation
'Lx' - 1:st-order partial derivative in x-direction
'Ly' - 1:st-order partial derivative in y-direction
'Lxx' - 2:nd-order partial derivative in x-direction
'Lxy' - mixed 2nd-order partial derivative in x- and y-directions
'Lyy' - 2:nd-order partial derivative in y-direction
'Lv' - gradient magnitude
'Lv2' - squared gradient magnitude
'Laplace' - Laplacian operator
'detHessian' - determinant of the Hessian
'sqrtdetHessian' - signed square root of (absolute) determinant of the Hessian
'Kappa' - rescaled level curve curvature
'Lv2Lvv' - 2:nd-order directional derivative in gradient direction * Lv^2
'Lv3Lvvv' - 3:rd-order directional derivative in gradient direction * Lv^3
'Lp' - 1:st-order directional derivative in 1:st principal curvature direction
'Lq' - 1:st-order directional derivative in 2:nd principal curvature direction
'Lpp' - 2:nd-order directional derivative in 1:st principal curvature direction
'Lqq' - 2:nd-order directional derivative in 2:nd principal curvature direction
In addition, 3:rd- and 4:th-order partial derivatives are also implemented.
The differential expressions 'Lv', 'Lv2', 'Lv2Lvv' and 'Lv3Lvvv' are used in
methods for edge detection. The differential expressions 'Laplace', 'detHessian'
and 'sqrtdetHessian' are used in methods for interest point detection,
blob detection and corner detection. The differential expressions 'Lp', 'Lq',
'Lpp' and 'Lqq' are used in methods for ridge detection.
The derivatives in the (u, v)-coordinates are based on Equations (6)-(7) in
Lindeberg (1998) "Edge detection and ridge detection with automatic scale
selection", International Journal of Computer Vision, vol 30(2): 117-154,
whereas the derivatives in the (p, q)-coordinates are based on
Equations (37)-(40) in the same article.
This function is the preferred choice for simplicitly or if you only need a single
N-jetfcn at the given scale. If you instead want to compute multiple N-jetfcns
at the same scale, it is, however, computationally more efficient to perform
the scale-space smoothing yourself using the scspconv() function and then
applying the function applyNjetfcn() multiple times for each N-jetfcn.
"""
if isinstance(normdermethod, str):
normdermethod = defaultscspnormdermethodobject(normdermethod)
smoothpic = scspconv(inpic, sigma, normdermethod.scspmethod)
return applyNjetfcn(smoothpic, njetfcn, sigma, normdermethod, gamma)
def applyNjetfcn(
smoothpic : np.ndarray,
njetfcn : str,
sigma : float = 1.0,
normdermethod : Union[str, ScSpNormDerMethod] = 'discgauss',
gamma : float = 1.0
) -> np.ndarray :
"""Applies an N-jet function in terms of scale-normalized Gaussian derivatives
to an already computed scale-space representation at scale level sigma in units
of the standard deviation of the Gaussian kernel, and using the scale normalization
method normdermethod.
Implemented N-jet functions:
'L' - smoothed scale-space representation
'Lx' - 1:st-order partial derivative in x-direction
'Ly' - 1:st-order partial derivative in y-direction
'Lxx' - 2:nd-order partial derivative in x-direction
'Lxy' - mixed 2nd-order partial derivative in x- and y-directions
'Lyy' - 2:nd-order partial derivative in y-direction
'Lv' - gradient magnitude
'Lv2' - squared gradient magnitude
'Laplace' - Laplacian operator
'detHessian' - determinant of the Hessian
'sqrtdetHessian' - signed square root of (absolute) determinant of the Hessian
'Kappa' - rescaled level curve curvature
'Lv2Lvv' - 2:nd-order directional derivative in gradient direction * Lv^2
'Lv3Lvvv' - 3:rd-order directional derivative in gradient direction * Lv^3
'Lp' - 1:st-order directional derivative in 1:st principal curvature direction
'Lq' - 1:st-order directional derivative in 2:nd principal curvature direction
'Lpp' - 2:nd-order directional derivative in 1:st principal curvature direction
'Lqq' - 2:nd-order directional derivative in 2:nd principal curvature direction
In addition, 3:rd- and 4:th-order partial derivatives are also implemented.
The differential expressions 'Lv', 'Lv2', 'Lv2Lvv' and 'Lv3Lvvv' are used in
methods for edge detection. The differential expressions 'Laplace', 'detHessian'
and 'sqrtdetHessian' are used in methods for interest point detection,
blob detection and corner detection. The differential expressions 'Lp', 'Lq',
'Lpp' and 'Lqq' are used in methods for ridge detection.
The derivatives in the (u, v)-coordinates are based on Equations (6)-(7) in
Lindeberg (1998) "Edge detection and ridge detection with automatic scale
selection", International Journal of Computer Vision, vol 30(2): 117-154,
whereas the derivatives in the (p, q)-coordinates are based on
Equations (37)-(40) in the same article.
"""
if isinstance(normdermethod, str):
normdermethod = defaultscspnormdermethodobject(normdermethod)
if ((smoothpic.ndim == 3) and (smoothpic.shape[2] > 1)):
# Apply same function to all the layers if the input is a multi-layer image
numlayers = smoothpic.shape[2]
outpic = np.zeros(smoothpic.shape)
for layer in range(0, numlayers):
outpic[:, :, layer] = \
applyNjetfcn(smoothpic[:, :, layer], njetfcn, sigma, normdermethod)
else:
if njetfcn == 'L':
outpic = smoothpic
elif njetfcn == 'Lx':
outpic = normderfactor(1, 0, sigma, normdermethod, gamma) * \
correlate(smoothpic, dxmask())
elif njetfcn == 'Ly':
outpic = normderfactor(0, 1, sigma, normdermethod, gamma) * \
correlate(smoothpic, dymask())
elif njetfcn == 'Lxx':
outpic = normderfactor(2, 0, sigma, normdermethod, gamma) * \
correlate(smoothpic, dxxmask())
elif njetfcn == 'Lxy':
outpic = normderfactor(1, 1, sigma, normdermethod, gamma) * \
correlate(smoothpic, dxymask())
elif njetfcn == 'Lyy':
outpic = normderfactor(0, 2, sigma, normdermethod, gamma) * \
correlate(smoothpic, dyymask())
elif njetfcn == 'Lv':
Lx = normderfactor(1, 0, sigma, normdermethod, gamma) * \
correlate(smoothpic, dxmask())
Ly = normderfactor(0, 1, sigma, normdermethod, gamma) * \
correlate(smoothpic, dymask())
outpic = np.sqrt(Lx*Lx + Ly*Ly)
elif njetfcn == 'Lv2':
Lx = normderfactor(1, 0, sigma, normdermethod, gamma) * \
correlate(smoothpic, dxmask())
Ly = normderfactor(0, 1, sigma, normdermethod, gamma) * \
correlate(smoothpic, dymask())
outpic = Lx*Lx + Ly*Ly
elif njetfcn == 'Laplace':
Lxx = normderfactor(2, 0, sigma, normdermethod, gamma) * \
correlate(smoothpic, dxxmask())
Lyy = normderfactor(0, 2, sigma, normdermethod, gamma) * \
correlate(smoothpic, dyymask())
outpic = Lxx + Lyy