From fa63b18e85608fe40682f14c7dfd5cb4ffedfe6d Mon Sep 17 00:00:00 2001 From: kimikage Date: Sat, 7 Mar 2020 20:52:54 +0000 Subject: [PATCH] Add `complement` migrated from Images.jl Co-Authored-by: Ioannis Valasakis --- src/ColorVectorSpace.jl | 12 +++++++++++- test/runtests.jl | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/ColorVectorSpace.jl b/src/ColorVectorSpace.jl index 92a5e93..1df907c 100644 --- a/src/ColorVectorSpace.jl +++ b/src/ColorVectorSpace.jl @@ -27,7 +27,7 @@ import SpecialFunctions: gamma, lgamma, lfact using Statistics import Statistics: middle, _mean_promote -export RGBRGB, nan, dotc, dot, ⋅, hadamard, ⊙, tensor, ⊗, norm, varmult +export RGBRGB, complement, nan, dotc, dot, ⋅, hadamard, ⊙, tensor, ⊗, norm, varmult MathTypes{T,C} = Union{AbstractRGB{T},TransparentRGB{C,T},AbstractGray{T},TransparentGray{C,T}} @@ -225,6 +225,16 @@ for op in unaryOps @eval ($op)(c::AbstractGray) = Gray($op(gray(c))) end +""" + y = complement(x) + +Take the complement `1-x` of `x`. If `x` is a color with an alpha channel, +the alpha channel is left untouched. Don't forget to add a dot when `x` is +an array: `complement.(x)` +""" +complement(x::Union{Number,Colorant}) = oneunit(x)-x +complement(x::TransparentColor) = typeof(x)(complement(color(x)), alpha(x)) + middle(c::AbstractGray) = arith_colorant_type(c)(middle(gray(c))) middle(x::C, y::C) where {C<:AbstractGray} = arith_colorant_type(C)(middle(gray(x), gray(y))) diff --git a/test/runtests.jl b/test/runtests.jl index 3eb1d02..740b61f 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -479,6 +479,20 @@ ColorTypes.blue(c::RatRGB) = c.b @test cf ⋅ cf === (Float64(red(cf))^2 + Float64(green(cf))^2 + Float64(blue(cf))^2)/3 end + @testset "Complement" begin + @test complement(Gray(0.2)) === Gray(0.8) + @test complement(AGray(0.2f0, 0.7f0)) === AGray(0.8f0, 0.7f0) + @test complement(GrayA{N0f8}(0.2, 0.7)) === GrayA{N0f8}(0.8, 0.7) + @test_broken complement(Gray24(0.2)) === Gray24(0.8) + @test_broken complement(AGray32(0.2, 0.7)) === AGray32(0.8, 0.7) + + @test complement(RGB(0, 0.3, 1)) === RGB(1, 0.7, 0) + @test complement(ARGB(0, 0.3f0, 1, 0.7f0)) === ARGB(1, 0.7f0, 0, 0.7f0) + @test complement(RGBA{N0f8}(0, 0.6, 1, 0.7)) === RGBA{N0f8}(1, 0.4, 0.0, 0.7) + @test complement(RGB24(0, 0.6, 1)) === RGB24(1, 0.4, 0.0) + @test complement(ARGB32(0, 0.6, 1, 0.7)) === ARGB32(1, 0.4, 0.0, 0.7) + end + @testset "dotc" begin @test dotc(0.2, 0.2) == 0.2^2 @test dotc(Int8(3), Int16(6)) === 18