Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix overflow in contrast-stretching #59

Merged
merged 1 commit into from
Jul 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading