color pixels in image
Show older comments
I want to color the pixels with color , like this example

5 Comments
Image Analyst
on 12 Dec 2021
Do you have a question? You did not ask one, so no one has answered. If so read this link first
then ask your question. Because I have no idea what you're starting with and what you want to do.
DGM
on 12 Dec 2021
Specifically, which pixels in what image need to be colored with what color?
The example is indeed an image with pixels of color, but without any supporting information, it can't clarify anything.
I hesitate to offer a mask-based demo, since the example appears to be opacity blended instead. Either that or it's been downscaled severely with a continuous interpolant.
linou landini
on 12 Dec 2021
Chunru
on 12 Dec 2021
Can you post your images?
Chunru
on 12 Dec 2021
How do you define the pixes in two images are same or different?
Answers (4)
Image Analyst
on 12 Dec 2021
Edited: Image Analyst
on 12 Dec 2021
What you ask is so simplistic as to be useless, like some trivial homework assignment. Untested code:
equalMask = logical(max(image1 == image2, [], 3));
outputEqual = imoverlay(image1, equalMask, 'g')
outputDifferent = imoverlay(image1, ~equalMask, 'r')
I think what you really want is to know what regions of the image have changed from "before" to "after", like the region has experienced an earthquake or fire or some other type of catastrophe. Then you know where to send emergency services, i.e. to the most heavily damaged areas.
This has been extensively studied and there are papers on it. I give you references below. Look over the papers and pick one and code it up. I do not have any of these algorithms already coded up and ready to give you. You can always ask the authors for source code.
- 23.2.2.1 Site Model Change Detection, Map Update
- 23.2.2.1.1 Building Change Detection
- 23.2.2.2 Change Detection for Damage Assessment
- 23.2.2.2.1 Flood Analysis, Flood Mapping, Flood Monitoring
- 23.2.2.2.2 Flood Damage Analysis, Impacts, Economic
- 23.2.2.2.3 Flood Risk Analysis, Flood Hazard Assessment, Susceptibility
- 23.2.2.2.4 Coastal, Tidal Flood Analysis, Storm Surge
- 23.2.2.3 Hydrological Analysis, Hydrological Modeling
- 23.2.2.3.1 River Discharge Measurement, River Flow
- 23.2.2.4 Landslide Analysis, Damage Assessment, Deformations
- 23.2.2.4.1 Landslide Analysis, SAR, InSAR, IFSAR, Radar
- 23.2.2.4.2 Landslide Susceptibility, Landslide Risk Analysi
- 23.2.2.4.3 Specific Site Landslide Analysis
- 23.2.2.4.4 Surface Deformation from SAR Applied to Volcanoes
- 23.2.2.4.5 Lava Flows, Eruptions Volcanoes, Thermal
- 23.2.2.4.6 Geothermal Area Analysis
- 23.2.2.4.7 Landslide Analysis, Earthquake Related, Seismic Analysis
- 23.2.2.4.8 Surface Deformation From SAR Applied to Earthquakes, Fault Monitoring
- 23.2.2.4.9 Avalanches, Snow Avalanche
- 23.2.2.4.10 Deformation of Bridges, Monitor Bridges, Other Structures
- 23.2.2.4.11 Disaster Management, Damage Mitigation, Risk Evaluation, Emergency Management
- 23.2.2.4.12 Evacuation Management, Disaster Management
- 23.2.2.4.13 Disaster Management, Seismic Vulnerability, Earthquakes
3 Comments
Image Analyst
on 12 Dec 2021
Edited: Image Analyst
on 12 Dec 2021
This is as far as I got but your images are different sizes. Why is that? Can you upload images that are the same size? And your images are different for every pixel so the whole output image will be red.
% Demo by Image Analyst, December, 2021.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
fprintf('Beginning to run %s.m ...\n', mfilename);
%-----------------------------------------------------------------------------------------------------------------------------------
% Read in image.
folder = [];
baseFileName = 'image1.png';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~isfile(fullFileName)
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
fullFileName = fullFileNameOnSearchPath;
end
image1 = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(image1)
% Display the image.
subplot(2, 2, 1);
imshow(image1, []);
axis('on', 'image');
caption = sprintf('Original Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Read in image.
folder = [];
baseFileName = 'image2.png';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~isfile(fullFileName)
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
fullFileName = fullFileNameOnSearchPath;
end
image2 = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(image2)
% Display the image.
subplot(2, 2, 2);
imshow(image2, []);
axis('on', 'image');
caption = sprintf('Original Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
hFig1 = gcf;
hFig1.Units = 'Normalized';
hFig1.WindowState = 'maximized';
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
hFig1.Name = 'Demo by Image Analyst';
%--------------------------------------------------------------------------------------------------------
% Segment (mask) the image.
equalMask = logical(max(equalMask, [], 3));
outputEqual = imoverlay(image1, equalMask, 'g');
outputDifferent = imoverlay(image1, ~equalMask, 'r');
% Display the mask image.
subplot(2, 2, 3);
imshow(equalMask, []);
axis('on', 'image');
caption = sprintf('Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Display the masked image.
subplot(2, 2, 4);
imshow(outputDifferent);
axis('on', 'image');
caption = sprintf('Masked Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
Image Analyst
on 12 Dec 2021
Not sure what you want but maybe it's this
outputEqual = imoverlay(imge1, image2, 'g');
or maybe it's this
equalMask = imge1 & image2;
outputImage = cat(3, uint8(255 * equalMask), uint8(255 * ~equalMask), zeros(size(imge1), 'uint8'))
Image Analyst
on 13 Dec 2021
@linou landini those images are different sizes. Please upload two images that have exactly the same dimensions as each other.
Voss
on 12 Dec 2021
Here's an approach that may work for you. (It uses the two black-and-white images you posted to your comment here. I don't know what data type your images are stored as, but when I downloaded each of those, I got a 3D matrix of uint8's, so the code assumes that. Since they are different sizes, the code cuts each one down so they are the same size.) This will make an image that has a green pixel where the input images are the same and a red pixel where they are not, as specified in your comment here.
image1 = imread('image1.png');
image2 = imread('image2.png');
image1(end,:,:) = []; % cut them down to size. you will need to change this for different
image2(:,end,:) = []; % pairs of images or make sure they are the same size beforehand
[m,n,p] = size(image1);
image_out = zeros([m n p],'uint8'); % make an output image of the same size and type
for i = 1:m
for j = 1:n
pixel_same = true;
for k = 1:p
% pixels are the same if all channels (i.e., R, G, B) are the
% same, so as soon as any channel is different, we know the
% pixel is different, so we stop checking (i.e., break)
if image1(i,j,k) ~= image2(i,j,k)
pixel_same = false;
break
end
end
if pixel_same
image_out(i,j,:) = [0 255 0]; % green pixel in output image
else
image_out(i,j,:) = [255 0 0]; % red pixel in output image
end
end
end
% do something with the result:
imwrite(image_out,'image_out.png');
imshow(image_out);
As @Benjamin noted, your example binarized images are mismatched in size and are actually RGB images. I'm going to guess that this is because they were saved from a figure.
As a consequence, the first two sections of this code are entirely a matter of fixing that. If you have two logical or floating-point images of the same size, you'll only need to do the last part.
% images as provided are RGB uint8; convert back to logical
A = rgb2gray(imread('https://www.mathworks.com/matlabcentral/answers/uploaded_files/832005/image.png'))>128;
B = rgb2gray(imread('https://www.mathworks.com/matlabcentral/answers/uploaded_files/832010/image.png'))>128;
% image sizes don't match; you'll have to fix that somehow.
A = A(1:end-1,:);
B = B(:,1:end-1);
% combine images, cast
C = im2double(cat(3,A,A & B,B));
% display it
imshow(C)
2 Comments
linou landini
on 13 Dec 2021
DGM
on 14 Dec 2021
Again, I doubt that the images you posted are the exact same images that you're working with. You'll need to do whatever is required to make sure that the two images are the same size. If they're already the same size, then they don't need to be cropped as in my example.
The example images are 88x89x3 and 87x90x3 respectively. If their sizes mismatch and are different than the example images, then they'll have to be padded/cropped as necessary.
Image Analyst
on 13 Dec 2021
@linou landini try this:
% Demo by Image Analyst, December, 2021.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
fprintf('Beginning to run %s.m ...\n', mfilename);
%-----------------------------------------------------------------------------------------------------------------------------------
% Read in image.
folder = [];
baseFileName = 'image1.png';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~isfile(fullFileName)
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
fullFileName = fullFileNameOnSearchPath;
end
image1 = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(image1)
if numberOfColorChannels == 3
% Image is color. We need gray scale. Convert to gray scale.
image1 = rgb2gray(image1);
end
% Display the image.
subplot(2, 2, 1);
imshow(image1, []);
axis('on', 'image');
caption = sprintf('Original Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Read in image.
folder = [];
baseFileName = 'image2.png';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~isfile(fullFileName)
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
fullFileName = fullFileNameOnSearchPath;
end
image2 = imread(fullFileName);
[rows2, columns2, numberOfColorChannels2] = size(image2)
if numberOfColorChannels2 == 3
% Image is color. We need gray scale. Convert to gray scale.
image2 = rgb2gray(image2);
end
% Make sizes match
if rows ~= rows2 || columns ~= columns2
message = sprintf('Images are of different sizes.\nI will resize image2 to match image1.')
uiwait(warndlg(message))
image2 = imresize(image2, [rows, columns]);
end
% Display the image.
subplot(2, 2, 2);
imshow(image2, []);
axis('on', 'image');
caption = sprintf('Original Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
hFig1 = gcf;
hFig1.Units = 'Normalized';
hFig1.WindowState = 'maximized';
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
hFig1.Name = 'Demo by Image Analyst';
%--------------------------------------------------------------------------------------------------------
% Segment (mask) the image.
equalMask = image1 == image2;
% Display the equal mask image.
subplot(2, 2, 3);
imshow(equalMask, []);
axis('on', 'image');
caption = sprintf('Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Now make an all red image.
redImage = 255 * ones(rows, columns, 'uint8');
zerosImage = zeros(rows, columns, 'uint8');
redImage = cat(3, redImage, zerosImage, zerosImage);
% Burn in green where they are equal.
outputEqual = imoverlay(redImage, equalMask, 'g');
% Display the color coded image.
subplot(2, 2, 4);
imshow(outputEqual, []);
axis('on', 'image');
caption = sprintf('Red = Not Equal. Green = Equal');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.

5 Comments
Image Analyst
on 13 Dec 2021
@linou landini, please explain why you want the code of @DGM even though you say his code does not work. His code gives black, white, and red pixels, not green and red. And it throws an error if the two images sizes don't match.
My code works and the image is green where the images have the same pixel value and are red where the pixel values are different -- EXACTLY what you said. So why is my code not acceptable? It runs without error and gives you what you asked for.
Image Analyst
on 13 Dec 2021
OK, I can do that for you easily. Do you want me to, or do you want to wait for DGM?
Also, why don't your images have the same size?
Image Analyst
on 14 Dec 2021
Edited: Image Analyst
on 14 Dec 2021
OK, when I checked back, you had deleted most of your comments so now I don't remember what to do. This is what I remember:
- Your images are supposed to be the same size but you uploaded images of different sizes. Please upload the actual images.
- Your images are supposed to be binary but you uploaded images that were gray scale with many more than 2 gray levels (black and white). There were lots of grays in there.. Please upload the actual binary images.
- You actually wanted 4 colors (black, white, red, and green) instead of 2 (red and green) like you originally said. But I'm not sure what color indicated what condition. Please give the 4 conditions.
- You said you wanted DGM's code even though mine ran without error and handled different sizes and his didn't produce red and green regions, and couldn't handle different sizes.
So this is what I'd do. Let me know if it's what you want or not. If not, for what reason?
% Demo by Image Analyst, December, 2021.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
fprintf('Beginning to run %s.m ...\n', mfilename);
%-----------------------------------------------------------------------------------------------------------------------------------
% Read in image.
folder = [];
baseFileName = 'image1.png';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~isfile(fullFileName)
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
fullFileName = fullFileNameOnSearchPath;
end
image1 = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(image1)
if numberOfColorChannels == 3
% Image is color. We need gray scale. Convert to gray scale.
image1 = rgb2gray(image1);
end
% Convert image to binary.
image1 = image1 > 6;
% Display the image.
subplot(2, 2, 1);
imshow(image1, []);
axis('on', 'image');
caption = sprintf('Original Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
%--------------------------------------------------------------------------------------------------------
% Read in image.
folder = [];
baseFileName = 'image2.png';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~isfile(fullFileName)
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
fullFileName = fullFileNameOnSearchPath;
end
image2 = imread(fullFileName);
[rows2, columns2, numberOfColorChannels2] = size(image2)
if numberOfColorChannels2 == 3
% Image is color. We need gray scale. Convert to gray scale.
image2 = rgb2gray(image2);
end
% Make sizes match
if rows ~= rows2 || columns ~= columns2
message = sprintf('Images are of different sizes.\nI will resize image2 to match image1.')
uiwait(warndlg(message))
image2 = imresize(image2, [rows, columns]);
end
% Convert image to binary.
image2 = image2 > 6;
% Display the image.
subplot(2, 2, 2);
imshow(image2, []);
axis('on', 'image');
caption = sprintf('Original Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
hFig1 = gcf;
hFig1.Units = 'Normalized';
hFig1.WindowState = 'maximized';
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
hFig1.Name = 'Demo by Image Analyst';
%--------------------------------------------------------------------------------------------------------
% Segment (mask) the image.
% Get mask where image1 is 0 and image2 is 0. % Color this as black.
mask00 = ~image1 & ~image2;
% Get mask where image1 is 1 and image2 is 1. % Color this as green.
mask11 = image1 & image2;
% Get mask where image1 is 1 and image2 is 0. % Color this as red.
mask10 = image1 > image2;
% Get mask where image1 is 0 and image2 is 1. % Color this as white.
mask01 = image1 < image2;
% Display the equal mask image.
subplot(2, 2, 3);
imshow(mask11, []);
axis('on', 'image');
caption = sprintf('Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
%--------------------------------------------------
% Now make images that are all 0 or 255.
all255Image = 255 * ones(rows, columns, 'uint8');
all0Image = zeros(rows, columns, 'uint8');
%--------------------------------------------------
% Now make the red channel image.
redChannel = cat(3, 255 * uint8(mask10 | mask01), all0Image, all0Image);
% Now make the green channel image.
greenChannel = cat(3, all0Image, 255 * uint8(mask11| mask01), all0Image);
% Now make the blue channel image. Blue is 255 where it's white only
blueChannel = cat(3, all0Image, all0Image, 255 * uint8(mask01));
% Combine all color channels.
outputImage = redChannel + greenChannel + blueChannel;
%--------------------------------------------------
% Display the color coded image.
subplot(2, 2, 4);
imshow(outputImage, []);
axis('on', 'image');
caption = sprintf('Red = Not Equal. Green = Equal');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.

Please state what needs to be changed.
linou landini
on 14 Dec 2021
Image Analyst
on 15 Dec 2021
OK, you're welcome. Sorry I/we couldn't help though -- I did everything I could.
Just to complete the question though, you can post your own code as a new Answer (so I can see how it's different than mine) and mark yours as the "Accepted" answer, and the other Answers you can click the "Vote" icon for it you want to award DGM and me "reputation points."
Categories
Find more on Convert Image Type in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!