将图像中的一种颜色更改为另一种颜色

时间:2016-10-23 20:58:10

标签: matlab image-processing

我想在图像中将绿色转换为红色。我已经编写了下面的代码,但它无法正常工作

   rgbImage = imread('image.jpg');
   [rows columns numberOfColorBands] = size(rgbImage);
   imshow(rgbImage, []);
   title('Original Color Image');
   redChannel = rgbImage(:, :, 1);
   greenChannel = rgbImage(:, :, 2);
   blueChannel = rgbImage(:, :, 3);
   rgbImage2 = cat(3, greenChannel, redChannel, blueChannel);
   imshow(rgbImage2, []);
   title('Green is now red');  

2 个答案:

答案 0 :(得分:2)

您的代码交换红色通道和绿色通道。

rgbImage2 = cat(3, greenChannel, redChannel, blueChannel);
将绿色代替红色,红色代替绿色(交换渠道)。

为了保持绿色通道不变,并用绿色替换(原始)红色,请使用以下内容:
rgbImage2 = cat(3, greenChannel, greenChannel, blueChannel);

peppers.png图片的结果:

rgbImage = imread('peppers.png');
[rows columns numberOfColorBands] = size(rgbImage);
imshow(rgbImage, []);
title('Original Color Image');
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
rgbImage2 = cat(3, greenChannel, greenChannel, blueChannel);
imshow(rgbImage2, []);
title('Green is now red');

enter image description here

原始图片:
enter image description here

答案 1 :(得分:1)

正如Rotem所说,你只是在交换红色和绿色通道。交换影响整个图像而不仅仅是绿色。

首先必须将绿色分段以将绿色更改为任何其他颜色。您可以在Matlab文档中找到几个examples

我尝试细分和更改绿色,下面的代码可能对您的图片无效,但我猜可能会得到不错的结果。

 rgbImage = imread('peppers.png');
 figure, imshow(rgbImage);
 title('Original Image');

 redChannel = rgbImage(:, :, 1);
 greenChannel = rgbImage(:, :, 2);
 blueChannel = rgbImage(:, :, 3);

 %% Now lets take the difference of each the channels. 
 % these subtracted images will be used to mask the segmented area.
 % If you are curious, plot them and see how they look!! 
 red_subtract_grn = redChannel-greenChannel;
 red_subtract_blue = redChannel-blueChannel;
 grn_subtract_blue = greenChannel - blueChannel;
 red_add_grn = double(redChannel)+double(greenChannel)+double(blueChannel);

 %% Lets segment the green color by filtering/thresholding technique,
 % we need to choose the index number according to rgbImage, one should tweak a bit to get better results. (These
 % numbers worked well for 'peppers.jpg' image.I have used indexing since its 
 % very neat and faster, alternatively you can use find() also).
 try_mask = ones(size(rgbImage(:,:,1))); %Initialize mask image.
 try_mask(red_subtract_blue < 7) = 0;    %remove background
 try_mask = medfilt2(try_mask,[4,4]);    %Filter unwanted scattered pixels.
 try_mask(red_subtract_grn > 40) = 0;
 try_mask(red_add_grn > 500) = 0;
 try_mask(grn_subtract_blue < 20) = 0;
 try_mask(blueChannel > 80) = 0;
 try_mask = medfilt2(try_mask,[8,8]);

 %% Lets apply mask to remove green and blue pixels such that only red color will appear on the masked region.
 greenChannel(try_mask > 0) = 0;
 blueChannel(try_mask > 0) = 0;
 rgbImage2 = cat(3, redChannel, greenChannel, blueChannel);

 figure, imshow(rgbImage2);
 title('After changing green to red')

绿色到红色:

img

相关问题