Convert an RGB image to grayscale but keep one color?

A = imread('C:\FFOutput\gdgf\B.jpg'); B = rgb2gray(A); figure(1),imshow(B);
I have converted the image to a grayscale but don't know how to keep one color especially green.

回答 (4 件)

yonatan gerufi
yonatan gerufi 2014 年 9 月 7 日
編集済み: yonatan gerufi 2014 年 9 月 7 日

0 投票

Hi, there are several ways to do it,
i find it easy to do:
red_color = A(:,:,1);
green_color = A(:,:,2);
blue_color = A(:,:,3);

1 件のコメント

Jaja
Jaja 2014 年 9 月 7 日
how can I add this to my code to keep the green one? can you give me an example with the code??

サインインしてコメントする。

John
John 2014 年 9 月 7 日

0 投票

I am guessing you want the green channel stored in a separate matrix. In your code, A is only read. Its value does not change after the call to rgb2gray. To get the green channel from A:
greenChannel = A(:,:,2);

1 件のコメント

Jaja
Jaja 2014 年 9 月 7 日
nothing happens actually. can you give me an example with the code??

サインインしてコメントする。

Image Analyst
Image Analyst 2014 年 9 月 7 日

0 投票

3 件のコメント

Image Analyst
Image Analyst 2014 年 9 月 7 日
Code is attached.
Jaja
Jaja 2014 年 9 月 25 日
I actually want to keep the color green in the picture and the rest of the color is in the grayscale
Image Analyst
Image Analyst 2014 年 9 月 25 日
Why? That's pretty much what the original image is already.

サインインしてコメントする。

DGM
DGM 2022 年 10 月 21 日
編集済み: DGM 2023 年 2 月 13 日

0 投票

Refer to this answer for more details on how this can be done. While that link includes multiple methods, I'm going to use MIMT replacepixels() for ease of use.
% this is a color image
rgbpict = imread('coloredChips.png');
% create a grayscale copy by some means
graypict = rgb2gray(rgbpict); % BT601 luma
% HSV ranges for masking
rangeR = [0.963 0.016; 0.258 1; 0.338 1];
rangeG = [0.380 0.453; 0.258 1; 0.338 1];
% create masks to select objects of specified colors
hsvpict = rgb2hsv(rgbpict);
maskR = all(hsvpict >= permute(rangeR(:,1),[2 3 1]),3) ...
| all(hsvpict <= permute(rangeR(:,2),[2 3 1]),3);
maskG = all(hsvpict >= permute(rangeG(:,1),[2 3 1]),3) ...
& all(hsvpict <= permute(rangeG(:,2),[2 3 1]),3);
% clean the masks
maskR = bwareaopen(maskR,100);
maskG = bwareaopen(maskG,100);
% composite the color and gray images using the masks
% replacepixels is from MIMT
outpictR = replacepixels(rgbpict,graypict,maskR);
outpictG = replacepixels(rgbpict,graypict,maskG);
See this answer for more details on how the masking could be done for this particular image.
See also this thread about different ways of partially desaturating a part of an image.

質問済み:

2014 年 9 月 7 日

編集済み:

DGM
2023 年 2 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by