Replace a certain color in an image with another color Matlab

时光怂恿深爱的人放手 提交于 2019-12-11 12:08:26

问题


I have an image that I opened in Matlab using imshow and I want to replace the color of every pixel with value (140,50,61) with a new color (150,57,80). If anyone could please advise how I can do this.


回答1:


Assuming A to be the input image data, this could be one approach -

%// Initialize vectors for old and new pixels tuplets
oldval = [140,50,61]
newval = [150,57,80]

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

%// Find out which columns match up with the oldval [3x1] values
matches  = all(bsxfun(@eq,B,oldval(:)),1)
%// OR matches = matches = ismember(B',oldval(:)','rows')

%// 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))

Sample run -

>> A
A(:,:,1) =
   140   140   140
    40   140   140
A(:,:,2) =
    50    20    50
    50    50    50
A(:,:,3) =
    61    65    61
    61    61    61
>> out
out(:,:,1) =
   150   140   150
    40   150   150
out(:,:,2) =
    57    20    57
    50    57    57
out(:,:,3) =
    80    65    80
    61    80    80



回答2:


bsxfun is the way I would have solved it. However, if you aren't familiar with it, you can extract each channel from your image, use three logical masks for each channel and combine them all using logical AND. Doing AND will find those pixels in your image that looks for that particular RGB triple.

As such, we set the outputs of each channel accordingly and reconstruct the image to produce the output.

Therefore, given your input image A, one could do:

red = A(:,:,1); green = A(:,:,2); blue = A(:,:,3);
mred = red == 140; mgreen = green == 50; mblue = blue == 61;
final_mask = mred & mgreen & mblue;
red(final_mask) = 150; green(final_mask) = 57; blue(final_mask) = 80;
out = cat(3, red, green, blue);


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

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