Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I convert an RGB image to grayscale but keep one color?
    primarykey
    data
    text
    <p>I am trying to create an effect similar to <em>Sin City</em> or other movies where they remove all colors except one from an image.</p> <p>I have an RGB image which I want to convert to grayscale but I want to keep one color.</p> <p>This is my picture:</p> <p><img src="https://i.stack.imgur.com/EcyOd.jpg" alt="alt text"></p> <p>I want to keep the red color. The rest should be grayscale.</p> <p>This is what my code outputs so far (you can see that the areas are correct, I don't know why they are white instead of red though):</p> <p><img src="https://i.stack.imgur.com/22O60.jpg" alt="alt text"></p> <p>Here is my code so far:</p> <pre><code>filename = 'roses.jpg'; [cdata,map] = imread( filename ); % convert to RGB if it is indexed image if ~isempty( map ) cdata = idx2rgb( cdata, map ); end %imtool('roses.jpg'); imWidth = 685; imHeight = 428; % RGB ranges of a color we want to keep redRange = [140 255]; greenRange = [0 40]; blueRange = [0 40]; % RGB values we don't want to convert to grayscale redToKeep = zeros(imHeight, imWidth); greenToKeep = zeros(imHeight, imWidth); blueToKeep = zeros(imHeight, imWidth); for x=1:imWidth for y=1:imHeight red = cdata( y, x, 1 ); green = cdata( y, x, 2 ); blue = cdata( y, x, 3 ); if (red &gt;= redRange(1) &amp;&amp; red &lt;= redRange(2) &amp;&amp; green &gt;= greenRange(1) &amp;&amp; green &lt;= greenRange(2) &amp;&amp; blue &gt;= blueRange(1) &amp;&amp; blue &lt;= blueRange(2)) redToKeep( y, x ) = red; greenToKeep( y, x ) = green; blueToKeep( y, x ) = blue; else redToKeep( y, x ) = 999; greenToKeep( y, x ) = 999; blueToKeep( y, x ) = 999; end end end im = rgb2gray(cdata); [X, map] = gray2ind(im); im = ind2rgb(X, map); for x=1:imWidth for y=1:imHeight if (redToKeep( y, x ) &lt; 999) im( y, x, 1 ) = 240; end if (greenToKeep( y, x ) &lt; 999) im( y, x, 2 ) = greenToKeep( y, x ); end if (blueToKeep( y, x ) &lt; 999) im( y, x, 3 ) = blueToKeep( y, x ); end end end imshow(im); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload