How can I vectorize the following code?

main.m
I = imread('bear.png');
J = rgb2gray(imread('marked_bear.png'));
mask = I-J;
for r=1:size(I,1)
for c=1:size(I,2)
if(mask(r,c))
I = some_function(I, r, c);
end
end
end
imshow(I);
some_function.m
function I = some_function(I, r, c)
% some processing on image 'I'
I(r,c) = 255;
bear.png
marked_bear.png

 采纳的回答

Like this:
I = imread('bear.png');
J = rgb2gray(imread('marked_bear.png'));
mask = I-J; % Weird, but okay...whatever.
I(mask~=0)=255;

4 个评论

1. function needs to be there. Coz, it's not that simple always.
2. Why do you think it's weird?
To make a funciton
function I = MaskI(I, J)
mask = I - J;
I(mask ~= 0) = 255;
Usually people use logical operations to create masks that are binary images, not arithmetic ones that produce integer images, that may depend on clipping, and then which still have to use logical operations anyway, such as mask ~=0. Most people, seeing what you intend, would have done:
mask = I ~= J;
and most people who write code for industry that needs to be maintained would use more descriptive variable names than I and J. I know Mathworks doesn't because they want their demo code to look as simple as possible, but I wouldn't let them write code like that in my company.
I was talking about retaining some_function().
OK, then...
function I = some_function(I, J)
mask = I - J;
I(mask ~= 0) = 255;
There. It's vectorized, still has a function, and that function is called "some_function" (instead of MaskI as I had called it), just like you asked for.

请先登录,再进行评论。

更多回答(0 个)

标签

Community Treasure Hunt

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

Start Hunting!

Translated by