How to sum (row,col) until the first red pixel

조회 수: 1 (최근 30일)
Stelios Fanourakis
Stelios Fanourakis 2019년 1월 13일
댓글: Image Analyst 2019년 1월 21일
Hi
Any ways to use the sum() command in an image, in a way to scan the whole image until it finds the first red pixel where it should stop and proceed to the nect column starting the scanning again.
Any ideas? Thank you.
  댓글 수: 2
Rik
Rik 2019년 1월 13일
Your definitions/data structure are not entirely clear. What do you mean with red pixel? Do you have an indexed image or is it an RGB?
Is every row guaranteed to have a red pixel? If not, what should happen in that case?
Stelios Fanourakis
Stelios Fanourakis 2019년 1월 13일
@Rik
I attach the Image.
The user needs to define the start and end point on the image (row, columns). The sum() command will start scanning vertically, until it finds the first red pixel on the contour you see in the image. Then it will stop and proceed to the next column.

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2019년 1월 14일
I believe I answered the image in your duplicate question
Here it is again:
I think this does what you want.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
%===============================================================================
% Get the name of the image the user wants to use.
baseFileName = 'A2.jpg';
folder = pwd;
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% 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
end
%=======================================================================================
% Read in demo image.
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display image.
subplot(2, 3, 1);
imshow(rgbImage, []);
impixelinfo;
axis on;
caption = sprintf('Original Color Image\n%s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0.05 1 0.95]);
% 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.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
%===================================================================================
% FIND THE RED MASK
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% get a mask for the red line.
mask = redChannel > greenChannel;
% Display the image.
subplot(2, 3, 2);
imshow(mask);
caption = sprintf('Color Segmentation Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
drawnow;
% fill holes.
mask = imfill(mask, 'holes');
% Take the largest blob only.
mask = bwareafilt(mask, 1);
% Shrink two layers of pixels to come inside the red lines.
mask = imerode(mask, true(5));
% Display the image.
subplot(2, 3, 3);
imshow(mask);
title('Final Mask', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
% Get a masked image.
% Mask the image using bsxfun() function to multiply the mask by each channel individually.
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage));
% Display the image.
subplot(2, 3, 4);
imshow(maskedRgbImage);
title('Masked RGB Image', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
% A = contour(mask,'b');
set(gca,'ydir','reverse')
conversion = 0.9183; % in mm/pixel
addMM = @(x) sprintf('%.3fmm', x * conversion);
xticklabels(cellfun(addMM, num2cell(xticks'), 'UniformOutput', false));
yticklabels(cellfun(addMM, num2cell(yticks'), 'UniformOutput', false));
%===================================================================================
% FIND THE HEIGHT OF THE MASK, AND SUM OF GRAY LEVELS FROM ROW 1 TO RED ROW.
topRow = 1; % Whatever you want.
grayLevelSum = zeros(1, columns); % Initialize sums for every column.
heights = zeros(1, columns); % Initialize heights for every column.
% Find the left and right column of the mask so we know where to sum over.
[rows, columns] = find(mask);
col1 = min(columns);
col2 = max(columns);
for col = col1 : col2
row2 = find(mask(:, col), 1, 'last'); % Get bottom row of mask
if ~isempty(row2)
% Get the sum in the GREEN channel, from row1 to row2.
grayLevelSum(col) = sum(greenChannel(topRow:row2, col));
% Compute the height of the mask at every column.
heights(col) = sum(mask(topRow:row2, col));
end
end
% Plot integrated gray level.
subplot(2, 3, 5);
plot(grayLevelSum, 'b-', 'LineWidth', 2);
xlabel('Column', 'FontSize', 20);
ylabel('Sum of gray levels in column', 'FontSize', 20);
title('Sum of gray levels in column', 'FontSize', 20);
grid on;
% Plot heights
subplot(2, 3, 6);
plot(heights, 'b-', 'LineWidth', 2);
xlabel('Column', 'FontSize', 20);
ylabel('Height of mask in column', 'FontSize', 20);
title('Mask Height vs. Column', 'FontSize', 20);
grid on;
% Tell user the answer.
message = sprintf('Done!');
uiwait(helpdlg(message));
  댓글 수: 17
Stelios Fanourakis
Stelios Fanourakis 2019년 1월 21일
Yes and thanks a lot. One more question is how do I make it exclude certain excel rows when storing data.
For example, I want to store the data from B2 (second row) as I want the first row as a headline. How do I do this programmatically?
I use that code. I want to adjust the range
data = [heights(:)];
sheet = 1;
range = 'B';
xlswrite('YourFile.xls', data, sheet, range)
Image Analyst
Image Analyst 2019년 1월 21일
Make a cell array for your header, then call xlswrite once for the header and once for the numerical data
header = cell(1, 2); % Row vector
header{1} = 'Column 1';
header{2} = 'Column 2';
sheet = 1;
xlswrite('YourFile.xls', header, sheet, 'A1')
xlswrite('YourFile.xls', data, sheet, 'A2') % Write one row below the header.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Red에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by