/
algorithms.jl
1855 lines (1633 loc) · 68 KB
/
algorithms.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
#### Math with images ####
(+)(img::AbstractImageDirect{Bool}, n::Bool) = img .+ n
(+)(n::Bool, img::AbstractImageDirect{Bool}) = n .+ img
(+)(img::AbstractImageDirect, n::Number) = img .+ n
(+)(img::AbstractImageDirect, n::AbstractRGB) = img .+ n
(+)(n::Number, img::AbstractImageDirect) = n .+ img
(+)(n::AbstractRGB, img::AbstractImageDirect) = n .+ img
(.+)(img::AbstractImageDirect, n::Number) = shareproperties(img, data(img).+n)
(.+)(n::Number, img::AbstractImageDirect) = shareproperties(img, data(img).+n)
if isdefined(:UniformScaling)
(+){Timg,TA<:Number}(img::AbstractImageDirect{Timg,2}, A::UniformScaling{TA}) = shareproperties(img, data(img)+A)
(-){Timg,TA<:Number}(img::AbstractImageDirect{Timg,2}, A::UniformScaling{TA}) = shareproperties(img, data(img)-A)
end
(+)(img::AbstractImageDirect, A::BitArray) = shareproperties(img, data(img)+A)
(+)(img::AbstractImageDirect, A::AbstractImageDirect) = shareproperties(img, data(img)+data(A))
(+)(img::AbstractImageDirect, A::AbstractArray) = shareproperties(img, data(img)+data(A))
(+){S,T}(A::Range{S}, img::AbstractImageDirect{T}) = shareproperties(img, data(A)+data(img))
(+)(A::AbstractArray, img::AbstractImageDirect) = shareproperties(img, data(A)+data(img))
(.+)(img::AbstractImageDirect, A::BitArray) = shareproperties(img, data(img).+A)
(.+)(img::AbstractImageDirect, A::AbstractArray) = shareproperties(img, data(img).+data(A))
(-)(img::AbstractImageDirect{Bool}, n::Bool) = img .- n
(-)(img::AbstractImageDirect, n::Number) = img .- n
(-)(img::AbstractImageDirect, n::AbstractRGB) = img .- n
(.-)(img::AbstractImageDirect, n::Number) = shareproperties(img, data(img).-n)
(-)(n::Bool, img::AbstractImageDirect{Bool}) = n .- img
(-)(n::Number, img::AbstractImageDirect) = n .- img
(-)(n::AbstractRGB, img::AbstractImageDirect) = n .- img
(.-)(n::Number, img::AbstractImageDirect) = shareproperties(img, n.-data(img))
(-)(img::AbstractImageDirect, A::BitArray) = shareproperties(img, data(img)-A)
(-){T}(img::AbstractImageDirect{T,2}, A::Diagonal) = shareproperties(img, data(img)-A) # fixes an ambiguity warning
(-)(img::AbstractImageDirect, A::Range) = shareproperties(img, data(img)-A)
(-)(img::AbstractImageDirect, A::AbstractImageDirect) = shareproperties(img, data(img)-data(A))
(-)(img::AbstractImageDirect, A::AbstractArray) = shareproperties(img, data(img)-data(A))
(-){S,T}(A::Range{S}, img::AbstractImageDirect{T}) = shareproperties(img, data(A)-data(img))
(-)(A::AbstractArray, img::AbstractImageDirect) = shareproperties(img, data(A)-data(img))
(-)(img::AbstractImageDirect) = shareproperties(img, -data(img))
(.-)(img::AbstractImageDirect, A::BitArray) = shareproperties(img, data(img).-A)
(.-)(img::AbstractImageDirect, A::AbstractArray) = shareproperties(img, data(img).-data(A))
(*)(img::AbstractImageDirect, n::Number) = (.*)(img, n)
(*)(n::Number, img::AbstractImageDirect) = (.*)(n, img)
(.*)(img::AbstractImageDirect, n::Number) = shareproperties(img, data(img).*n)
(.*)(n::Number, img::AbstractImageDirect) = shareproperties(img, data(img).*n)
(/)(img::AbstractImageDirect, n::Number) = shareproperties(img, data(img)/n)
(.*)(img1::AbstractImageDirect, img2::AbstractImageDirect) = shareproperties(img1, data(img1).*data(img2))
(.*)(img::AbstractImageDirect, A::BitArray) = shareproperties(img, data(img).*A)
(.*)(A::BitArray, img::AbstractImageDirect) = shareproperties(img, data(img).*A)
(.*)(img::AbstractImageDirect{Bool}, A::BitArray) = shareproperties(img, data(img).*A)
(.*)(A::BitArray, img::AbstractImageDirect{Bool}) = shareproperties(img, data(img).*A)
(.*)(img::AbstractImageDirect, A::AbstractArray) = shareproperties(img, data(img).*A)
(.*)(A::AbstractArray, img::AbstractImageDirect) = shareproperties(img, data(img).*A)
(./)(img::AbstractImageDirect, A::BitArray) = shareproperties(img, data(img)./A) # needed to avoid ambiguity warning
(./)(img1::AbstractImageDirect, img2::AbstractImageDirect) = shareproperties(img1, data(img1)./data(img2))
(./)(img::AbstractImageDirect, A::AbstractArray) = shareproperties(img, data(img)./A)
(.^)(img::AbstractImageDirect, p::Number) = shareproperties(img, data(img).^p)
sqrt(img::AbstractImageDirect) = shareproperties(img, sqrt(data(img)))
atan2(img1::AbstractImageDirect, img2::AbstractImageDirect) = shareproperties(img1, atan2(data(img1),data(img2)))
hypot(img1::AbstractImageDirect, img2::AbstractImageDirect) = shareproperties(img1, hypot(data(img1),data(img2)))
@vectorize_2arg Gray atan2
@vectorize_2arg Gray hypot
function sum(img::AbstractImageDirect, region::Union{AbstractVector,Tuple,Integer})
f = prod(size(img)[[region...]])
out = copyproperties(img, sum(data(img), region))
if in(colordim(img), region)
out["colorspace"] = "Unknown"
end
out
end
"""
`M = meanfinite(img, region)` calculates the mean value along the dimensions listed in `region`, ignoring any non-finite values.
"""
meanfinite{T<:Real}(A::AbstractArray{T}, region) = _meanfinite(A, T, region)
meanfinite{CT<:Colorant}(A::AbstractArray{CT}, region) = _meanfinite(A, eltype(CT), region)
function _meanfinite{T<:AbstractFloat}(A::AbstractArray, ::Type{T}, region)
sz = Base.reduced_dims(A, region)
K = zeros(Int, sz)
S = zeros(eltype(A), sz)
sumfinite!(S, K, A)
S./K
end
_meanfinite(A::AbstractArray, ::Type, region) = mean(A, region) # non floating-point
function meanfinite{T<:AbstractFloat}(img::AbstractImageDirect{T}, region)
r = meanfinite(data(img), region)
out = copyproperties(img, r)
if in(colordim(img), region)
out["colorspace"] = "Unknown"
end
out
end
meanfinite(img::AbstractImageIndexed, region) = meanfinite(convert(Image, img), region)
# Note that you have to zero S and K upon entry
@generated function sumfinite!{T,N}(S, K, A::AbstractArray{T,N})
quote
isempty(A) && return S, K
@nexprs $N d->(sizeS_d = size(S,d))
sizeA1 = size(A, 1)
if size(S, 1) == 1 && sizeA1 > 1
# When we are reducing along dim == 1, we can accumulate to a temporary
@inbounds @nloops $N i d->(d>1? (1:size(A,d)) : (1:1)) d->(j_d = sizeS_d==1 ? 1 : i_d) begin
s = @nref($N, S, j)
k = @nref($N, K, j)
for i_1 = 1:sizeA1
tmp = @nref($N, A, i)
if isfinite(tmp)
s += tmp
k += 1
end
end
@nref($N, S, j) = s
@nref($N, K, j) = k
end
else
# Accumulate to array storage
@inbounds @nloops $N i A d->(j_d = sizeS_d==1 ? 1 : i_d) begin
tmp = @nref($N, A, i)
if isfinite(tmp)
@nref($N, S, j) += tmp
@nref($N, K, j) += 1
end
end
end
S, K
end
end
# Entropy for grayscale (intensity) images
function _log(kind::Symbol)
if kind == :shannon
x -> log2(x)
elseif kind == :nat
x -> log(x)
elseif kind == :hartley
x -> log10(x)
else
throw(ArgumentError("Invalid entropy unit. (:shannon, :nat or :hartley)"))
end
end
"""
`entropy(img, kind)` is the entropy of a grayscale image defined as -sum(p.*logb(p)).
The base b of the logarithm (a.k.a. entropy unit) is one of the following:
`:shannon ` (log base 2, default)
`:nat` (log base e)
`:hartley` (log base 10)
"""
function entropy(img::AbstractArray; kind=:shannon)
logᵦ = _log(kind)
_, counts = hist(img[:], 256)
p = counts / length(img)
logp = logᵦ(p)
# take care of empty bins
logp[isinf(logp)] = 0
-sum(p.*logp)
end
function entropy(img::AbstractArray{Bool}; kind=:shannon)
logᵦ = _log(kind)
p = sum(img) / length(img)
(0 < p < 1) ? - p*logᵦ(p) - (1-p)*logᵦ(1-p) : zero(p)
end
entropy{C<:AbstractGray}(img::AbstractArray{C}; kind=:shannon) = entropy(raw(img), kind=kind)
# Logical operations
(.<)(img::AbstractImageDirect, n::Number) = data(img) .< n
(.>)(img::AbstractImageDirect, n::Number) = data(img) .> n
(.<)(img::AbstractImageDirect{Bool}, A::AbstractArray{Bool}) = data(img) .< A
(.<)(img::AbstractImageDirect, A::AbstractArray) = data(img) .< A
(.>)(img::AbstractImageDirect, A::AbstractArray) = data(img) .> A
(.==)(img::AbstractImageDirect, n::Number) = data(img) .== n
(.==)(img::AbstractImageDirect{Bool}, A::AbstractArray{Bool}) = data(img) .== A
(.==)(img::AbstractImageDirect, A::AbstractArray) = data(img) .== A
"""
`imadjustintensity(img [, (minval,maxval)]) -> Image`
Map intensities over the interval `(minval,maxval)` to the interval
`[0,1]`. This is equivalent to `map(ScaleMinMax(eltype(img), minval,
maxval), img)`. (minval,maxval) defaults to `extrema(img)`.
"""
imadjustintensity{T}(img::AbstractArray{T}, range) = map(ScaleMinMax(T, range...), img)
imadjustintensity{T}(img::AbstractArray{T}) = map(ScaleAutoMinMax(T), img)
# functions red, green, and blue
for (funcname, fieldname) in ((:red, :r), (:green, :g), (:blue, :b))
fieldchar = string(fieldname)[1]
@eval begin
function $funcname{CV<:Color}(img::AbstractArray{CV})
T = eltype(CV)
out = Array(T, size(img))
for i = 1:length(img)
out[i] = convert(RGB{T}, img[i]).$fieldname
end
out
end
function $funcname(img::AbstractArray)
pos = search(lowercase(colorspace(img)), $fieldchar)
pos == 0 && error("channel $fieldchar not found in colorspace $(colorspace(img))")
sliceim(img, "color", pos)
end
end
end
"`r = red(img)` extracts the red channel from an RGB image `img`" red
"`g = green(img)` extracts the green channel from an RGB image `img`" green
"`b = blue(img)` extracts the blue channel from an RGB image `img`" blue
"""
`m = minfinite(A)` calculates the minimum value in `A`, ignoring any values that are not finite (Inf or NaN).
"""
function minfinite{T}(A::AbstractArray{T})
ret = sentinel_min(T)
for a in A
ret = minfinite_scalar(a, ret)
end
ret
end
"""
`m = maxfinite(A)` calculates the maximum value in `A`, ignoring any values that are not finite (Inf or NaN).
"""
function maxfinite{T}(A::AbstractArray{T})
ret = sentinel_max(T)
for a in A
ret = maxfinite_scalar(a, ret)
end
ret
end
"""
`m = maxabsfinite(A)` calculates the maximum absolute value in `A`, ignoring any values that are not finite (Inf or NaN).
"""
function maxabsfinite{T}(A::AbstractArray{T})
ret = sentinel_min(typeof(abs(A[1])))
for a in A
ret = maxfinite_scalar(abs(a), ret)
end
ret
end
# Issue #232. FIXME: really should return a Gray here?
for f in (:minfinite, :maxfinite, :maxabsfinite)
@eval $f{T}(A::AbstractArray{Gray{T}}) = $f(reinterpret(T, data(A)))
end
minfinite_scalar{T}(a::T, b::T) = isfinite(a) ? (b < a ? b : a) : b
maxfinite_scalar{T}(a::T, b::T) = isfinite(a) ? (b > a ? b : a) : b
minfinite_scalar{T<:Union{Integer,FixedPoint}}(a::T, b::T) = b < a ? b : a
maxfinite_scalar{T<:Union{Integer,FixedPoint}}(a::T, b::T) = b > a ? b : a
minfinite_scalar(a, b) = minfinite_scalar(promote(a, b)...)
maxfinite_scalar(a, b) = maxfinite_scalar(promote(a, b)...)
function minfinite_scalar{C<:AbstractRGB}(c1::C, c2::C)
C(minfinite_scalar(c1.r, c2.r),
minfinite_scalar(c1.g, c2.g),
minfinite_scalar(c1.b, c2.b))
end
function maxfinite_scalar{C<:AbstractRGB}(c1::C, c2::C)
C(maxfinite_scalar(c1.r, c2.r),
maxfinite_scalar(c1.g, c2.g),
maxfinite_scalar(c1.b, c2.b))
end
sentinel_min{T<:Union{Integer,FixedPoint}}(::Type{T}) = typemax(T)
sentinel_max{T<:Union{Integer,FixedPoint}}(::Type{T}) = typemin(T)
sentinel_min{T<:AbstractFloat}(::Type{T}) = convert(T, NaN)
sentinel_max{T<:AbstractFloat}(::Type{T}) = convert(T, NaN)
sentinel_min{C<:AbstractRGB}(::Type{C}) = _sentinel_min(C, eltype(C))
_sentinel_min{C<:AbstractRGB,T}(::Type{C},::Type{T}) = (s = sentinel_min(T); C(s,s,s))
sentinel_max{C<:AbstractRGB}(::Type{C}) = _sentinel_max(C, eltype(C))
_sentinel_max{C<:AbstractRGB,T}(::Type{C},::Type{T}) = (s = sentinel_max(T); C(s,s,s))
sentinel_min{C<:AbstractGray}(::Type{C}) = _sentinel_min(C, eltype(C))
_sentinel_min{C<:AbstractGray,T}(::Type{C},::Type{T}) = C(sentinel_min(T))
sentinel_max{C<:AbstractGray}(::Type{C}) = _sentinel_max(C, eltype(C))
_sentinel_max{C<:AbstractGray,T}(::Type{C},::Type{T}) = C(sentinel_max(T))
# fft & ifft
fft(img::AbstractImageDirect) = shareproperties(img, fft(data(img)))
function fft(img::AbstractImageDirect, region, args...)
F = fft(data(img), region, args...)
props = copy(properties(img))
props["region"] = region
Image(F, props)
end
fft{CV<:Colorant}(img::AbstractImageDirect{CV}) = fft(img, 1:ndims(img))
function fft{CV<:Colorant}(img::AbstractImageDirect{CV}, region, args...)
imgr = reinterpret(eltype(CV), img)
if ndims(imgr) > ndims(img)
newregion = ntuple(i->region[i]+1, length(region))
else
newregion = ntuple(i->region[i], length(region))
end
F = fft(data(imgr), newregion, args...)
props = copy(properties(imgr))
props["region"] = newregion
Image(F, props)
end
function ifft(img::AbstractImageDirect)
region = get(img, "region", 1:ndims(img))
A = ifft(data(img), region)
props = copy(properties(img))
haskey(props, "region") && delete!(props, "region")
Image(A, props)
end
ifft(img::AbstractImageDirect, region, args...) = ifft(data(img), region, args...)
# average filter
"""
`kern = imaverage(filtersize)` constructs a boxcar-filter of the specified size.
"""
function imaverage(filter_size=[3,3])
if length(filter_size) != 2
error("wrong filter size")
end
m, n = filter_size
if mod(m, 2) != 1 || mod(n, 2) != 1
error("filter dimensions must be odd")
end
f = ones(Float64, m, n)/(m*n)
end
# laplacian filter kernel
"""
`kern = imlaplacian(filtersize)` returns a kernel for laplacian filtering.
"""
function imlaplacian(diagonals::AbstractString="nodiagonals")
if diagonals == "diagonals"
return [1.0 1.0 1.0; 1.0 -8.0 1.0; 1.0 1.0 1.0]
elseif diagonals == "nodiagonals"
return [0.0 1.0 0.0; 1.0 -4.0 1.0; 0.0 1.0 0.0]
else
error("Expected \"diagnoals\" or \"nodiagonals\" or Number, got: \"$diagonals\"")
end
end
# more general version
function imlaplacian(alpha::Number)
lc = alpha/(1 + alpha)
lb = (1 - alpha)/(1 + alpha)
lm = -4/(1 + alpha)
return [lc lb lc; lb lm lb; lc lb lc]
end
# 2D gaussian filter kernel
"""
`kern = gaussian2d(sigma, filtersize)` returns a kernel for FIR-based Gaussian filtering.
See also: `imfilter_gaussian`.
"""
function gaussian2d(sigma::Number=0.5, filter_size=[])
if length(filter_size) == 0
# choose 'good' size
m = 4*ceil(Int, sigma)+1
n = m
elseif length(filter_size) != 2
error("wrong filter size")
else
m, n = filter_size[1], filter_size[2]
end
if mod(m, 2) != 1 || mod(n, 2) != 1
error("filter dimensions must be odd")
end
g = Float64[exp(-(X.^2+Y.^2)/(2*sigma.^2)) for X=-floor(Int,m/2):floor(Int,m/2), Y=-floor(Int,n/2):floor(Int,n/2)]
return g/sum(g)
end
# difference of gaussian
"""
`kern = imdog(sigma)` creates a difference-of-gaussians kernel (`sigma`s differing by a factor of
`sqrt(2)`).
"""
function imdog(sigma::Number=0.5)
m = 4*ceil(sqrt(2)*sigma)+1
return gaussian2d(sqrt(2)*sigma, [m m]) - gaussian2d(sigma, [m m])
end
# laplacian of gaussian
"""
`kern = imlog(sigma)` returns a laplacian-of-gaussian kernel.
"""
function imlog(sigma::Number=0.5)
m = ceil(8.5sigma)
m = m % 2 == 0 ? m + 1 : m
return [(1/(2pi*sigma^4))*(2 - (x^2 + y^2)/sigma^2)*exp(-(x^2 + y^2)/(2sigma^2))
for x=-floor(m/2):floor(m/2), y=-floor(m/2):floor(m/2)]
end
# Sum of squared differences and sum of absolute differences
for (f, op) in ((:ssd, :(abs2(x))), (:sad, :(abs(x))))
@eval begin
function ($f)(A::AbstractArray, B::AbstractArray)
size(A) == size(B) || throw(DimensionMismatch("A and B must have the same size"))
T = promote_type(difftype(eltype(A)), difftype(eltype(B)))
s = zero(accum(eltype(T)))
for i = 1:length(A)
x = convert(T, A[i]) - convert(T, B[i])
s += $op
end
s
end
end
end
"`s = ssd(A, B)` computes the sum-of-squared differences over arrays/images A and B" ssd
"`s = sad(A, B)` computes the sum-of-absolute differences over arrays/images A and B" sad
difftype{T<:Integer}(::Type{T}) = Int
difftype{T<:Real}(::Type{T}) = Float32
difftype(::Type{Float64}) = Float64
difftype{CV<:Colorant}(::Type{CV}) = difftype(CV, eltype(CV))
difftype{CV<:RGBA,T<:Real}(::Type{CV}, ::Type{T}) = RGBA{Float32}
difftype{CV<:RGBA}(::Type{CV}, ::Type{Float64}) = RGBA{Float64}
difftype{CV<:BGRA,T<:Real}(::Type{CV}, ::Type{T}) = BGRA{Float32}
difftype{CV<:BGRA}(::Type{CV}, ::Type{Float64}) = BGRA{Float64}
difftype{CV<:AbstractGray,T<:Real}(::Type{CV}, ::Type{T}) = Gray{Float32}
difftype{CV<:AbstractGray}(::Type{CV}, ::Type{Float64}) = Gray{Float64}
difftype{CV<:AbstractRGB,T<:Real}(::Type{CV}, ::Type{T}) = RGB{Float32}
difftype{CV<:AbstractRGB}(::Type{CV}, ::Type{Float64}) = RGB{Float64}
accum{T<:Integer}(::Type{T}) = Int
accum(::Type{Float32}) = Float32
accum{T<:Real}(::Type{T}) = Float64
# normalized by Array size
"`s = ssdn(A, B)` computes the sum-of-squared differences over arrays/images A and B, normalized by array size"
ssdn{T}(A::AbstractArray{T}, B::AbstractArray{T}) = ssd(A, B)/length(A)
# normalized by Array size
"`s = sadn(A, B)` computes the sum-of-absolute differences over arrays/images A and B, normalized by array size"
sadn{T}(A::AbstractArray{T}, B::AbstractArray{T}) = sad(A, B)/length(A)
# normalized cross correlation
"""
`C = ncc(A, B)` computes the normalized cross-correlation of `A` and `B`.
"""
function ncc{T}(A::AbstractArray{T}, B::AbstractArray{T})
Am = (data(A).-mean(data(A)))[:]
Bm = (data(B).-mean(data(B)))[:]
return dot(Am,Bm)/(norm(Am)*norm(Bm))
end
# Simple image difference testing
macro test_approx_eq_sigma_eps(A, B, sigma, eps)
quote
if size($(esc(A))) != size($(esc(B)))
error("Sizes ", size($(esc(A))), " and ",
size($(esc(B))), " do not match")
end
Af = imfilter_gaussian($(esc(A)), $(esc(sigma)))
Bf = imfilter_gaussian($(esc(B)), $(esc(sigma)))
diffscale = max(maxabsfinite($(esc(A))), maxabsfinite($(esc(B))))
d = sad(Af, Bf)
if d > length(Af)*diffscale*($(esc(eps)))
error("Arrays A and B differ")
end
end
end
# image difference testing (@tbreloff's, based on the macro)
# A/B: images/arrays to compare
# sigma: tuple of ints... how many pixels to blur
# eps: error allowance
# returns: percentage difference on match, error otherwise
function test_approx_eq_sigma_eps{T<:Real}(A::AbstractArray, B::AbstractArray,
sigma::AbstractVector{T} = ones(ndims(A)),
eps::AbstractFloat = 1e-2,
expand_arrays::Bool = true)
if size(A) != size(B)
if expand_arrays
newsize = map(max, size(A), size(B))
if size(A) != newsize
A = copy!(zeros(eltype(A), newsize...), A)
end
if size(B) != newsize
B = copy!(zeros(eltype(B), newsize...), B)
end
else
error("Arrays differ: size(A): $(size(A)) size(B): $(size(B))")
end
end
if length(sigma) != ndims(A)
error("Invalid sigma in test_approx_eq_sigma_eps. Should be ndims(A)-length vector of the number of pixels to blur. Got: $sigma")
end
Af = imfilter_gaussian(A, sigma)
Bf = imfilter_gaussian(B, sigma)
diffscale = max(maxabsfinite(A), maxabsfinite(B))
d = sad(Af, Bf)
diffpct = d / (length(Af) * diffscale)
if diffpct > eps
error("Arrays differ. Difference: $diffpct eps: $eps")
end
diffpct
end
# Array padding
function padindexes{T,n}(img::AbstractArray{T,n}, prepad::Union{Vector{Int},Dims}, postpad::Union{Vector{Int},Dims}, border::AbstractString)
I = Array(Vector{Int}, n)
for d = 1:n
I[d] = padindexes(img, d, prepad[d], postpad[d], border)
end
I
end
"""
```
imgpad = padarray(img, prepad, postpad, border, value)
```
For an `N`-dimensional array `img`, apply padding on both edges. `prepad` and
`postpad` are vectors of length `N` specifying the number of pixels used to pad
each dimension. `border` is a string, one of `"value"` (to pad with a specific
pixel value), `"replicate"` (to repeat the edge value), `"circular"` (periodic
boundary conditions), `"reflect"` (reflecting boundary conditions, where the
reflection is centered on edge), and `"symmetric"` (reflecting boundary
conditions, where the reflection is centered a half-pixel spacing beyond the
edge, so the edge value gets repeated). Arrays are automatically padded before
filtering. Use `"inner"` to avoid padding altogether; the output array will be
smaller than the input.
"""
function padarray{T,n}(img::AbstractArray{T,n}, prepad::Union{Vector{Int},Dims}, postpad::Union{Vector{Int},Dims}, border::AbstractString)
img[padindexes(img, prepad, postpad, border)...]::Array{T,n}
end
function padarray{n}(img::BitArray{n}, prepad::Union{Vector{Int},Dims}, postpad::Union{Vector{Int},Dims}, border::AbstractString)
img[padindexes(img, prepad, postpad, border)...]::BitArray{n}
end
function padarray{n,A<:BitArray}(img::Image{Bool,n,A}, prepad::Union{Vector{Int},Dims}, postpad::Union{Vector{Int},Dims}, border::AbstractString)
img[padindexes(img, prepad, postpad, border)...]::BitArray{n}
end
function padarray{T,n}(img::AbstractArray{T,n}, prepad::Union{Vector{Int},Dims}, postpad::Union{Vector{Int},Dims}, border::AbstractString, value)
if border != "value"
return padarray(img, prepad, postpad, border)
end
A = Array(T, ntuple(d->size(img,d)+prepad[d]+postpad[d], n))
fill!(A, value)
I = Vector{Int}[1+prepad[d]:size(A,d)-postpad[d] for d = 1:n]
A[I...] = img
A::Array{T,n}
end
padarray{T,n}(img::AbstractArray{T,n}, padding::Union{Vector{Int},Dims}, border::AbstractString = "replicate") = padarray(img, padding, padding, border)
# Restrict the following to Number to avoid trouble when img is an Array{AbstractString}
padarray{T<:Number,n}(img::AbstractArray{T,n}, padding::Union{Vector{Int},Dims}, value::T) = padarray(img, padding, padding, "value", value)
function padarray{T,n}(img::AbstractArray{T,n}, padding::Union{Vector{Int},Dims}, border::AbstractString, direction::AbstractString)
if direction == "both"
return padarray(img, padding, padding, border)
elseif direction == "pre"
return padarray(img, padding, zeros(Int, n), border)
elseif direction == "post"
return padarray(img, zeros(Int, n), padding, border)
end
end
function padarray{T<:Number,n}(img::AbstractArray{T,n}, padding::Vector{Int}, value::T, direction::AbstractString)
if direction == "both"
return padarray(img, padding, padding, "value", value)
elseif direction == "pre"
return padarray(img, padding, zeros(Int, n), "value", value)
elseif direction == "post"
return padarray(img, zeros(Int, n), padding, "value", value)
end
end
function prep_kernel(img::AbstractArray, kern::AbstractArray)
sc = coords_spatial(img)
if ndims(kern) > length(sc)
error("""The kernel has $(ndims(kern)) dimensions, more than the $(sdims(img)) spatial dimensions of img.
You'll need to set the dimensions and type of the kernel to be the same as the image.""")
end
sz = ones(Int, ndims(img))
for i = 1:ndims(kern)
sz[sc[i]] = size(kern,i)
end
reshape(kern, sz...)
end
###
### imfilter
###
"""
```
imgf = imfilter(img, kernel, [border, value])
```
filters the array `img` with the given `kernel`, using boundary conditions
specified by `border` and `value`. See `padarray` for an explanation of
the boundary conditions. Default is to use `"replicate"` boundary conditions.
This uses finite-impulse-response (FIR) filtering, and is fast only for
relatively small `kernel`s.
See also: `imfilter_fft`, `imfilter_gaussian`.
"""
imfilter(img, kern, border, value) = imfilter_inseparable(img, kern, border, value)
# Do not combine these with the previous using a default value (see the 2d specialization below)
imfilter(img, filter) = imfilter(img, filter, "replicate", zero(eltype(img)))
imfilter(img, filter, border) = imfilter(img, filter, border, zero(eltype(img)))
imfilter_inseparable{T,K,N,M}(img::AbstractArray{T,N}, kern::AbstractArray{K,M}, border::AbstractString, value) =
imfilter_inseparable(img, prep_kernel(img, kern), border, value)
function imfilter_inseparable{T,K,N}(img::AbstractArray{T,N}, kern::AbstractArray{K,N}, border::AbstractString, value)
if border == "inner"
result = Array(typeof(one(T)*one(K)), ntuple(d->max(0, size(img,d)-size(kern,d)+1), N))
imfilter!(result, img, kern)
else
prepad = [div(size(kern,i)-1, 2) for i = 1:N]
postpad = [div(size(kern,i), 2) for i = 1:N]
A = padarray(img, prepad, postpad, border, convert(T, value))
result = imfilter!(Array(typeof(one(T)*one(K)), size(img)), A, data(kern))
end
copyproperties(img, result)
end
# Special case for 2d kernels: check for separability
function imfilter{T}(img::AbstractArray{T}, kern::AbstractMatrix, border::AbstractString, value)
sc = coords_spatial(img)
if length(sc) < 2
imfilter_inseparable(img, kern, border, value)
end
SVD = svdfact(kern)
U, S, Vt = SVD[:U], SVD[:S], SVD[:Vt]
separable = true
EPS = sqrt(eps(eltype(S)))
for i = 2:length(S)
separable &= (abs(S[i]) < EPS)
end
if !separable
return imfilter_inseparable(img, kern, border, value)
end
s = S[1]
u,v = U[:,1],Vt[1,:]
ss = sqrt(s)
sz1 = ones(Int, ndims(img)); sz1[sc[1]] = size(kern, 1)
sz2 = ones(Int, ndims(img)); sz2[sc[2]] = size(kern, 2)
tmp = imfilter_inseparable(data(img), reshape(u*ss, sz1...), border, value)
copyproperties(img, imfilter_inseparable(tmp, reshape(v*ss, sz2...), border, value))
end
for N = 1:5
@eval begin
function imfilter!{T,K}(B, A::AbstractArray{T,$N}, kern::AbstractArray{K,$N})
for i = 1:$N
if size(B,i)+size(kern,i) > size(A,i)+1
throw(DimensionMismatch("Output dimensions $(size(B)) and kernel dimensions $(size(kern)) do not agree with size of padded input, $(size(A))"))
end
end
(isempty(A) || isempty(kern)) && return B
p = A[1]*kern[1]
TT = typeof(p+p)
@nloops $N i B begin
tmp = zero(TT)
@inbounds begin
@nloops $N j kern d->(k_d = i_d+j_d-1) begin
tmp += (@nref $N A k)*(@nref $N kern j)
end
(@nref $N B i) = tmp
end
end
B
end
end
end
"""
```
imfilter!(dest, img, kernel)
```
filters the image with the given `kernel`, storing the output in the
pre-allocated output `dest`. The size of `dest` must not be greater than the
size of the result of `imfilter` with `border = "inner"`, and it behaves
identically. This uses finite-impulse-response (FIR) filtering, and is fast
only for relatively small `kernel`s.
No padding is performed; see `padarray` for options if you want to do
this manually.
See also: `imfilter`, `padarray`.
"""
imfilter!
###
### imfilter_fft
###
"""
```
imgf = imfilter_fft(img, kernel, [border, value])
```
filters `img` with the given `kernel` using an FFT algorithm. This
is slower than `imfilter` for small kernels, but much faster for large
kernels. For Gaussian blur, an even faster choice is `imfilter_gaussian`.
See also: `imfilter`, `imfilter_gaussian`.
"""
imfilter_fft(img, kern, border, value) = copyproperties(img, imfilter_fft_inseparable(img, kern, border, value))
imfilter_fft(img, filter) = imfilter_fft(img, filter, "replicate", 0)
imfilter_fft(img, filter, border) = imfilter_fft(img, filter, border, 0)
imfilter_fft_inseparable{T,K,N,M}(img::AbstractArray{T,N}, kern::AbstractArray{K,M}, border::AbstractString, value) =
imfilter_fft_inseparable(img, prep_kernel(img, kern), border, value)
function imfilter_fft_inseparable{T<:Colorant,K,N,M}(img::AbstractArray{T,N}, kern::AbstractArray{K,M}, border::AbstractString, value)
A = reinterpret(eltype(T), data(img))
kernrs = reshape(kern, tuple(1, size(kern)...))
B = imfilter_fft_inseparable(A, prep_kernel(A, kernrs), border, value)
reinterpret(base_colorant_type(T), B)
end
function imfilter_fft_inseparable{T<:Real,K,N}(img::AbstractArray{T,N}, kern::AbstractArray{K,N}, border::AbstractString, value)
if border == "circular" && size(img) == size(kern)
A = data(img)
krn = reflect(kern)
out = real(ifftshift(ifft(fft(A).*fft(krn))))
elseif border != "inner"
prepad = [div(size(kern,i)-1, 2) for i = 1:N]
postpad = [div(size(kern,i), 2) for i = 1:N]
fullpad = Int[nextprod([2,3], size(img,i) + prepad[i] + postpad[i]) - size(img, i) - prepad[i] for i = 1:N] # work around julia #15276
A = padarray(img, prepad, fullpad, border, convert(T, value))
krn = zeros(eltype(one(T)*one(K)), size(A))
indexesK = ntuple(d->[size(krn,d)-prepad[d]+1:size(krn,d);1:size(kern,d)-prepad[d]], N)
krn[indexesK...] = reflect(kern)
AF = ifft(fft(A).*fft(krn))
out = Array(realtype(eltype(AF)), size(img))
indexesA = ntuple(d->postpad[d]+1:size(img,d)+postpad[d], N)
copyreal!(out, AF, indexesA)
else
A = data(img)
prepad = [div(size(kern,i)-1, 2) for i = 1:N]
postpad = [div(size(kern,i), 2) for i = 1:N]
krn = zeros(eltype(one(T)*one(K)), size(A))
indexesK = ntuple(d->[size(krn,d)-prepad[d]+1:size(krn,d);1:size(kern,d)-prepad[d]], N)
krn[indexesK...] = reflect(kern)
AF = ifft(fft(A).*fft(krn))
out = Array(realtype(eltype(AF)), ([size(img)...] - prepad - postpad)...)
indexesA = ntuple(d->postpad[d]+1:size(img,d)-prepad[d], N)
copyreal!(out, AF, indexesA)
end
out
end
# flips the dimension specified by name instead of index
# it is thus independent of the storage order
Base.flipdim(img::AbstractImage, dimname::String) = shareproperties(img, flipdim(data(img), dimindex(img, dimname)))
flipx(img::AbstractImage) = flipdim(img, "x")
flipy(img::AbstractImage) = flipdim(img, "y")
flipz(img::AbstractImage) = flipdim(img, "z")
# Generalization of rot180
@generated function reflect{T,N}(A::AbstractArray{T,N})
quote
B = Array(T, size(A))
@nexprs $N d->(n_d = size(A, d)+1)
@nloops $N i A d->(j_d = n_d - i_d) begin
@nref($N, B, j) = @nref($N, A, i)
end
B
end
end
for N = 1:5
@eval begin
function copyreal!{T<:Real}(dst::Array{T,$N}, src, I::Tuple{Vararg{UnitRange{Int}}})
@nexprs $N d->(I_d = I[d])
@nloops $N i dst d->(j_d = first(I_d)+i_d-1) begin
(@nref $N dst i) = real(@nref $N src j)
end
dst
end
function copyreal!{T<:Complex}(dst::Array{T,$N}, src, I::Tuple{Vararg{UnitRange{Int}}})
@nexprs $N d->I_d = I[d]
@nloops $N i dst d->(j_d = first(I_d)+i_d-1) begin
(@nref $N dst i) = @nref $N src j
end
dst
end
end
end
realtype{R<:Real}(::Type{R}) = R
realtype{R<:Real}(::Type{Complex{R}}) = R
# IIR filtering with Gaussians
# See
# Young, van Vliet, and van Ginkel, "Recursive Gabor Filtering",
# IEEE TRANSACTIONS ON SIGNAL PROCESSING, VOL. 50: 2798-2805.
# and
# Triggs and Sdika, "Boundary Conditions for Young - van Vliet
# Recursive Filtering, IEEE TRANSACTIONS ON SIGNAL PROCESSING,
# Here we're using NA boundary conditions, so we set i- and i+
# (in Triggs & Sdika notation) to zero.
# Note these two papers use different sign conventions for the coefficients.
# Note: astype is ignored for AbstractFloat input
"""
```
imgf = imfilter_gaussian(img, sigma)
```
filters `img` with a Gaussian of the specified width. `sigma` should have
one value per array dimension (any number of dimensions are supported), 0
indicating that no filtering is to occur along that dimension. Uses the Young,
van Vliet, and van Ginkel IIR-based algorithm to provide fast gaussian filtering
even with large `sigma`. Edges are handled by "NA" conditions, meaning the
result is normalized by the number and weighting of available pixels, and
missing data (NaNs) are handled likewise.
"""
function imfilter_gaussian{CT<:Colorant}(img::AbstractArray{CT}, sigma; emit_warning = true, astype::Type=Float64)
A = reinterpret(eltype(CT), data(img))
newsigma = ndims(A) > ndims(img) ? [0;sigma] : sigma
ret = imfilter_gaussian(A, newsigma; emit_warning=emit_warning, astype=astype)
shareproperties(img, reinterpret(base_colorant_type(CT), ret))
end
function imfilter_gaussian{T<:AbstractFloat}(img::AbstractArray{T}, sigma::Vector; emit_warning = true, astype::Type=Float64)
if all(sigma .== 0)
return img
end
A = copy(data(img))
nanflag = isnan(A)
hasnans = any(nanflag)
if hasnans
A[nanflag] = zero(T)
validpixels = convert(Array{T}, !nanflag)
imfilter_gaussian!(A, validpixels, sigma; emit_warning=emit_warning)
A[nanflag] = convert(T, NaN)
else
imfilter_gaussian_no_nans!(A, sigma; emit_warning=emit_warning)
end
shareproperties(img, A)
end
# For these types, you can't have NaNs
function imfilter_gaussian{T<:Union{Integer,UFixed},TF<:AbstractFloat}(img::AbstractArray{T}, sigma::Vector; emit_warning = true, astype::Type{TF}=Float64)
A = copy!(Array(TF, size(img)), data(img))
if all(sigma .== 0)
return shareproperties(img, A)
end
imfilter_gaussian_no_nans!(A, sigma; emit_warning=emit_warning)
shareproperties(img, A)
end
# This version is in-place, and destructive
# Any NaNs have to already be removed from data (and marked in validpixels)
function imfilter_gaussian!{T<:AbstractFloat}(data::Array{T}, validpixels::Array{T}, sigma::Vector; emit_warning = true)
nd = ndims(data)
if length(sigma) != nd
error("Dimensionality mismatch")
end
_imfilter_gaussian!(data, sigma, emit_warning=emit_warning)
_imfilter_gaussian!(validpixels, sigma, emit_warning=false)
for i = 1:length(data)
data[i] /= validpixels[i]
end
return data
end
# When there are no NaNs, the normalization is separable and hence can be computed far more efficiently
# This speeds the algorithm by approximately twofold
function imfilter_gaussian_no_nans!{T<:AbstractFloat}(data::Array{T}, sigma::Vector; emit_warning = true)
nd = ndims(data)
if length(sigma) != nd
error("Dimensionality mismatch")
end
_imfilter_gaussian!(data, sigma, emit_warning=emit_warning)
denom = Array(Vector{T}, nd)
for i = 1:nd
denom[i] = ones(T, size(data, i))
if sigma[i] > 0
_imfilter_gaussian!(denom[i], sigma[i:i], emit_warning=false)
end
end
imfgnormalize!(data, denom)
return data
end
for N = 1:5
@eval begin
function imfgnormalize!{T}(data::Array{T,$N}, denom)
@nextract $N denom denom
@nloops $N i data begin
den = one(T)
@nexprs $N d->(den *= denom_d[i_d])
(@nref $N data i) /= den
end
end
end
end
function iir_gaussian_coefficients(T::Type, sigma::Number; emit_warning::Bool = true)
if sigma < 1 && emit_warning
warn("sigma is too small for accuracy")
end
m0 = convert(T,1.16680)
m1 = convert(T,1.10783)
m2 = convert(T,1.40586)
q = convert(T,1.31564*(sqrt(1+0.490811*sigma*sigma) - 1))
scale = (m0+q)*(m1*m1 + m2*m2 + 2m1*q + q*q)
B = m0*(m1*m1 + m2*m2)/scale
B *= B
# This is what Young et al call b, but in filt() notation would be called a
a1 = q*(2*m0*m1 + m1*m1 + m2*m2 + (2*m0+4*m1)*q + 3*q*q)/scale
a2 = -q*q*(m0 + 2m1 + 3q)/scale
a3 = q*q*q/scale
a = [-a1,-a2,-a3]
Mdenom = (1+a1-a2+a3)*(1-a1-a2-a3)*(1+a2+(a1-a3)*a3)
M = [-a3*a1+1-a3^2-a2 (a3+a1)*(a2+a3*a1) a3*(a1+a3*a2);
a1+a3*a2 -(a2-1)*(a2+a3*a1) -(a3*a1+a3^2+a2-1)*a3;
a3*a1+a2+a1^2-a2^2 a1*a2+a3*a2^2-a1*a3^2-a3^3-a3*a2+a3 a3*(a1+a3*a2)]/Mdenom;
return a, B, M
end
function _imfilter_gaussian!{T<:AbstractFloat}(A::Array{T}, sigma::Vector; emit_warning::Bool = true)
nd = ndims(A)
szA = [size(A,i) for i = 1:nd]
strdsA = [stride(A,i) for i = 1:nd]
for d = 1:nd
if sigma[d] == 0
continue
end
if size(A, d) < 3
error("All filtered dimensions must be of size 3 or larger")
end
a, B, M = iir_gaussian_coefficients(T, sigma[d], emit_warning=emit_warning)
a1 = a[1]
a2 = a[2]
a3 = a[3]
n1 = size(A,1)
keepdims = [false;trues(nd-1)]
if d == 1
x = zeros(T, 3)
vstart = zeros(T, 3)
szhat = szA[keepdims]
strdshat = strdsA[keepdims]
if isempty(szhat)
szhat = [1]
strdshat = [1]
end
@inbounds @forcartesian c szhat begin
coloffset = offset(c, strdshat)
A[2+coloffset] -= a1*A[1+coloffset]
A[3+coloffset] -= a1*A[2+coloffset] + a2*A[1+coloffset]
for i = 4+coloffset:n1+coloffset
A[i] -= a1*A[i-1] + a2*A[i-2] + a3*A[i-3]
end
copytail!(x, A, coloffset, 1, n1)
A_mul_B!(vstart, M, x)
A[n1+coloffset] = vstart[1]
A[n1-1+coloffset] -= a1*vstart[1] + a2*vstart[2] + a3*vstart[3]
A[n1-2+coloffset] -= a1*A[n1-1+coloffset] + a2*vstart[1] + a3*vstart[2]
for i = n1-3+coloffset:-1:1+coloffset
A[i] -= a1*A[i+1] + a2*A[i+2] + a3*A[i+3]
end
end
else
x = Array(T, 3, n1)
vstart = similar(x)
keepdims[d] = false
szhat = szA[keepdims]
szd = szA[d]
strdshat = strdsA[keepdims]
strdd = strdsA[d]
if isempty(szhat)
szhat = [1]
strdshat = [1]
end
@inbounds @forcartesian c szhat begin
coloffset = offset(c, strdshat) # offset for the remaining dimensions
for i = 1:n1 A[i+strdd+coloffset] -= a1*A[i+coloffset] end
for i = 1:n1 A[i+2strdd+coloffset] -= a1*A[i+strdd+coloffset] + a2*A[i+coloffset] end
for j = 3:szd-1
jj = j*strdd+coloffset
for i = jj+1:jj+n1 A[i] -= a1*A[i-strdd] + a2*A[i-2strdd] + a3*A[i-3strdd] end
end
copytail!(x, A, coloffset, strdd, szd)
A_mul_B!(vstart, M, x)
for i = 1:n1 A[i+(szd-1)*strdd+coloffset] = vstart[1,i] end
for i = 1:n1 A[i+(szd-2)*strdd+coloffset] -= a1*vstart[1,i] + a2*vstart[2,i] + a3*vstart[3,i] end
for i = 1:n1 A[i+(szd-3)*strdd+coloffset] -= a1*A[i+(szd-2)*strdd+coloffset] + a2*vstart[1,i] + a3*vstart[2,i] end
for j = szd-4:-1:0