Replace multiple values in matrix / image
조회 수: 4 (최근 30일)
이전 댓글 표시
Hey there,
I have two matrices. One is an image, the other one is as big as the image with only one dimension. The second matrix indicates where I want to replace pixels in the image by a certain colour. For now I have replaced the pixels using loops. I wanted to get rid of those loops but still have no idea on how to do so.
My code so far looks like this:
(the mask contains values to indicate which pixels to replace. Contains different values for multiple replacements; toReplace contains the values in the mask, that should be replaced in the image)
for c=1:length(toReplace)
[Y, X] = find(mask == toReplace(c));
for p=1:size(Y,1)
img(Y(p),X(p),:) = color; % color is a 1x3 vertor
end
end
My closest try so far (At least 1 loop less):
o = ones(size(mask));
r = img(:,:,1);
g = img(:,:,2);
b = img(:,:,3);
for c=1:length(indicator)
r(mask==toReplace(c)) = o(mask==toReplace(c)).*color(1);
g(mask==toReplace(c)) = o(mask==toReplace(c)).*color(2);
b(mask==toReplace(c)) = o(mask==toReplace(c)).*color(3);
end
img(:,:,1) = r;
img(:,:,2) = g;
img(:,:,3) = b;
No idea if it will bring any performance improvements in the end :-)
Thanks in advance,
Patrick
댓글 수: 2
Neuropragmatist
2019년 8월 5일
I think I need a little more info on your code.
From what I understand you have an MxNx3 RBG image (img) and you have an MxNx1 logical matrix that defines pixels you want to replace (mask).
But you also have another matrix that has colours you want to replace in img called toReplace? What size is that matrix?
In the first piece of code you have posted where does the variable 'color' come from? And why are you testing where mask == toReplace(c)?
채택된 답변
Rik
2019년 8월 5일
You can use ismember to remove a loop. I put in a loop over the colors, but since that is only 3 iterations, that will not cause any issues.
im=rand(10,12,3);
mask=randi(10,size(im,1),size(im,2));
toReplace=[1 3];
color=[0 1 0];
im_out=im;
L=ismember(mask,toReplace);
[x,y]=find(L);n=numel(x);
for color_channel=1:3
ind=sub2ind(size(im),x,y,color_channel*ones(n,1));
im_out(ind)=color(color_channel);
end
figure(1),clf(1)
subplot(1,2,1)
imshow(im),title('original')
subplot(1,2,2)
imshow(im_out),title('processed')
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!