/
phasecongruency.jl
executable file
·1906 lines (1609 loc) · 85 KB
/
phasecongruency.jl
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
#=--------------------------------------------------------------------
phasecongruency - Functions related to the phase congruency model of
feature perception and phase based approaches to
image processing.
Copyright (c) 2015-2018 Peter Kovesi
peterkovesi.com
MIT License:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
August 2015 Original conversion from MATLAB to Julia
November 2017 Julia 0.6
October 2018 Julia 0.7/1.0
---------------------------------------------------------------------=#
using FFTW, Statistics
using ImageCore
export phasecongmono, phasesymmono, ppdrc
export highpassmonogenic, bandpassmonogenic
export gaborconvolve, monofilt
export phasecong3, phasesym, ppdenoise
#--------------------------------------------------------------------
# ppdrc
"""
Phase Preserving Dynamic Range Compression
Generates a series of dynamic range compressed images at different scales.
This function is designed to reveal subtle features within high dynamic range
images such as aeromagnetic and other potential field grids. Often this kind
of data is presented using histogram equalisation in conjunction with a
rainbow colourmap. A problem with histogram equalisation is that the contrast
amplification of a feature depends on how commonly its data value occurs,
rather than on the amplitude of the feature itself.
Phase Preserving Dynamic Range Compression allows subtle features to be
revealed without these distortions. Perceptually important phase information
is preserved and the contrast amplification of anomalies in the signal is
purely a function of their amplitude. It operates as follows: first a highpass
filter is applied to the data, this controls the desired scale of analysis.
The 2D analytic signal of the data is then computed to obtain local phase and
amplitude at each point in the image. The amplitude is attenuated by adding 1
and then taking its logarithm, the signal is then reconstructed using the
original phase values.
```
Usage: dimg = ppdrc(img, wavelength; clip, n)
Arguments: img - Image to be processed. A 2D array of Real or Gray elements.
wavelength - Scalar value, or Vector, of wavelengths, in pixels, of
the cut-in frequencies to be used when forming the highpass
versions of the image. Try a range of values starting
with, say, a wavelength corresponding to half the size
of the image and working down to something like 50
grid units.
Keyword arguments:
clip - Percentage of output image histogram to clip. Only a
very small value should be used, say 0.01 or 0.02, but
this can be beneficial. Defaults to 0.01%
n - Order of the Butterworth high pass filter. Defaults
to 2
Returns: dimg - Array of the dynamic range reduced images. If only
one wavelength is specified the image is returned
directly, and not as a one element array of image arrays.
```
Important: Scaling of the image affects the results. If your image has values
of order 1 or less it is useful to scale the image up a few orders of magnitude.
The reason is that when the frequency amplitudes are attenuated we add one
before taking the log to avoid obtaining negative results for values less than
one. Thus if `v` is small `log(1 + v)` will not be a good approximation to `log(v)`.
However, if you scale the image by say, 1000 then `log(1 + 1000*v)` will be a reasonable
approximation to `log(1000*v)`.
When specifying the array `wavelength` it is suggested that you use wavelengths
that increase in a geometric series. You can use the function `geoseries()` to
conveniently do this
Example using `geoseries()` to generate a set of wavelengths that increase
geometrically in 10 steps from 50 to 800.
```
dimg = ppdrc(img, geoseries((50 800), 10))
```
See also: [`highpassmonogenic`](@ref), [`geoseries`](@ref)
"""
function ppdrc(img::AbstractArray{T1,2}, wavelength::Vector{T2}; clip::Real=0.01, n::Integer=2) where {T1 <: Real, T2 <: Real}
#=
Reference:
Peter Kovesi, "Phase Preserving Tone Mapping of Non-Photographic High Dynamic
Range Images". Proceedings: Digital Image Computing: Techniques and
Applications 2012 (DICTA 2012). Available via IEEE Xplore
Preprint: http://www.peterkovesi.com/papers/DICTA2012-tonemapping.pdf
=#
nscale = length(wavelength)
(ph, _, E) = highpassmonogenic(img, wavelength, n)
# Construct each dynamic range reduced image
dimg = Vector{Array{Float64,2}}(undef, nscale)
if nscale == 1 # Single image, highpassmonogenic() will have returned single
# images, hence this separate case
dimg[1] = histtruncate(sin.(ph).*log1p.(E), clip, clip)
else # ph and E will be arrays of 2D arrays
range = zeros(nscale,1)
for k = 1:nscale
dimg[k] = histtruncate(sin.(ph[k]).*log1p.(E[k]), clip, clip)
range[k] = maximum(abs.(dimg[k]))
end
maxrange = maximum(range)
# Set the first two pixels of each image to +range and -range so that
# when the sequence of images are displayed together, say using linimix(),
# there are no unexpected overall brightness changes
for k = 1:nscale
dimg[k][1] = maxrange
dimg[k][2] = -maxrange
end
end
if nscale == 1 # Single image, return output matrix directly
return dimg[1]
else
return dimg
end
end
# Case when wavelength is a single value
function ppdrc(img::AbstractArray{T1,2}, wavelength::Real; clip::Real=0.01, n::Integer=2) where T1 <: Real
return ppdrc(img, [wavelength]; clip=clip, n=n)
end
# Case for an image of Gray values
function ppdrc(img::AbstractArray{T1,2}, wavelength::Real; clip::Real=0.01, n::Integer=2) where T1 <: Gray
fimg = Float64.(img)
return ppdrc(fimg, wavelength; clip=clip, n=n)
end
#--------------------------------------------------------------------
# highpassmonogenic
"""
Compute phase and amplitude in highpass images via monogenic filters.
```
Usage: (phase, orient, E) = highpassmonogenic(img, maxwavelength, n)
Arguments: img - Image to be processed. A 2D array of Real or Gray elements.
maxwavelength - Wavelength(s) in pixels of the cut-in frequency(ies)
of the Butterworth highpass filter.
n - The order of the Butterworth filter. This is an
integer >= 1. The higher the value the sharper
the cutoff.
Returns: phase - The local phase. Values are between -pi/2 and pi/2
orient - The local orientation. Values between -pi and pi.
Note that where the local phase is close to
+-pi/2 the orientation will be poorly defined.
E - Local energy, or amplitude, of the signal.
```
Note that `maxwavelength` can be an array in which case the outputs will
be an array of output images of length `nscales`, where `nscales = length(maxwavelength)`.
See also: [`bandpassmonogenic`](@ref), [`ppdrc`](@ref), [`monofilt`](@ref)
"""
function highpassmonogenic(img::AbstractArray{T1,2}, maxwavelength::Vector{T2}, n::Integer) where {T1 <: Real, T2 <: Real}
if minimum(maxwavelength) < 2
error("Minimum wavelength that can be specified is 2 pixels")
end
nscales = length(maxwavelength)
IMG = fft(img)
# Generate monogenic and filter grids
(H1, H2, freq) = monogenicfilters(size(img))
phase = Vector{Array{Float64,2}}(undef, nscales)
orient = Array{Array{Float64,2}}(undef, nscales)
E = Vector{Array{Float64,2}}(undef, nscales)
f = zeros(size(img))
h1f = zeros(size(img))
h2f = zeros(size(img))
H = zeros(size(img))
for s = 1:nscales
# High pass Butterworth filter
H .= 1.0 .- 1.0 ./ (1.0 .+ (freq .* maxwavelength[s]).^(2*n))
f .= real.(ifft(H.*IMG))
h1f .= real.(ifft(H.*H1.*IMG))
h2f .= real.(ifft(H.*H2.*IMG))
phase[s] = atan.(f./sqrt.(h1f.^2 .+ h2f.^2 .+ eps()))
orient[s] = atan.(h2f, h1f)
E[s] = sqrt.(f.^2 .+ h1f.^2 .+ h2f.^2)
end
# If a single scale specified return output matrices directly
if nscales == 1
return phase[1], orient[1], E[1]
else
return phase, orient, E
end
end
# Version when maxwavelength is a scalar
function highpassmonogenic(img::AbstractArray{T,2}, maxwavelength::Real, n::Integer) where T <: Real
return highpassmonogenic(img, [maxwavelength], n)
end
# Case for an image of Gray values
function highpassmonogenic(img::AbstractArray{T,2}, maxwavelength, n::Integer) where T <: Gray
fimg = Float64.(img)
return highpassmonogenic(fimg, maxwavelength, n)
end
#--------------------------------------------------------------------
# bandpassmonogenic
"""
Compute phase and amplitude in bandpass images via monogenic filters.
```
Usage: (phase, orient, E) = bandpassmonogenic(img, minwavelength, maxwavelength, n)
Arguments: img - Image to be processed. A 2D array of Real or Gray elements.
minwavelength - } Wavelength(s) in pixels of the cut-in and cut-out frequency(ies)
maxwavelength - } of the Butterworth bandpass filter(s).
n - The order of the Butterworth filter. This is an
integer >= 1. The higher the value the sharper
the cutoff.
Returns: phase - The local phase. Values are between -pi/2 and pi/2
orient - The local orientation. Values between -pi and pi.
Note that where the local phase is close to
+-pi/2 the orientation will be poorly defined.
E - Local energy, or amplitude, of the signal.
```
Note that `minwavelength` and `maxwavelength` can be (equal length) arrays in which case the outputs will
be an array of output images of length `nscales`, where `nscales = length(maxwavelength)`.
See also: [`highpassmonogenic`](@ref), [`ppdrc`](@ref), [`monofilt`](@ref)
"""
function bandpassmonogenic(img::AbstractArray{T1,2}, minwavelength::Vector{T2}, maxwavelength::Vector{T3}, n::Integer) where {T1 <: Real, T2 <: Real, T3 <: Real}
if minimum(minwavelength) < 2 || minimum(maxwavelength) < 2
error("Minimum wavelength that can be specified is 2 pixels")
end
if length(minwavelength) != length(maxwavelength)
error("Arrays of min and max wavelengths must be of same length")
end
nscales = length(maxwavelength)
IMG = fft(img)
# Generate monogenic and filter grids
(H1, H2, freq) = monogenicfilters(size(img))
phase = Vector{Array{Float64,2}}(undef, nscales)
orient = Array{Array{Float64,2}}(undef, nscales)
E = Vector{Array{Float64,2}}(undef, nscales)
f = zeros(size(img))
h1f = zeros(size(img))
h2f = zeros(size(img))
H = zeros(size(img))
for s = 1:nscales
# Band pass Butterworth filter
H .= 1.0 ./ (1.0 .+ (freq .* minwavelength[s]).^(2*n)) .-
1.0 ./ (1.0 .+ (freq .* maxwavelength[s]).^(2*n))
f .= real.(ifft(H.*IMG))
h1f .= real.(ifft(H.*H1.*IMG))
h2f .= real.(ifft(H.*H2.*IMG))
phase[s] = atan.(f./sqrt.(h1f.^2 .+ h2f.^2 .+ eps()))
orient[s] = atan.(h2f, h1f)
E[s] = sqrt.(f.^2 .+ h1f.^2 .+ h2f.^2)
end
# If a single scale specified return output matrices directly
if nscales == 1
return phase[1], orient[1], E[1]
else
return phase, orient, E
end
end
# Version when min and maxwavelength is a scalar
function bandpassmonogenic(img::AbstractArray{T,2}, minwavelength::Real, maxwavelength::Real, n::Integer) where T <: Real
return bandpassmonogenic(img, [minwavelength], [maxwavelength], n)
end
# Case for an image of Gray values
function bandpassmonogenic(img::AbstractArray{T,2}, minwavelength, maxwavelength, n::Integer) where T <: Gray
fimg = Float64.(img)
return bandpassmonogenic(fimg, minwavelength, maxwavelength, n)
end
#--------------------------------------------------------------------
# phasecongmono
"""
Phase congruency of an image using monogenic filters.
This code is considerably faster than `phasecong3()` but you may prefer the
output from `phasecong3()`'s oriented filters.
There are potentially many arguments, here is the full usage:
```
(PC, or, ft, T) =
phasecongmono(img; nscale, minwavelength, mult,
sigmaonf, k, cutoff, g, deviationgain, noisemethod)
However, apart from the image, all parameters have defaults and the
usage can be as simple as:
(PC,) = phasecongmono(img) # Use (PC,) so that PC is not a tuple of all
# the returned values
More typically you will pass the image followed by a series of keyword
arguments that you wish to set, leaving the remaining parameters set to
their defaults, for example:
(PC,) = phasecongmono(img, nscale = 5, minwavelength = 3, k = 2.5)
Keyword arguments:
Default values Description
nscale 4 - Number of wavelet scales, try values 3-6
A lower value will reveal more fine scale
features. A larger value will highlight 'major'
features.
minwavelength 3 - Wavelength of smallest scale filter.
mult 2.1 - Scaling factor between successive filters.
sigmaonf 0.55 - Ratio of the standard deviation of the Gaussian
describing the log Gabor filter's transfer function
in the frequency domain to the filter center frequency.
k 3.0 - No of standard deviations of the noise energy beyond
the mean at which we set the noise threshold point.
You may want to vary this up to a value of 10 or
20 for noisy images
cutoff 0.5 - The fractional measure of frequency spread
below which phase congruency values get penalized.
g 10 - Controls the sharpness of the transition in
the sigmoid function used to weight phase
congruency for frequency spread.
deviationgain 1.5 - Amplification to apply to the calculated phase
deviation result. Increasing this sharpens the
edge responses, but can also attenuate their
magnitude if the gain is too large. Sensible
values to use lie in the range 1-2.
noisemethod -1 - Parameter specifies method used to determine
noise statistics.
-1 use median of smallest scale filter responses
-2 use mode of smallest scale filter responses
0+ use noiseMethod value as the fixed noise threshold
A value of 0 will turn off all noise compensation.
Returned values:
PC - Phase congruency indicating edge significance
or - Orientation image in radians -pi/2 to pi/2, +ve anticlockwise.
0 corresponds to a vertical edge, pi/2 is horizontal.
ft - Local weighted mean phase angle at every point in the
image. A value of pi/2 corresponds to a bright line, 0
corresponds to a step and -pi/2 is a dark line.
T - Calculated noise threshold (can be useful for
diagnosing noise characteristics of images). Once you know
this you can then specify fixed thresholds and save some
computation time.
```
The convolutions are done via the FFT. Many of the parameters relate to the
specification of the filters in the frequency plane. The values do not seem
to be very critical and the defaults are usually fine. You may want to
experiment with the values of `nscales` and `k`, the noise compensation
factor.
Typical sequence of operations to obtain an edge image:
```
> (PC, or) = phasecongmono(img)
> nm = nonmaxsup(PC, or, 1.5) # nonmaxima suppression
> bw = hysthresh(nm, 0.1, 0.3) # hysteresis thresholding 0.1 - 0.3
Notes on filter settings to obtain even coverage of the spectrum
sigmaonf .85 mult 1.3
sigmaonf .75 mult 1.6 (filter bandwidth ~1 octave)
sigmaonf .65 mult 2.1
sigmaonf .55 mult 3 (filter bandwidth ~2 octaves)
```
Note that better results are generally achieved using the large
bandwidth filters. I typically use a `sigmaOnf` value of 0.55 or even
smaller.
See also: [`phasecong3`](@ref), [`phasesymmono`](@ref), [`gaborconvolve`](@ref), [`filtergrid`](@ref)
"""
function phasecongmono(img::AbstractArray{T1,2}; nscale::Integer = 4, minwavelength::Real = 3,
mult::Real = 2.1, sigmaonf::Real = 0.55, k::Real = 3.0,
noisemethod::Real = -1, cutoff::Real = 0.5, g::Real = 10.0,
deviationgain::Real = 1.5) where T1 <: Real
#=
References:
Peter Kovesi, "Image Features From Phase Congruency". Videre: A
Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,
Summer 1999 http://www.cs.rochester.edu/u/brown/Videre/001/v13.html
Michael Felsberg and Gerald Sommer, "A New Extension of Linear Signal
Processing for Estimating Local Properties and Detecting Features". DAGM
Symposium 2000, Kiel
Michael Felsberg and Gerald Sommer. "The Monogenic Signal" IEEE
Transactions on Signal Processing, 49(12):3136-3144, December 2001
Peter Kovesi, "Phase Congruency Detects Corners and Edges". Proceedings
DICTA 2003, Sydney Dec 10-12. Available via IEEE Xplore
Preprint: http://www.peterkovesi.com/papers/phasecorners.pdf
=#
epsilon = .0001 # Used to prevent division by zero.
(rows,cols) = size(img)
# (IMG,) = perfft2(img) # Periodic Fourier transform of image
# (Just get the first returned value)
IMG = fft(img) # Use fft rather than perfft2
sumAn = zeros(rows,cols) # Accumulators
sumf = zeros(rows,cols)
sumh1 = zeros(rows,cols)
sumh2 = zeros(rows,cols)
maxAn = zeros(rows,cols) # Need maxAn in main scope of function
IMGF = zeros(ComplexF64, rows, cols) # Buffers
h = zeros(ComplexF64, rows, cols)
f = zeros(rows, cols)
h1 = zeros(rows, cols)
h2 = zeros(rows, cols)
An = zeros(rows, cols)
or = zeros(rows,cols) # Final output arrays
ft = zeros(rows,cols)
energy = zeros(rows,cols)
PC = zeros(rows,cols)
tau = 0.0
T = 0.0
# Generate filter grids in the frequency domain
(H, freq) = packedmonogenicfilters(rows,cols)
# The two monogenic filters H1 and H2 that are packed within H are
# not selective in terms of the magnitudes of the frequencies.
# The code below generates bandpass log-Gabor filters which are
# point-wise multiplied by IMG to produce different bandpass
# versions of the image before being convolved with H1 and H2. We
# also apply a low-pass filter that is as large as possible, yet
# falls away to zero at the boundaries. All filters are
# multiplied by this to ensure no extra frequencies at the
# 'corners' of the FFT are incorporated as this can upset the
# normalisation process when calculating phase symmetry. The
# low-pass filter has a cutoff frequency of 0.45 and a high order of 15.
for s = 1:nscale
wavelength = minwavelength*mult^(s-1)
fo = 1.0/wavelength # Centre frequency of filter.
# For each element in IMG construct and apply the log Gabor filter and low-pass filter
# to produce IMGF, the bandpassed image in the frequency domain.
for n in eachindex(freq)
IMGF[n] = IMG[n]*loggabor(freq[n], fo, sigmaonf)*lowpassfilter(freq[n], 0.45, 15)
end
f .= real.(ifft(IMGF)) # Bandpassed image in spatial domain.
h .= IMGF.*H # Apply monogenic filter.
ifft!(h) # real part of h contains convolution result with h1,
# imaginary part contains convolution result with h2.
# h .= ifft(IMGF.*H) # (not as fast or memory efficient)
@. h1 = real(h)
@. h2 = imag(h)
@. An = sqrt(f^2 + h1^2 + h2^2) # Amplitude of this scale component.
@. sumAn += An # Sum of component amplitudes over scale.
@. sumf += f
@. sumh1 += h1
@. sumh2 += h2
# At the smallest scale estimate noise characteristics from the
# distribution of the filter amplitude responses stored in sumAn.
# tau is the Rayleigh parameter that is used to describe the
# distribution.
if s == 1
if abs(noisemethod + 1) < epsilon # Use median to estimate noise statistics
tau = median(sumAn)/sqrt(log(4))
elseif abs(noisemethod + 2) < epsilon # Use mode to estimate noise statistics
tau = rayleighmode(sumAn)
end
maxAn .= An
else
# Record maximum amplitude of components across scales. This is needed
# to determine the frequency spread weighting.
maxAn .= max.(maxAn, An)
end
end # For each scale
# Form weighting that penalizes frequency distributions that are
# particularly narrow. Calculate fractional 'width' of the frequencies
# present by taking the sum of the filter response amplitudes and dividing
# by the maximum component amplitude at each point on the image. If
# there is only one non-zero component width takes on a value of 0, if
# all components are equal width is 1.
width = (sumAn./(maxAn .+ epsilon) .- 1) ./ (nscale-1)
# Now calculate the sigmoidal weighting function.
weight = 1.0 ./ (1 .+ exp.((cutoff .- width).*g))
# Automatically determine noise threshold
#
# Assuming the noise is Gaussian the response of the filters to noise will
# form Rayleigh distribution. We use the filter responses at the smallest
# scale as a guide to the underlying noise level because the smallest scale
# filters spend most of their time responding to noise, and only
# occasionally responding to features. Either the median, or the mode, of
# the distribution of filter responses can be used as a robust statistic to
# estimate the distribution mean and standard deviation as these are related
# to the median or mode by fixed constants. The response of the larger
# scale filters to noise can then be estimated from the smallest scale
# filter response according to their relative bandwidths.
#
# This code assumes that the expected response to noise on the phase
# congruency calculation is simply the sum of the expected noise responses
# of each of the filters. This is a simplistic overestimate, however these
# two quantities should be related by some constant that will depend on the
# filter bank being used. Appropriate tuning of the parameter 'k' will
# allow you to produce the desired output. (though the value of k seems to
# be not at all critical)
if noisemethod >= 0 # We are using a fixed noise threshold
T = noisemethod # use supplied noiseMethod value as the threshold
else
# Estimate the effect of noise on the sum of the filter responses as
# the sum of estimated individual responses (this is a simplistic
# overestimate). As the estimated noise response at successive scales
# is scaled inversely proportional to bandwidth we have a simple
# geometric sum.
totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult))
# Calculate mean and std dev from tau using fixed relationship
# between these parameters and tau. See
# http://mathworld.wolfram.com/RayleighDistribution.html
EstNoiseEnergyMean = totalTau*sqrt(pi/2) # Expected mean and std
EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2) # values of noise energy
T = EstNoiseEnergyMean + k*EstNoiseEnergySigma # Noise threshold
end
#------ Final computation of key quantities -------
# Orientation - this varies +/- pi/2
@. or = atan(-sumh2/sumh1)
# Feature type - a phase angle -pi/2 to pi/2.
@. ft = atan(sumf, sqrt(sumh1^2 + sumh2^2))
# Overall energy
@. energy = sqrt(sumf^2 + sumh1^2 + sumh2^2)
# Compute phase congruency. The original measure,
# PC = energy/sumAn
# is proportional to the weighted cos(phasedeviation). This is not very
# localised
# A more localised measure to use is
# PC = 1 - phasedeviation.
# The expression below uses the fact that the weighted cosine of
# the phase deviation is given by energy/sumAn. Note, in the
# expression below that the noise threshold is not subtracted from
# energy immediately as this would interfere with the phase
# deviation computation. Instead it is applied as a weighting as
# a fraction by which energy exceeds the noise threshold. This
# weighting is applied in addition to the weighting for frequency
# spread. Note also the phase deviation gain factor which acts to
# sharpen up the edge response. A value of 1.5 seems to work well.
# Sensible values are from 1 to about 2.
@. PC = weight*max(1 - deviationgain*acos(energy/(sumAn + epsilon)),0) *
max(energy-T,0)/(energy+epsilon)
return PC, or, ft, T
end
# Case for an image of Gray values
function phasecongmono(img::AbstractArray{T1,2}; nscale::Integer = 4, minwavelength::Real = 3,
mult::Real = 2.1, sigmaonf::Real = 0.55, k::Real = 3.0,
noisemethod::Real = -1, cutoff::Real = 0.5, g::Real = 10.0,
deviationgain::Real = 1.5) where T1 <: Gray
fimg = Float64.(img)
return phasecongmono(fimg, nscale=nscale, minwavelength=minwavelength, mult=mult, sigmaonf=sigmaonf,
k=k, noisemethod=noisemethod, cutoff=cutoff, g=g, deviationgain=deviationgain)
end
#-------------------------------------------------------------------------
"""
rayleighmode
Computes mode of a vector/matrix of data that is assumed to come from a
Rayleigh distribution.
```
Usage: rmode = rayleighmode(data, nbins)
Arguments: data - data assumed to come from a Rayleigh distribution
nbins - Optional number of bins to use when forming histogram
of the data to determine the mode.
```
Mode is computed by forming a histogram of the data over 50 bins and then
finding the maximum value in the histogram. Mean and standard deviation
can then be calculated from the mode as they are related by fixed
constants.
```
mean = mode * sqrt(pi/2)
std dev = mode * sqrt((4-pi)/2)
See
http://mathworld.wolfram.com/RayleighDistribution.html
http://en.wikipedia.org/wiki/Rayleigh_distribution
```
"""
function rayleighmode(X, nbins::Integer= 50)
edges, counts = build_histogram(X, nbins=nbins)
ind = argmax(counts)
return (edges[ind]+edges[ind+1])/2
end
#-------------------------------------------------------------------------
# phasesymmono
"""
Phase symmetry of an image using monogenic filters.
This function calculates the phase symmetry of points in an image.
This is a contrast invariant measure of symmetry. This function can be
used as a line and blob detector. The greyscale polarity of the lines
that you want to find can be specified.
This code is considerably faster than `phasesym()` but you may prefer the
output from `phasesym()`'s oriented filters.
There are potentially many arguments, here is the full usage:
```
(phSym, symmetryEnergy, T) =
phasesymmono(img; nscale, minwaveLength, mult,
sigmaonf, k, polarity, noisemethod)
```
However, apart from the image, all parameters have defaults and the
usage can be as simple as:
```
(phSym,) = phasesymmono(img)
Keyword arguments:
Default values Description
nscale 5 - Number of wavelet scales, try values 3-6
minwaveLength 3 - Wavelength of smallest scale filter.
mult 2.1 - Scaling factor between successive filters.
sigmaonf 0.55 - Ratio of the standard deviation of the Gaussian
describing the log Gabor filter's transfer function
in the frequency domain to the filter center frequency.
k 2.0 - No of standard deviations of the noise energy beyond
the mean at which we set the noise threshold point.
You may want to vary this up to a value of 10 or
20 for noisy images
polarity 0 - Controls 'polarity' of symmetry features to find.
1 - just return 'bright' points
-1 - just return 'dark' points
0 - return bright and dark points.
noisemethod -1 - Parameter specifies method used to determine
noise statistics.
-1 use median of smallest scale filter responses
-2 use mode of smallest scale filter responses
0+ use noiseMethod value as the fixed noise threshold
A value of 0 will turn off all noise compensation.
Return values:
phSym - Phase symmetry image (values between 0 and 1).
symmetryEnergy - Un-normalised raw symmetry energy which may be
more to your liking.
T - Calculated noise threshold (can be useful for
diagnosing noise characteristics of images)
```
The convolutions are done via the FFT. Many of the parameters relate to the
specification of the filters in the frequency plane. The values do not seem
to be very critical and the defaults are usually fine. You may want to
experiment with the values of `nscales` and `k`, the noise compensation factor.
Notes on filter settings to obtain even coverage of the spectrum
```
sigmaonf .85 mult 1.3
sigmaonf .75 mult 1.6 (filter bandwidth ~1 octave)
sigmaonf .65 mult 2.1
sigmaonf .55 mult 3 (filter bandwidth ~2 octaves)
```
See Also: [`phasesym`](@ref), [`phasecongmono`](@ref)
"""
function phasesymmono(img::AbstractArray{T1,2}; nscale::Integer = 5, minwavelength::Real = 3,
mult::Real = 2.1, sigmaonf::Real = 0.55, k::Real = 2.0,
polarity::Integer = 0, noisemethod::Real = -1) where T1 <: Real
#=
References:
Peter Kovesi, "Symmetry and Asymmetry From Local Phase" AI'97, Tenth
Australian Joint Conference on Artificial Intelligence. 2 - 4 December
1997. http://www.peterkovesi.com/papers/ai97.pdf
Peter Kovesi, "Image Features From Phase Congruency". Videre: A
Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,
Summer 1999 http://www.cs.rochester.edu/u/brown/Videre/001/v13.html
Michael Felsberg and Gerald Sommer, "A New Extension of Linear Signal
Processing for Estimating Local Properties and Detecting Features". DAGM
Symposium 2000, Kiel
Michael Felsberg and Gerald Sommer. "The Monogenic Signal" IEEE
Transactions on Signal Processing, 49(12):3136-3144, December 2001
=#
epsilon = .0001 # Used to prevent division by zero.
(rows,cols) = size(img)
IMG = fft(img) # Fourier transform of image
tau = 0.0
symmetryEnergy = zeros(rows,cols) # Matrix for accumulating weighted phase
# symmetry values (energy).
sumAn = zeros(rows,cols) # Matrix for accumulating filter response
# amplitude values.
IMGF = zeros(ComplexF64, rows, cols)
h = zeros(ComplexF64, rows, cols)
f = zeros(rows, cols)
# Generate filter grids in the frequency domain
(H, freq) = packedmonogenicfilters(rows,cols)
# The two monogenic filters H1 and H2 that are packed within H are
# not selective in terms of the magnitudes of the frequencies.
# The code below generates bandpass log-Gabor filters which are
# point-wise multiplied by IMG to produce different bandpass
# versions of the image before being convolved with H1 and H2. We
# also apply a low-pass filter that is as large as possible, yet
# falls away to zero at the boundaries. All filters are
# multiplied by this to ensure no extra frequencies at the
# 'corners' of the FFT are incorporated as this can upset the
# normalisation process when calculating phase symmetry
for s = 1:nscale
wavelength = minwavelength*mult^(s-1)
fo = 1.0/wavelength # Centre frequency of filter.
# For each element in IMG construct and apply the log Gabor filter and low-pass filter
# to produce IMGF, the bandpassed image in the frequency domain
for n in eachindex(freq)
IMGF[n] = IMG[n]*loggabor(freq[n], fo, sigmaonf)*lowpassfilter(freq[n], 0.4, 10)
end
f .= real.(ifft(IMGF)) # Bandpassed image in spatial domain.
h .= IMGF.*H # Apply monogenic filter.
ifft!(h) # real part of h contains convolution result with h1,
# imaginary part contains convolution result with h2.
# h .= ifft(IMGF.*H) # (not as fast or memory efficient)
# Now calculate the phase symmetry measure.
for n in eachindex(h)
hAmp2 = real(h[n])^2 + imag(h[n])^2 # Squared amplitude of h1 h2 filter results
sumAn[n] += sqrt(f[n]^2 + hAmp2) # Magnitude of Energy.
if polarity == 0 # look for 'white' and 'black' spots
symmetryEnergy[n] += abs(f[n]) - sqrt(hAmp2)
elseif polarity == 1 # Just look for 'white' spots
symmetryEnergy[n] += f[n] - sqrt(hAmp2)
elseif polarity == -1 # Just look for 'black' spots
symmetryEnergy[n] += (-f[n] - sqrt(hAmp2))
end
end
# At the smallest scale estimate noise characteristics from the
# distribution of the filter amplitude responses stored in sumAn.
# tau is the Rayleigh parameter that is used to specify the
# distribution.
if s == 1
if abs(noisemethod + 1) < epsilon # Use median to estimate noise statistics
tau = median(sumAn)/sqrt(log(4))
elseif abs(noisemethod + 2) < epsilon # Use mode to estimate noise statistics
tau = rayleighmode(sumAn)
end
end
end # For each scale
# Compensate for noise
#
# Assuming the noise is Gaussian the response of the filters to noise will
# form Rayleigh distribution. We use the filter responses at the smallest
# scale as a guide to the underlying noise level because the smallest scale
# filters spend most of their time responding to noise, and only
# occasionally responding to features. Either the median, or the mode, of
# the distribution of filter responses can be used as a robust statistic to
# estimate the distribution mean and standard deviation as these are related
# to the median or mode by fixed constants. The response of the larger
# scale filters to noise can then be estimated from the smallest scale
# filter response according to their relative bandwidths.
#
# This code assumes that the expected response to noise on the phase symmetry
# calculation is simply the sum of the expected noise responses of each of
# the filters. This is a simplistic overestimate, however these two
# quantities should be related by some constant that will depend on the
# filter bank being used. Appropriate tuning of the parameter 'k' will
# allow you to produce the desired output. (though the value of k seems to
# be not at all critical)
if noisemethod >= 0 # We are using a fixed noise threshold
T = noisemethod # use supplied noiseMethod value as the threshold
else
# Estimate the effect of noise on the sum of the filter responses as
# the sum of estimated individual responses (this is a simplistic
# overestimate). As the estimated noise response at successive scales
# is scaled inversely proportional to bandwidth we have a simple
# geometric sum.
totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult))
# Calculate mean and std dev from tau using fixed relationship
# between these parameters and tau. See
# http://mathworld.wolfram.com/RayleighDistribution.html
EstNoiseEnergyMean = totalTau*sqrt(pi/2) # Expected mean and std
EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2) # values of noise energy
# Noise threshold, make sure it is not less than epsilon
T = max(EstNoiseEnergyMean + k*EstNoiseEnergySigma, epsilon)
end
# Apply noise threshold - effectively wavelet denoising soft thresholding
# and normalize symmetryEnergy by the sumAn to obtain phase symmetry.
# Note the max operation is not necessary if you are after speed, it is
# just 'tidy' not having -ve symmetry values
phSym = max.(symmetryEnergy .- T, 0) ./ (sumAn .+ epsilon)
return phSym, symmetryEnergy, T
end
# Version for an array of Gray elements
function phasesymmono(img::AbstractArray{T1,2}; nscale::Integer = 5, minwavelength::Real = 3,
mult::Real = 2.1, sigmaonf::Real = 0.55, k::Real = 2.0,
polarity::Integer = 0, noisemethod::Real = -1) where T1 <: Gray
fimg = Float64.(img)
return phasesymmono(fimg; nscale=nscale, minwavelength= minwavelength,
mult=mult, sigmaonf=sigmaonf, k=k,
polarity=polarity, noisemethod=noisemethod)
end
#------------------------------------------------------------------
# monofilt
"""
Apply monogenic filters to an image to obtain 2D analytic signal.
This is an implementation of Felsberg's monogenic filters
```
Usage: (f, h1f, h2f, A, theta, psi) =
monofilt(img, nscale, minWaveLength, mult, sigmaOnf, orientWrap)
3 4 2 0.65 true/false
Arguments:
The convolutions are done via the FFT. Many of the parameters relate
to the specification of the filters in the frequency plane.
Variable Suggested Description
name value
----------------------------------------------------------
img Image to be convolved. An Array of Real or Gray.
nscale = 3 Number of filter scales.
minWaveLength = 4 Wavelength of smallest scale filter.
mult = 2 Scaling factor between successive filters.
sigmaonf = 0.65 Ratio of the standard deviation of the
Gaussian describing the log Gabor filter's
transfer function in the frequency domain
to the filter center frequency.
orientWrap false Optional Boolean flag to turn on/off
'wrapping' of orientation data from a
range of -pi .. pi to the range 0 .. pi.
This affects the interpretation of the
phase angle - see note below. Defaults to false.
Returns:
f - vector of bandpass filter responses with respect to scale.
h1f - vector of bandpass h1 filter responses wrt scale.
h2f - vector of bandpass h2 filter responses.
A - vector of monogenic energy responses.
theta - vector of phase orientation responses.
psi - vector of phase angle responses.
```
If `orientWrap` is true `theta` will be returned in the range `0 .. pi`
Experimentation with `sigmaonf` can be useful depending on your application.
I have found values as low as 0.2 (a filter with a *very* large bandwidth)
to be useful on some occasions.
See also: [`gaborconvolve`](@ref)
"""
function monofilt(img::AbstractArray{T1,2}, nscale::Integer, minWaveLength::Real, mult::Real,
sigmaOnf::Real, orientWrap::Bool = false) where T1 <: Real
#=
References:
Michael Felsberg and Gerald Sommer. "A New Extension of Linear Signal
Processing for Estimating Local Properties and Detecting Features"
DAGM Symposium 2000, Kiel
Michael Felsberg and Gerald Sommer. "The Monogenic Signal" IEEE
Transactions on Signal Processing, 49(12):3136-3144, December 2001
=#
(rows,cols) = size(img)
IMG = fft(img)
# Generate filters
(H1, H2, freq) = monogenicfilters(rows,cols)
# The two monogenic filters H1 and H2 are oriented in frequency space
# but are not selective in terms of the magnitudes of the
# frequencies. The code below generates bandpass log-Gabor filters
# which are point-wise multiplied by H1 and H2 to produce different
# bandpass versions of H1 and H2
psi = Array{Array{Float64,2}}(undef, nscale)
theta = Array{Array{Float64,2}}(undef, nscale)
A = Array{Array{Float64,2}}(undef, nscale)
f = Array{Array{Float64,2}}(undef, nscale)
h1f = Array{Array{Float64,2}}(undef, nscale)
h2f = Array{Array{Float64,2}}(undef, nscale)
H1s = zeros(ComplexF64, rows, cols)
H2s = zeros(ComplexF64, rows, cols)
logGabor = zeros(rows, cols)
for s = 1:nscale
wavelength = minWaveLength*mult^(s-1)
fo = 1.0/wavelength # Centre frequency of filter.
@. logGabor = loggabor(freq, fo, sigmaOnf)
# Generate bandpass versions of H1 and H2 at this scale
H1s .= H1.*logGabor
H2s .= H2.*logGabor
# Apply filters to image in the frequency domain and get spatial
# results
f[s] = real.(ifft(IMG.*logGabor))
h1f[s] = real.(ifft(IMG.*H1s))
h2f[s] = real.(ifft(IMG.*H2s))
A[s] = sqrt.(f[s].^2 .+ h1f[s].^2 .+ h2f[s].^2) # Magnitude of Energy.
theta[s] = atan.(h2f[s], h1f[s]) # Orientation.
# Here phase is measured relative to the h1f-h2f plane as an
# 'elevation' angle that ranges over +- pi/2
psi[s] = atan.(f[s], sqrt.(h1f[s].^2 .+ h2f[s].^2))
if orientWrap # Wrap orientation values back into the range 0-pi
theta[s][theta[s] .< 0] += pi
end
end
return f, h1f, h2f, A, theta, psi
end
# Version for an array of Gray elements
function monofilt(img::AbstractArray{T1,2}, nscale::Integer, minWaveLength::Real, mult::Real,
sigmaOnf::Real, orientWrap::Bool = false) where T1 <: Gray
fimg = Float64.(img)
return monofilt(fimg, nscale, minWaveLength, mult, sigmaOnf, orientWrap)
end
#------------------------------------------------------------------