kimikage / ColorBlendModes.jl

blend modes such as multiply, screen, overlay and so on.
MIT License
4 stars 0 forks source link

3-arg non-allocating/inplace `blend!`? #37

Closed anandijain closed 2 years ago

anandijain commented 2 years ago

Hello,

I haven't dug too much into internals, but I'm wondering how hard it would be to write a 3-arg inplace blend! function that the allocating blend uses. I'm mainly looking to blend videos, so reusing the memory from one frame to the next is my goal.

This example might demonstrate what I'm thinking of (where v and v2 are equal lengths, of something like Vector{Matrix{RGB{N0f8}}}):

"allocates only a single frame"
function blendem(v, v2, mode=BlendHardLight)
    img = similar(v[1])
    for i in eachindex(v)
        blend!.(img, v[i], v2[i], mode=mode) # reuses `img`
        save("$i.jpeg", img)
    end
end

"allocates length(v) number of frames"
function blendem2(v, v2, mode=BlendHardLight)
    for i in eachindex(v)
        img = blend.(v[i], v2[i], mode=mode)
        save("$i.jpeg", img)
    end
end

There might be a way to do this without having to change this package, I'm not sure. Does this make any sense (ie will it cut down on allocations?)

kimikage commented 2 years ago

What about broadcast assignment (.=)?

function blendem3(v, v2, mode=BlendHardLight)
    img = similar(v[1])
    for i in eachindex(v)
        img .= blend.(v[i], v2[i], mode=mode) # reuses `img`
        save("$i.jpeg", img)
    end
end

If this is helpful to you, it would be worth adding that explanation to the documentation (https://kimikage.github.io/ColorBlendModes.jl/stable/blending-and-compositing/#Broadcasting).

kimikage commented 2 years ago

Feel free to reopen this if you still need to blend!.