Skip to content

Commit 64f8123

Browse files
authored
Fix overflow in contrast-stretching (#59)
Fixes #58
1 parent 979ff71 commit 64f8123

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/algorithms/contrast_stretching.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,15 @@ ret = adjust_histogram(img, ContrastStretching(t = 0.6, slope = 3))
6666
T₂ <: Union{Real,AbstractGray}} <: AbstractHistogramAdjustmentAlgorithm
6767
t::T₁ = 0.5
6868
slope::T₂ = 1.0
69+
ϵ::Union{T₁,Nothing} = nothing
6970
end
71+
ContrastStretching(t::T₁, slope::T₂, ϵ::Union{Real,AbstractGray}) where {T₁ <: Union{Real,AbstractGray},
72+
T₂ <: Union{Real,AbstractGray}} =
73+
ContrastStretching{T₁,T₂}(t, slope, T₁(ϵ))
7074

7175
function (f::ContrastStretching)(out::GenericGrayImage, img::GenericGrayImage)
7276
T = eltype(out)
73-
ϵ = eps(T)
77+
ϵ = f.ϵ === nothing ? eps(T) : f.ϵ
7478
out .= img
7579
map!(out,out) do val
7680
if isnan(val)
@@ -96,3 +100,4 @@ end
96100
function contrast_stretch(x, t, s, ϵ)
97101
return 1 / (1 + (t / (x+ϵ))^s)
98102
end
103+
contrast_stretch(x::Union{FixedPoint,AbstractGray{<:FixedPoint}}, t, s, ϵ) = contrast_stretch(float(x), t, s, ϵ)

test/contrast_stretching.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
using ImageCore
2+
using ImageContrastAdjustment
3+
using Test
4+
15
@testset "Contrast Stretching" begin
26

37
for T in (Gray{N0f8}, Gray{N0f16}, Gray{Float32}, Gray{Float64})
@@ -21,6 +25,9 @@
2125
@test nonzero_before < nonzero_after
2226
@test nonzero_after == 16
2327
@test eltype(img) == eltype(ret)
28+
if eltype(T) <: FixedPoint
29+
@test ret T.(adjust_histogram(float.(img), ContrastStretching(t = 0.4, slope = 17)))
30+
end
2431

2532
#=
2633
Verify that the function can cope with a NaN value.
@@ -76,4 +83,9 @@
7683
edges, counts_after = build_histogram(ret, 16, minval = 0, maxval = 1)
7784
@test sum(counts_after .!= 0) == 2
7885
end
86+
87+
# Issue #58
88+
img = Gray{N0f8}.([1 0; 0 1])
89+
@test adjust_histogram(img, ContrastStretching(t=0.3, slope=0.4)) ==
90+
Gray{N0f8}.(adjust_histogram(float.(img), ContrastStretching(t=0.3, slope=0.4, ϵ=eps(N0f8))))
7991
end

0 commit comments

Comments
 (0)