I want to detect the slopes of all the lines in a pattern. Is it possible? I am new to MATLAB. Can anyone help?

2 views (last 30 days)
  4 Comments
Muhammed Shebeeb Cherum Kuzhi
Edited: Rik on 22 Sep 2021
I got this code for getting slope of a single line. But not working for mine.
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;
fontSize = 14;
rgbImage = imread('abc.jpg');
% Display the image.
subplot(1, 2, 1);
imshow(rgbImage, []);
title('Original RGB JPEG Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% 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')
grayImage = rgb2gray(rgbImage);
binaryImage = grayImage ~= 255;
% Display the image.
subplot(1, 2, 2);
imshow(binaryImage, []);
title('Binary Image showing horrible JPEG artifacts and fitted line', 'FontSize', fontSize, 'Interpreter', 'None');
% Find locations of pixels
[y, x] = find(binaryImage);
% Do the fit to a line:
coefficients = polyfit(x, y, 1)
slope = coefficients(1);
intercept = coefficients(2);
message = sprintf('The slope of the line is %f.\nThe intercept is %f',...
slope, intercept);
helpdlg(message);
% Make a fitted line
x1 = min(x)
x2 = max(x)
xFit = x1:x2;
yFit = polyval(coefficients, xFit);
hold on;
plot(xFit, yFit, 'r-', 'LineWidth', 2);
axis on;
Rik
Rik on 22 Sep 2021
You will first have to detect each line, so you will have to find a way to make only the pixels of a single line be 1. Then you can use the method Image Analyst suggested (based on the header this looks like one of his demos).

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 22 Sep 2021
That code was meant for finding the angle of just one blob. If you have multiple blobs, use regionprops() and ask for the Orientation:
% Demo by Image Analyst.
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. This is a horrible image. NEVER use JPG format for image analysis. Use PNG, TIFF, or BMP instead.
folder = [];
baseFileName = 'blue stripes.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.
subplot(2, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
caption = sprintf('Original RGB Image : "%s"\n%d rows by %d columns', baseFileName, rows, columns);
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';
[binaryImage,maskedRGBImage] = createMask(rgbImage);
% Get rid of blobs touching the border.
subplot(2, 2, 2);
imshow(binaryImage);
% Some stripes are broken. Try to connect broken stripes.
binaryImage = imdilate(binaryImage, true(1, 10));
% Get convex hull and fill holes
binaryImage = bwconvhull(binaryImage, 'objects');
imshow(binaryImage);
% Get the area of the blobs
props = regionprops(binaryImage, 'Area');
allAreas = sort([props.Area])
% Now we know that blobs with area less than 1000 pixels are not full stripes. Delete them
binaryImage = bwareafilt(binaryImage, [1000, inf]);
% Now small noise blobs are gone.
% Label each blob with 8-connectivity, so we can make measurements of it
[labeledImage, numberOfBlobs] = bwlabel(binaryImage, 8);
% Apply a variety of pseudo-colors to the regions.
coloredLabelsImage = label2rgb (labeledImage, 'hsv', 'k', 'shuffle');
% Display the pseudo-colored image.
imshow(coloredLabelsImage);
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
axis('on', 'image');
title('Final Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
% Get the centroids.
% Get all the blob properties. Can only pass in originalImage in version R2008a and later.
props = regionprops(labeledImage, 'Centroid', 'Area', 'Orientation');
numberOfBlobs = size(props, 1);
allAreas = [props.Area]
allAngles = [props.Orientation]
xy = vertcat(props.Centroid)
% Plot cross hairs are every centroid.
hold on;
for k = 1 : numberOfBlobs
plot(xy(k, 1), xy(k, 2), 'w+', 'LineWidth', 2);
end
% Compute the averate orientation.
aveAngle = mean(allAngles);
numStripes = length(allAngles);
% Show angles
subplot(2, 2, 3);
bar(allAngles, 1);
caption = sprintf('%d Individual Bar Angles. The average angle is %.3f degrees', numStripes, aveAngle);
title(caption, 'FontSize', fontSize);
xlabel('Bar Number', 'FontSize', fontSize);
ylabel('Angle in Degrees', 'FontSize', fontSize);
grid on;
% Show average angle as a red line.
yline(aveAngle, 'Color', 'r', 'LineWidth', 2);
% Show angle distribution
subplot(2, 2, 4);
histogram(allAngles);
xlabel('Angle in Degrees', 'FontSize', fontSize);
ylabel('Count', 'FontSize', fontSize);
grid on;
caption = sprintf('Histogram of %d Angles. The average angle is %.3f degrees', numStripes, aveAngle);
title(caption, 'FontSize', fontSize);
% Show average angle as a red line.
xline(aveAngle, 'Color', 'r', 'LineWidth', 2);
message = sprintf('Done!\nThe average angle is %.3f degrees', aveAngle)
msgbox(message);
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 22-Sep-2021
%------------------------------------------------------
% Convert RGB image to chosen color space
I = rgb2hsv(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.425;
channel1Max = 0.567;
% Define thresholds for channel 2 based on histogram settings
channel2Min = 0.308;
channel2Max = 1.000;
% Define thresholds for channel 3 based on histogram settings
channel3Min = 0.000;
channel3Max = 0.785;
% 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

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!