Application of polyfit() on certain pixels.

20 visualizaciones (últimos 30 días)
Ron Herman
Ron Herman el 25 de Jul. de 2020
Comentada: Ron Herman el 26 de Jul. de 2020
There are two types of co-ordinate system
a)Pixel cordinate sytem
b)Spatial cordinate system
I have an image and I identified the pixel position of certain desired edge. After finding the pixel coordinates of the edge I want to use polyfit() on those pixels so that I can draw a curve along the edge that would trace the edge.
But polyfit () seems to work on Spatial cordinate system so I am unable to get the edge traced. How would I approach this problem??
Any suggestions will be helpful?
  3 comentarios
dpb
dpb el 25 de Jul. de 2020
polyfit() simply fits the given X,Y data.
W/o data and code to see what you actually did on what it's not possible to do more than speculate.
It's probably more likely to be able to get a satisfactory fit with spline rather than a polynomial, but again would need the data to be able to know for sure...
KSSV
KSSV el 25 de Jul. de 2020
Editada: KSSV el 25 de Jul. de 2020
You can get the locations of white pixel and use boundary or convhull and from this select the lower side...won't this help? I have seen you have asked this question almost four times today.

Iniciar sesión para comentar.

Respuesta aceptada

Image Analyst
Image Analyst el 25 de Jul. de 2020
Ron:
Your problem came before that image. It came when you thought you should do an edge detection. Like most beginners, you thought that because you can see edges in the image, that edge detection must be the first step. It is usually not. What you should have done was a color segmentation and then find the bottom's edge and then fit a curve to it and get the distance. Here is corrected code:
% Demo to find distances. By Image Analyst, May 5, 2020.
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 = pwd;
baseFileName = 'warped_image2.jpeg';
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
rgbImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(rgbImage);
% Display the test image full size.
subplot(2, 1, 1);
imshow(rgbImage, []);
axis('on', 'image');
caption = sprintf('Reference 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';
[mask, maskedRGBImage] = createMask(rgbImage);
% Fill holes
mask = imfill(mask, 'holes');
% Smooth the mask by filtering
windowSize = 7; % An odd number.
f = ones(windowSize)/windowSize^2;
mask = imfilter(mask, f);
% Display the distance image.
subplot(2, 1, 2);
imshow(mask, []);
axis('on', 'image');
caption = sprintf('Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
colorbar;
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Scan getting the bottom row.
bottomRows = zeros(1, columns);
for col = 1 : columns
thisCol = mask(:, col);
r = find(thisCol, 1, 'last');
if ~isempty(r)
bottomRows(col) = r;
end
end
lastColumn = find(bottomRows > 0, 1, 'last')
bottomLine = max(bottomRows)
hold on;
yline(bottomLine, 'Color', 'g', 'LineWidth', 2)
plot(lastColumn, bottomRows(lastColumn), 'mo', 'MarkerSize', 15, 'LineWidth', 2)
text(lastColumn, bottomRows(lastColumn), 'Right most point ', 'HorizontalAlignment', 'right', 'Color', 'm', 'FontSize', 15, 'FontWeight', 'bold');
distance = bottomLine - bottomRows(lastColumn)
% Fitting
goodIndexes = bottomRows > 0;
c = 1:columns;
x = c(goodIndexes);
y = bottomRows(goodIndexes);
coefficients = polyfit(x, y, 2);
xFit = c;
yFit = polyval(coefficients, xFit);
plot(xFit, yFit, 'r-', 'LineWidth', 2)
yLast = yFit(lastColumn);
plot(lastColumn, yLast, 'r+', 'MarkerSize', 50, 'LineWidth', 2)
text(lastColumn, yLast, 'Fitted y at Right most point ', 'HorizontalAlignment', 'right', 'Color', 'r', 'FontSize', 15, 'FontWeight', 'bold');
fittedDistance = bottomLine - yLast
caption = sprintf('Magenta-to-green distance = %.1f. Red-to-green distance = %.1f', distance, fittedDistance);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
% Will be different than other distance because the other one was actual
% and this one is from the regression.
fprintf('Done running %s.m ...\n', mfilename);
function [BW,maskedRGBImage] = createMask(RGB)
%createMask Threshold RGB image using auto-generated code from colorThresholder app.
% [BW,MASKEDRGBIMAGE] = createMask(RGB) thresholds image RGB using
% auto-generated code from the colorThresholder app. The colorspace and
% range for each channel of the colorspace were set within the app. The
% segmentation mask is returned in BW, and a composite of the mask and
% original RGB images is returned in maskedRGBImage.
% Auto-generated by colorThresholder app on 25-Jul-2020
%------------------------------------------------------
% Convert RGB image to chosen color space
I = rgb2lab(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 5.530;
channel1Max = 99.753;
% Define thresholds for channel 2 based on histogram settings
channel2Min = -14.832;
channel2Max = 45.687;
% Define thresholds for channel 3 based on histogram settings
channel3Min = -73.763;
channel3Max = -28.389;
% Create mask based on chosen histogram thresholds
sliderBW = (I(:,:,1) >= channel1Min ) & (I(:,:,1) <= channel1Max) & ...
(I(:,:,2) >= channel2Min ) & (I(:,:,2) <= channel2Max) & ...
(I(:,:,3) >= channel3Min ) & (I(:,:,3) <= channel3Max);
BW = sliderBW;
% Initialize output masked image based on input image.
maskedRGBImage = RGB;
% Set background pixels where BW is false to zero.
maskedRGBImage(repmat(~BW,[1 1 3])) = 0;
end
If you can, you should use a black background, not white. And you should use crossed polarizers to knock out the specular reflections (white glints). Finally you should adjust your camera angle to have the optic axis be normal to the bottom plane of that blue slab. Ideally you should be using a "telecentric" lens, not a regular lens.
Regarding what you did wrong with the red curve and polyfit(), it looks likely you swapped x and y. Remember, images are not indexed like mask(x, y). They are indexed mask(row, column) which is mask(y, x). This is another extremely common beginner mistake. It looks like you may have swapped x and y in polyfit().
  1 comentario
Ron Herman
Ron Herman el 26 de Jul. de 2020
Thank you Sir, I get to learn a lot from these feedback. I posted this specifically for polyfit() for my learning.
It has been a plesant learning experience.
Thank you

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Deep Learning for Image Processing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by