Automatic Image Segmentation of three steel ropes using Image Processing Tools

1 次查看(过去 30 天)
Hello there,
I have an issue with dividing the image of three ropes into segments. You can see the original image (3104x3104) below:
I'd like to get some results of segmentation process like this:
How can I divide image into segments? What is the background should I choose? Please, help me with that.
I've written the code below, but I get unexpected results. How can I fix it?
I = imread('rope.jpg')
gs = im2gray(I)
imshow(gs)
imhist(gs)
%Adjust image contrast ratio%
Aadj = imadjust(gs);
imshow(Aadj)
%create binary image automatically
imhist(Aadj)
bw = im2bw(Aadj);
imshow(bw);
%Extract the first two largest objects from the binary image.
bw = bwareafilt(bw,[400, inf]);
%Fill holes in the extracted object regions.
bw = 1 - bw;
imshow(bw)

回答(2 个)

Raag
Raag 2025-4-24
Hi Darya,
From my understanding, you are trying to segment an image containing three ropes and generate a binary mask like the one you shared. The challenge appears to be achieving accurate segmentation with current method. This typically arises due to lighting variations, thresholding strategy, or insufficient morphological processing.
Here's an example of how we can modify your code:
I = imread('rope.jpg');
gs = rgb2gray(I);
Aadj = imadjust(gs);
% ‘imbinarize’ with 'adaptive' handles uneven lighting better than fixed thresholds like ‘im2bw’.
bw = imbinarize(Aadj, 'adaptive', 'Sensitivity', 0.4);
% ‘bwareaopen’ and ‘imfill’ clean up noise and fill internal rope gaps
bw = bwareaopen(bw, 500);
bw = imfill(bw, 'holes');
bw = imclose(bw, strel('disk', 3));
% ‘bwareafilt’ ensures only the main rope regions are preserved
bw = bwareafilt(bw, 3);
imshow(bw)
title('Segmented Ropes')
Following the above given approach, we can have the output as:
For a better understanding of the above solution, refer to the following MATLAB documentations:

Image Analyst
Image Analyst 2025-4-24
@Darya Yakovleva, I'm really surprised I did not see your post when you posted it 4 years ago. But anyway, you've chosen wisely when you chose to have a contrasting color for the background. That means you can use the Color Thresholder app (On the Apps tab of the tool ribbon) to get a mask for the yellow background. Then just invert it and do a little cleanup to get a mask for the ropes (cables) alone.
% Demo by Image Analyst
% 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;
fontSize = 25;
fprintf('Beginning to run %s.m at %s...\n', mfilename, datetime('now','TimeZone','local','Format','HH:mm:ss'));
Beginning to run LiveEditorEvaluationHelperEeditorId.m at 12:58:42...
%--------------------------------------------------------------------------------------------------------
% READ IN TEST IMAGE
folder = [];
baseFileName = 'cables.png';
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);
%--------------------------------------------------------------------------------------------------------
% Display the image.
subplot(1, 2, 1);
imshow(rgbImage);
impixelinfo;
axis('on', 'image');
title('Original RGB Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Maximize window.
g = gcf;
g.WindowState = 'maximized';
g.Name = 'Demo by Image Analyst';
g.NumberTitle = 'off';
drawnow;
%--------------------------------------------------------------------------------------------
% Get cable mask first by getting the mask of the yellow background.
[mask, maskedRGBImage] = createYellowMask(rgbImage);
% Invert it to get the non-yellow regions.
mask = ~mask;
% Take the 3 largest blobs since we know there should be exactly 3 cables.
mask = bwareafilt(mask, 3);
% Fill small holes in the regions.
mask = imfill(mask, 'holes');
% Display the new image.
subplot(1, 2, 2);
imshow(mask);
impixelinfo;
axis('on', 'image');
title('Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
fprintf('Done running %s.m at %s...\n', mfilename, datetime('now','TimeZone','local','Format','HH:mm:ss'));
Done running LiveEditorEvaluationHelperEeditorId.m at 12:58:43...
%=====================================================================================
function [BW,maskedRGBImage] = createYellowMask(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 24-Apr-2025
%------------------------------------------------------
% Convert RGB image to chosen color space
I = rgb2hsv(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.116;
channel1Max = 0.158;
% 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.351;
channel3Max = 1.000;
% 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

Community Treasure Hunt

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

Start Hunting!

Translated by