vectorization in context of if-condition and comparison for image array

I want to implement some image compositing methods in Matlab like for example ModulusAdd defined as
if (Sca + Dca) <= 1
Dca = Sca + Dca;
else
Dca = (Sca + Dca) - 1;
end
Here Sca, Dca, Sa, Da are (h,w,1) arrays (gray scale images respective alpha channels) all as double (see also http://www.w3.org/TR/2014/CR-compositing-1-20140220/ for image compositing details).
Comparisons with the if-condition are defined for scalar values so using the above code in Matlab is not working directly (there are also other compositing methods that relay on other if-conditions like "if Sca == 0 && Dca == Da ..." that can not directly be ported so answering this question might also be helpful for those cases). Naively one has to deal with the pixel level and its two nested for-loops:
for i=1:h
for j=1:w
if (Sca(i,j) + Dca(i,j)) <= 1
Dca(i,j) = Sca(i,j) + Dca(i,j);
else
Dca(i,j) = (Sca(i,j) + Dca(i,j)) - 1;
end
end
end
How can I redesign this to make it work faster with an (h,w,1) (or (h,w,3)) array? Perhaps a redesign beyond arrayfun is possible (being not an expert in this):
Dca = arrayfun(@ModulusAdd_scalar, Sca, Dca);
function d = ModulusAdd_scalar(s, d)
if (s + d) <= 1
d = s + d;
else
d = (s + d) - 1;
end
end

Answers (0)

This question is closed.

Products

Release

R2016b

Asked:

on 22 Jul 2019

Closed:

on 20 Aug 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!