MATLAB: Removing “straight” lines from image

image analysisimage processingImage Processing Toolbox

Hi all! I'm a material scientist by trade and I would appreciate some help with some image processing. The images are like the one below and contain (a) some fairly "straight" lines, which correspond to the rectangular-shaped microstructure and (b) some more "twisted"/"random" lines, which correspond to defects in this material. I would like to process the images to remove all (or most) of the fairly straight lines, but still keep the others. I searched for previous similar questions but most dealt with perfectly straight lines, whereas here this is not exactly the case. I would be very grateful for some suggestions. Many thanks in advance!

Best Answer

Well I worked on it for about 20 minutes and this is what I got. Not bad but you could probably improve it with some tweaking of parameters.
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 = 20;
%===============================================================================
% Read in gray scale demo image.
folder = pwd; % Determine where demo folder is (works with all versions).
baseFileName = 'test.png';
% Get the full filename, with path prepended.
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);
% Get the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
if numberOfColorChannels > 1
% It's not really gray scale like we expected - it's color.
% Use weighted sum of ALL channels to create a gray scale image.
% grayImage = rgb2gray(rgbImage);
% ALTERNATE METHOD: Convert it to gray scale by taking only the green channel,
% which in a typical snapshot will be the least noisy channel.
grayImage = rgbImage(:, :, 1); % Take red channel.
else
grayImage = rgbImage; % It's already gray scale.
end
% Now it's gray scale with range of 0 to 255.
% Display the image.


subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
%------------------------------------------------------------------------------
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
% 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;
% Binarize the image
binaryImage = grayImage < 128;
% Display the binary image.
subplot(2, 2, 2);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
drawnow;
% Find branchpoints
bpImage = bwmorph(binaryImage, 'branchpoints');
% Enlarge the branchpoints to really separate the lines.
bpImage2 = imdilate(bpImage, ones(3));
% Erase the branchpoints from the original binary image to leave
% just the single, unbranched stick-like lines.
linesImage = binaryImage & ~bpImage2;
% Now throw out blobs less than 15 pixels.
linesImage = bwareaopen(linesImage, 15);
% Colorize them.
% Label each blob with 8-connectivity, so we can make measurements of it
[labeledImage, numberOfBlobs] = bwlabel(linesImage, 8);
% Apply a variety of pseudo-colors to the regions.
coloredLabelsImage = label2rgb (labeledImage, 'hsv', 'k', 'shuffle');
% Display the pseudo-colored image.
subplot(2, 2, 3);
imshow(coloredLabelsImage);
title('Lines Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
drawnow;
% Now we need to find the pixels in each line and fit it to a line
% and determine if the line is straight or not.
% If the line is not straight, we keep it.
% If it's straight, it's boundary "grid" line and we'll want to fill those in.
props = regionprops(linesImage, 'PixelList', 'Solidity');
allSolidities = [props.Solidity]
subplot(2, 2, 4);
histogram(allSolidities);
grid on;
figure;
linesImage = bwpropfilt(linesImage, 'Solidity', [0.35, inf]);
% Put the branchpoints back in.
linesImage = linesImage | bpImage;
% If the branchpoints touched a line that is no longer there, remove them.
linesImage = bwareaopen(linesImage, 15);
% Display the image.
imshow(linesImage);
title('Lines Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
drawnow;
% Use this image to fill in the original binary image
binaryImage2 =~ binaryImage; % Initialize.
binaryImage2(linesImage) = true;
% Display the image.
figure;
imshow(binaryImage2);
title('Final Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
drawnow;