Select area in picture and send information about r,g,b
Mostrar comentarios más antiguos
Hello,
I need to select an area on my picture and i want to have informations about r,g,b.
Someone can help me, please ?
Thanks!
Respuestas (2)
KSSV
el 11 de Sept. de 2020
If I is an image you canget:
R = I(:,:,1) ;
G = I(:,:,2) ;
B = I(:,:,3) ;
You can select your required area using imcrop, imfreehand.
2 comentarios
Abbass SAYEGH
el 11 de Sept. de 2020
KSSV
el 11 de Sept. de 2020
Yes..you can write the data into text file. Read about fprintf, saveas, writematrix.
Image Analyst
el 11 de Sept. de 2020
0 votos
What information do you need? For example, you can mask it and get the means and area. See attached demo.
You can get the histogram.
29 comentarios
Abbass SAYEGH
el 11 de Sept. de 2020
Image Analyst
el 11 de Sept. de 2020
Then combine the masking demo with the RGBXY to CSV demo.
Abbass SAYEGH
el 11 de Sept. de 2020
Image Analyst
el 11 de Sept. de 2020
Strange. Did you right click and say "Save link as..."?
Here are the demos.
First, here is RGBXY_to_CSV.m
% Take an RGB Image and write all the pixel info to a csv file in the form [R, G, B, X, Y].
% It will have as many rows as pixels in the image, and have those 5 columns.
% Initialization steps.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = 'C:\Program Files\MATLAB\R2018a\toolbox\matlab\imagesci'; % or 'C:\wherever';
if ~exist(startingFolder, 'dir')
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
% Read in the image.
rgbImage = imread(fullFileName);
% Display the image.
imshow(rgbImage);
% Put up statusbar to let you mouse around over it and see r, g, b, and (x, y)
impixelinfo();
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0.2, 0.2, 0.8, 0.8]);
drawnow; % Force immediate screen repaint.
% Get x and y for all pixels.
[rows, columns, numberOfColorChannels] = size(rgbImage)
if numberOfColorChannels == 1
% This is not an RGB image.
promptMessage = sprintf('This is not an RGB image\nDo you want to Continue processing as grayscale, \nMake RGB,\nor Quit processing?');
titleBarCaption = 'Continue?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Grayscale', 'Make RGB', 'Quit', 'Continue');
if contains(buttonText, 'Quit')
return;
elseif contains(buttonText, 'RGB')
% Convert to RGB.
rgbImage = cat(3, rgbImage, rgbImage, rgbImage);
[rows, columns, numberOfColorChannels] = size(rgbImage);
else
% Leave as grayscale.
end
end
[x, y] = meshgrid(1:columns, 1:rows);
% Extract the individual red, green, and blue color channels.
% Need to cast to double or else x and y will be clipped to 255 when we concatenate them.
if numberOfColorChannels == 1
% Leave as gray scale.
% Get array listing [r, g, b, x, y]. Using (:) will turn all the 2-D arrays into column vectors.
output = [rgbImage(:), x(:), y(:)];
else
redChannel = double(rgbImage(:, :, 1));
greenChannel = double(rgbImage(:, :, 2));
blueChannel = double(rgbImage(:, :, 3));
% Get array listing [r, g, b, x, y]. Using (:) will turn all the 2-D arrays into column vectors.
output = [redChannel(:), greenChannel(:), blueChannel(:), x(:), y(:)];
end
% Get the output filename - same as input file name but with .csv extension.
[folder, baseFileNameNoExtension, extension] = fileparts(fullFileName);
baseFileName = [baseFileNameNoExtension, '.csv'];
% folder = pwd; % Change to current folder.
outputFileName = fullfile(folder, baseFileName);
% Write output to CSV file.
message = sprintf('Please wait...\n Writing data to CSV file:\n %s', outputFileName);
fprintf('%s\n', message);
csvwrite(outputFileName, output);
% Let user know we're done.
fprintf('Done!\n Wrote data to CSV file:\n %s\n', outputFileName);
% Open up
promptMessage = sprintf('Done!\n\nWrote data to CSV file:\n%s\n\nDo you want me to it now?', outputFileName);
titleBarCaption = 'Open?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Yes - open it', 'No, do not open it', 'Yes - open it');
if contains(buttonText, 'No,')
return;
end
winopen(outputFileName);
and here is freehand_masking_demo.m
% Demo to have the user freehand draw an irregular shape over a gray scale image.
% Then it creates new images:
% (1) where the drawn region is all white inside the region and untouched outside the region,
% (2) where the drawn region is all black inside the region and untouched outside the region,
% (3) where the drawn region is untouched inside the region and all black outside the region.
% It also (4) calculates the mean intensity value and standard deviation of the image within that shape,
% (5) calculates the perimeter, centroid, and center of mass (weighted centroid), and
% (6) crops the drawn region to a new, smaller separate image.
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc; % Clear command window.
clear; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 16;
% Read in a standard MATLAB gray scale demo image.
folder = fileparts(which('cameraman.tif')); % Determine where demo folder is.
baseFileName = 'cameraman.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, '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
end
grayImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(grayImage);
imshow(grayImage, []);
axis on;
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
% Ask user to draw freehand mask.
message = sprintf('Left click and hold to begin drawing.\nSimply lift the mouse button to finish');
uiwait(msgbox(message));
hFH = imfreehand(); % Actual line of code to do the drawing.
% Create a binary image ("mask") from the ROI object.
binaryImage = hFH.createMask();
xy = hFH.getPosition;
% Now make it smaller so we can show more images.
subplot(2, 4, 1);
imshow(grayImage, []);
axis on;
drawnow;
title('Original gray scale image', 'FontSize', fontSize);
% Display the freehand mask.
subplot(2, 4, 2);
imshow(binaryImage);
axis on;
title('Binary mask of the region', 'FontSize', fontSize);
% Label the binary image and computer the centroid and center of mass.
labeledImage = bwlabel(binaryImage);
measurements = regionprops(binaryImage, grayImage, ...
'area', 'Centroid', 'WeightedCentroid', 'Perimeter');
area = measurements.Area
centroid = measurements.Centroid
centerOfMass = measurements.WeightedCentroid
perimeter = measurements.Perimeter
% Calculate the area, in pixels, that they drew.
numberOfPixels1 = sum(binaryImage(:))
% Another way to calculate it that takes fractional pixels into account.
numberOfPixels2 = bwarea(binaryImage)
% Get coordinates of the boundary of the freehand drawn region.
structBoundaries = bwboundaries(binaryImage);
xy=structBoundaries{1}; % Get n by 2 array of x,y coordinates.
x = xy(:, 2); % Columns.
y = xy(:, 1); % Rows.
subplot(2, 4, 1); % Plot over original image.
hold on; % Don't blow away the image.
plot(x, y, 'LineWidth', 2);
drawnow; % Force it to draw immediately.
% Burn region as white into image by setting it to 255 wherever the mask is true.
% burnedImage = grayImage;
% burnedImage(binaryImage) = 255;
% Mask the image using bsxfun() function to multiply the mask by each channel individually. Works for gray scale as well as RGB Color images.
burnedImage = bsxfun(@plus, grayImage, 255);
% Display the image with the mask "burned in."
subplot(2, 4, 3);
imshow(burnedImage);
axis on;
caption = sprintf('Masked white inside region');
title(caption, 'FontSize', fontSize);
% Burn region as black into image by setting it to 255 wherever the mask is true.
% Mask the image using bsxfun() function to multiply the mask by each channel individually. Works for gray scale as well as RGB Color images.
burnedImage = bsxfun(@times, grayImage, cast(~binaryImage, 'like', grayImage));
% Display the image with the mask "burned in."
subplot(2, 4, 4);
imshow(burnedImage);
axis on;
caption = sprintf('Masked black inside region');
title(caption, 'FontSize', fontSize);
% Mask the image white outside the mask, and display it.
% Will keep only the part of the image that's inside the mask, white outside mask.
whiteMaskedImage = grayImage;
whiteMaskedImage(~binaryImage) = 255;
subplot(2, 4, 5);
imshow(whiteMaskedImage);
axis on;
title('Masked white outside region', 'FontSize', fontSize);
% Mask the image outside the mask (make it black outside the white mask region), and display it.
% Will keep only the part of the image that's inside the mask, zero outside mask.
% Mask the image using bsxfun() function to multiply the mask by each channel individually. Works for gray scale as well as RGB Color images.
blackMaskedImage = bsxfun(@times, grayImage, cast(binaryImage, 'like', grayImage));
subplot(2, 4, 6);
imshow(blackMaskedImage);
axis on;
title('Masked black outside region', 'FontSize', fontSize);
% Calculate the mean
meanGL = mean(blackMaskedImage(binaryImage));
sdGL = std(double(blackMaskedImage(binaryImage)));
% Put up crosses at the centroid and center of mass.
hold on;
plot(centroid(1), centroid(2), 'r+', 'MarkerSize', 30, 'LineWidth', 2);
plot(centerOfMass(1), centerOfMass(2), 'g+', 'MarkerSize', 20, 'LineWidth', 2);
% Now crop the image.
leftColumn = min(x);
rightColumn = max(x);
topLine = min(y);
bottomLine = max(y);
width = rightColumn - leftColumn + 1;
height = bottomLine - topLine + 1;
croppedImage = imcrop(blackMaskedImage, [leftColumn, topLine, width, height]);
% Display cropped image.
subplot(2, 4, 7:8);
imshow(croppedImage);
axis on;
title('Cropped image', 'FontSize', fontSize);
% Put up crosses at the centroid and center of mass.
hold on;
plot(centroid(1)-leftColumn, centroid(2)-topLine, 'r+', 'MarkerSize', 30, 'LineWidth', 2);
% text(centroid(1)-leftColumn + 20, centroid(2)-topLine-20, 'Centroid', 'Color', 'r');
plot(centerOfMass(1)-leftColumn, centerOfMass(2)-topLine, 'g+', 'MarkerSize', 20, 'LineWidth', 2);
% text(centroid(1)-leftColumn + 20, centroid(2)-topLine+20, 'Weighted Centroid', 'Color', 'g');
% Report results.
message = sprintf('Mean value within drawn area = %.3f\nStandard deviation within drawn area = %.3f\nNumber of pixels = %d\nArea in pixels = %.2f\nperimeter = %.2f\nCentroid at (x,y) = (%.1f, %.1f)\nCenter of Mass at (x,y) = (%.1f, %.1f)\nRed crosshairs at centroid.\nGreen crosshairs at center of mass.', ...
meanGL, sdGL, numberOfPixels1, numberOfPixels2, perimeter, ...
centroid(1), centroid(2), centerOfMass(1), centerOfMass(2));
msgbox(message);
Abbass SAYEGH
el 14 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Image Analyst
el 14 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
We still need to figure out why you were not able to save the files directly from your browser and I had to paste them into the message body. Can you answer my questions about it above?
For your "Answer" here that you posted (which is actually a new question), see the FAQ: https://matlab.fandom.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F
Abbass SAYEGH
el 14 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Abbass SAYEGH
el 15 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Walter Roberson
el 15 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
dinfo = dir('*.png');
filenames = {dinfo.name};
nfiles = length(filenames);
for K = 1 : nfiles
thisfile = filenames{K};
thisimage = imread(thisfile);
revimage = 255-thisimage;
imshow(revimage)
title(thisfile);
pause(1);
end
Abbass SAYEGH
el 16 de Sept. de 2020
Image Analyst
el 16 de Sept. de 2020
Abbass, add a call to imwrite():
folder = pwd; % or 'C:/wherever you want'
fullFileName = fullfile(folder, 'Cropped Image.png'); % Whatever you want to call it...
imwrite(croppedImage, fullFileName);
Abbass SAYEGH
el 16 de Sept. de 2020
Abbass SAYEGH
el 18 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Image Analyst
el 18 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Sure. Follow these steps:
- Create mask with drawfreehand()
- Threshold image binaryImage = grayImage < someThresholdValue
- Detect edges with either (A) edgeImage = edge(grayImage) if you want edges on the gray scale image, or (B) with boundaries = bwboundaries(binaryImage) if you want edges on the binaryImage and then burn the edges into the binaryImage.
- Erase edges with edgeImage(mask) = false.
Abbass SAYEGH
el 21 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Abbass SAYEGH
el 21 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Image Analyst
el 21 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Don't you think it's better for you to understand if you work through it yourself?
Image Analyst
el 21 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Abbass SAYEGH
el 22 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Walter Roberson
el 22 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Your MATLAB is too old to have isfolder() . Use isdir() instead.
Abbass SAYEGH
el 23 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Abbass SAYEGH
el 23 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Image Analyst
el 23 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Sure but we don't know exactly what you want. We gave you code for tracing out some area on the image and getting all the values and the mean value in the drawn area. We also gave you code for processing a sequence of images. But we don't really know what "I need lines of code able to do automatic command. The command is : when i select an area on the image, i want to open all the files with the same extension for the process ? " means. Can you give us a step-by-step process for what you want to do, like:
- Interactively browse for an image and Get the filename.
- Read it in the selected image.
- Display error if user picks a gray scale image instead of a color image.
- Display the color image.
- User draws some irregular region on it.
- Get individual color channels.
- Get mean gray level for each of the color channels inside the drawn region.
- Save these values and filename.
- Enter a loop where we process all (other) files that have the same extension as the first image that was chosen
- Inside the loop, repeat steps 2 through 8
etc.
Unless you do that your request is so vague and imprecise that if we do something (like we already have), you'll just say it's not what you want. So please give a step-by-step recipe of what you want to do.
Abbass SAYEGH
el 23 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Image Analyst
el 23 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
You forgot to attach a sample Excel workbook, probably because you ignored the posting guidelines when you posted. Here, you can read them here: https://www.mathworks.com/matlabcentral/answers/6200-tutorial-how-to-ask-a-question-on-answers-and-get-a-fast-answer
What form is the image in in Excel? A 2-D matrix? A N-by-3 list of (x,y,graylevel)?
Abbass SAYEGH
el 24 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Abbass SAYEGH
el 24 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
Walter Roberson
el 24 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
my Image is a N-by-3 list of (x,y,graylevel)
Is the file "complete", in the sense that every possible x and y combination appears? Or are some not listed -- for example are the locations that are zero not listed ? Are the x and y regularly spaced? Are they positive integers that start from 1 ? Should it be considered scattered information, samples of the actual surface with the other locations on the grid to be interpolated based upon the points that are present?
- Browse my folder and find all my xlsx files
We gave you code for that.
- Open these xlsx files like image
readtable() or readmatrix() or xlsread(). But then you have to arrange the list of data into an image, and to do that we need to know the answers to the questions I asked above.
- When i opened them, i want to select an area
A fixed area? If so then imcrop() or index the image. A variable area? If so then imfreehand(). Image Analyst showed you how to do that in https://www.mathworks.com/matlabcentral/answers/592150-select-area-in-picture-and-send-information-about-r-g-b#comment_1005523 and also attached a demonstration program in one of his other answers. Or use https://www.mathworks.com/help/images/ref/roipoly.html roipoly()
- when i select this area, i want to put the values of pixels (r,g,b) on new xlsx file
If you used imfreehand() then use createmask https://www.mathworks.com/help/images/ref/imroi.createmask.html to get a binary selection matrix. If you used roipoly() then it returns a binary selection matrix directly. If you somehow have a list of coordinates that bound the selection region then poly2mask() https://www.mathworks.com/help/images/ref/poly2mask.html
Now use find() with two outputs on the mask to get a list of rows and column numbers where the mask is set. The row numbers are your y coordinates. The column numbers are your x coordinates. Do not make the mistake of using the rows as your x coordinates!!
Now use the logical mask to index your grayscale image. The result will be a vector of image values, in the same order that find() returned its values.
Put the x, y, and values together into an N x 3 array.
Now writematrix() or writetable() or xlswrite() the data out.
- Calculate the mean of these values and put it on new xlsx file
mean() the vector of values referred to above. writematrix() or writetable() or writecell() or xlswrite() the data out.
- Do the same process for the rest of the files
We gave you the code for that.
If you are wanting to put the mean values all in the same xlsx file, then I recommend that you do not write the mean values into a file inside the loop. I recommend that you instead record the values in arrays, and then do a single write at the end. Keeping track of the current position inside an xlsx file to be able to write at the "end" of it is a nuisance best avoided (and writing only once would be considerably more efficient.)
Can I have help for my question ? or i cant ?
Ummm.. you know we are volunteers, and that we have other things going on in our lives, like answering other questions, or sleeping, or our jobs, or relaxing because we are worn out from answering lots of questions? The majority of the active volunteers are in North America, and your post about the file format and your prodding for additional assistance were during the middle of the night in North America.
Image Analyst
el 25 de Sept. de 2020
Movida: DGM
el 23 de Feb. de 2023
I'll ask you the same question you asked us "Can I have help for my question ? or i cant ?"
I specifically and directly asked you to attach one of your Excel workbooks, and instead of simply attaching one, you said "It's like other excel file." Come on - make it easy for us to help you not hard! You're basically saying to me "I don't want to spend a few seconds to attach my workbook but I expect you to write code to read in some image, then write out the x,y,grayLevel values, in order to create some sample image." Why are you wanting me to go through all that? No, sorry but I won't. If you won't spend the time to attach it and make it easy for us to help you, then I won't spend my time either.
We can't just write the whole thing for you, but there are people who would gladly do so. They are here. Please contact them and they'd be happy to do it all for you and deliver a turnkey system, or train you throughout the process while you do it.
We non-Mathworks volunteers generally provide some help if we can do it within a few minutes (which we've already spent). If it would be more than that, we can provide code snippets or refer you to the FAQ or other places (File Exchange) for code, which we've done. Try to make an effort with the code snippets you now know about and make a stab at creating your program. I mean the code in the FAQ is basically half the program you'd need. Here, I adapted the FAQ code a little for you to give you a start.
% Specify the folder where the files live.
myFolder = 'C:\Users\yourUserName\Documents\My Pictures';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.xls*'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
imageArray = xlsread(fullFileName);
% Find size in the last row. Form is [x, y, grayLevel]
columns = imageArray(end, 1); % Max X
rows = imageArray(end, 2); % Max Y
grayLevels = imageArray(:, 3);
% Reshape into rectangle:
imageArray = reshape(imageArray, rows, columns);
imshow(imageArray); % Display image.
drawnow; % Force display to update immediately.
% Call roipoly() or drawfreehand() to get a mask
% I'm sure you can figure this out.
% Get row, column for pixels in the mask
[r, c] = find(mask);
% Make new array
output = zeros(length(r), 3);
for kk = 1 : length(r)
output(kk, 1) = c(kk);
output(kk, 2) = r(kk);
output(kk, 3) = imageArray(r(kk), c(kk), kk);
end
% Create Excel filename by appending _output
excelFullFileName = strrep(lower(fullFileName), '.xls', '_output.xls');
writematrix(output, excelFullFileName);
end
Why not try it? Good luck.
Categorías
Más información sobre Programming en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!