Shifting of trace boundaries in Matlab code?

Viewed 189

I am trying to trace boundaries of objects using a manual ROI selection and to plot there outlines back on the original image in grayscale. I noticed that I have a shift of the outline compered to the original object location. Why? did I missed something in my code?

Code:

close all;
clear all;
clc;
I = imread('pillsetc.png');
figure('Name','pillsetc');
imshow(I)
  
x1 = 50;
y1 = 200
Iroi = imcrop(I,[x1,y1,400,150]);


GrayRoi = rgb2gray(Iroi);
figure('Name','pillsetcGrayCrop');
imshow(GrayRoi);
BWRoi = imbinarize(GrayRoi);
BWRoi = bwareaopen(BWRoi, 10);
BWRoi = imfill(BWRoi,'holes');
[B,L] = bwboundaries(BWRoi,'noholes');
            
stat = regionprops(L, 'Centroid');
figure('Name','pillsetcCropBoundaries');
imshow(rgb2gray(I));
hold on;
             
for k = 1 :numel(stat)
    b = B{k};
    c = stat(k).Centroid;
    plot(b(:,2)+x1, b(:,1)+y1,'r');
end

enter image description here

1 Answers

Looks like your image is not as binary as regionprops prefers. The regionprops function appears to be Left-to-Right raster scanning for the brightest to start and darkest to stop, and delays any action on gradients.

To put it simply:

  • Upon the brightest (similar to white) of a gradient, selection starts
  • Upon the darkest (similar to black) of a gradient, selection ends

So if you make make the dark background blur together to the same darkest level and then spike any non-dark to the brightest foreground (any grey above bottom couple darkest levels is set to white) before processing with regionprops, you might get better outlines.

Related