如何将RGB图像转换为灰度,但保留一种颜色?
filename = 'roses.jpg';[cdata,map] = imread( filename );% convert to RGB if it is indexed imageif ~isempty( map ) cdata = idx2rgb( cdata, map ); end%imtool('roses.jpg');imWidth = 685;imHeight = 428;% RGB ranges of a color we want to keepredRange = [140 255];greenRange = [0 40];blueRange = [0 40];% RGB values we don't want to convert to grayscaleredToKeep = 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 >= redRange(1) && red <= redRange(2) && green >= greenRange(1) && green <= greenRange(2) && blue >= blueRange(1) & & blue <= 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 ) < 999) im( y, x, 1 ) = 240; end if (greenToKeep( y, x ) < 999) im( y, x, 2 ) = greenToKeep( y, x ); end if (blueToKeep( y, x ) < 999) im( y, x, 3 ) = blueToKeep( y, x ); end end end imshow(im);
慕仙森
小怪兽爱吃肉
开满天机