Masking out Images different pixel intensity with different color values

7 次查看(过去 30 天)
I have a large gray image with size (4329x5448) . I want to color the the pixels depending upon different range of values. My code is:
RGBImage=cat(3,grayImage,grayImage,grayImage);
for ii=1:size(grayImage,1)
for jj=1:size(grayImage,2)
% get pixel value
pixel=RGBImage(ii,jj,1);
if(~isnan(pixel))
% check pixel value and assign new value
if pixel>0 && pixel<=0.2
new_pixel=[0; 0; 1];
elseif pixel>0.2 && pixel<=0.4
new_pixel=[0; 1; 0];
elseif pixel>0.4 && pixel<=0.6
new_pixel=[1; 1; 0];
elseif pixel>0.6 && pixel<=0.8
new_pixel=[1; 0; 0];
else
new_pixel = [0; 0; 0];
end
% save new pixel value in thresholded image
RGBthreshold(ii,jj,:)=new_pixel;
else
RGBthreshold(ii,jj,:)=[NaN;NaN;NaN];
end
end
end
But the code is slow. It is taking long time. Any idea of making it fast.

回答(1 个)

DGM
DGM 2021-3-23
编辑:DGM 2021-3-23
Don't do it pixel by pixel. That'll take forever. At most, do it channel by channel or frame by frame. There are a lot of ways to do something like this. I'm going to choose to do it in a fairly basic and direct way.
% this is just my test image; not included
inpict=imread('sources/table.jpg');
graypict=im2double(rgb2gray(inpict));
% we want how many gray levels
graylevels=5;
% what's our colormap?
cmap=[0 0 1; 0 1 0; 1 1 0; 1 0 0; 0 0 0];
% number of graylevels should correspond to the length of cmap
% get map of nans
nanmap=isnan(graypict);
% allocate output array
outpict=zeros([size(graypict,1) size(graypict,2) 3]);
% permute the colormap
cmap=permute(cmap,[1 3 2]);
for gl=1:graylevels
% make a logical mask for this range of gray values
mask=(graypict>=((gl-1)/graylevels)) & (graypict<=(gl/graylevels));
% step through the image channels and assign color values to the mask region
% this can be done with bsxfun, but let's not get confusing.
for c=1:3
thischannel=outpict(:,:,c);
thischannel(mask)=cmap(gl,1,c);
outpict(:,:,c)=thischannel;
end
end
% inherit all those wonderful NaNs
for c=1:3
thischannel=outpict(:,:,c);
thischannel(nanmap)=NaN;
outpict(:,:,c)=thischannel;
end
imshow(outpict)
It's not going to win any awards for efficiency or elegance, but it's readable. It takes about 9 seconds to process a 4500x5500 image on a ~10 year old computer.
The per-channel loops could be avoided with bsxfun and/or array replication. The MIMT (on the file exchange) has a multilevel mask generation tool (mlmask()) and a tool for replacing image regions with a color tuple based on a single-channel mask (replacepixels()). There are probably other ways.

类别

Help CenterFile Exchange 中查找有关 Modify Image Colors 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by