Replace a certain color range in an image with another color Matlab

て烟熏妆下的殇ゞ 提交于 2019-12-25 07:48:48

问题


how to replace the pixels having a certain RGB range not just a specific value as shown in this question like for example pixels with R ranging from 140-150, G ranging from 50-55 and B ranging from 61-70 , with another single value like (150,57,80). If anyone could please advise.


回答1:


This is also a modification to the answer I provided in the other question you posted earlier. You simply change the logical mask calculations so that we search for a range of red, green and blue values.

As such:

red = A(:,:,1); green = A(:,:,2); blue = A(:,:,3);

%// Change here
mred = red >= 140 & red <= 150; 
mgreen = green >= 50 & green <= 55; 
mblue = blue >= 61 & blue <= 70;

%// Back to before
final_mask = mred & mgreen & mblue;
red(final_mask) = 150; green(final_mask) = 57; blue(final_mask) = 80;
out = cat(3, red, green, blue);



回答2:


Turns out you would need few modifications there with finding the suitable matching pixel locations. Here's the implementation -

%// Initialize vectors for the lower and upper limits for finding suitable 
%// pixels to be replaced
lower_lim = [140,50,61]
upper_lim = [150,55,70]

%// Initialize vector for new pixels tuplet
newval = [150,57,80]

%// Reshape the input array to a 2D array, so that each column would
%// represent one pixel color information. 
B = reshape(permute(A,[3 1 2]),3,[])

%// Find out which columns fall within those ranges with `bsxfun(@ge` and `bsxfun(@le`
matches  = all(bsxfun(@ge,B,lower_lim(:)) & bsxfun(@le,B,upper_lim(:)),1)

%// Replace all those columns with the replicated versions of oldval
B(:,matches) = repmat(newval(:),1,sum(matches))

%// Reshape the 2D array back to the same size as input array
out = reshape(permute(B,[3 2 1]),size(A))


来源:https://stackoverflow.com/questions/28446743/replace-a-certain-color-range-in-an-image-with-another-color-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!