Skip to content

Commit

Permalink
Fix overflow in contrast-stretching (#59)
Browse files Browse the repository at this point in the history
Fixes #58
  • Loading branch information
timholy authored Jul 23, 2023
1 parent 979ff71 commit 64f8123
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/algorithms/contrast_stretching.jl
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,15 @@ ret = adjust_histogram(img, ContrastStretching(t = 0.6, slope = 3))
T₂ <: Union{Real,AbstractGray}} <: AbstractHistogramAdjustmentAlgorithm
t::T₁ = 0.5
slope::T₂ = 1.0
ϵ::Union{T₁,Nothing} = nothing
end
ContrastStretching(t::T₁, slope::T₂, ϵ::Union{Real,AbstractGray}) where {T₁ <: Union{Real,AbstractGray},
T₂ <: Union{Real,AbstractGray}} =
ContrastStretching{T₁,T₂}(t, slope, T₁(ϵ))

function (f::ContrastStretching)(out::GenericGrayImage, img::GenericGrayImage)
T = eltype(out)
ϵ = eps(T)
ϵ = f.ϵ === nothing ? eps(T) : f.ϵ
out .= img
map!(out,out) do val
if isnan(val)
Expand All @@ -96,3 +100,4 @@ end
function contrast_stretch(x, t, s, ϵ)
return 1 / (1 + (t / (x+ϵ))^s)
end
contrast_stretch(x::Union{FixedPoint,AbstractGray{<:FixedPoint}}, t, s, ϵ) = contrast_stretch(float(x), t, s, ϵ)
12 changes: 12 additions & 0 deletions test/contrast_stretching.jl
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
using ImageCore
using ImageContrastAdjustment
using Test

@testset "Contrast Stretching" begin

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

#=
Verify that the function can cope with a NaN value.
Expand Down Expand Up @@ -76,4 +83,9 @@
edges, counts_after = build_histogram(ret, 16, minval = 0, maxval = 1)
@test sum(counts_after .!= 0) == 2
end

# Issue #58
img = Gray{N0f8}.([1 0; 0 1])
@test adjust_histogram(img, ContrastStretching(t=0.3, slope=0.4)) ==
Gray{N0f8}.(adjust_histogram(float.(img), ContrastStretching(t=0.3, slope=0.4, ϵ=eps(N0f8))))
end

0 comments on commit 64f8123

Please sign in to comment.