How to regroup or reconstruct connected elements in a binary image into squares

2 次查看(过去 30 天)
Hello, please I need help with this.
I have a binary image(50x50).
The matrix was randomly generated therefore making the image noisy. My aim is to regroup or reconstruct connected elements of same value together into different square shapes(not necessarily a perfect square), the edges of the square doesn't have to be smooth since the matrix is randomly generated. I did the following but I want to reconstruct all same elements into squares.
I = imread('Fig1.jpg');
BW = imbinarize(I); % Convert image to binary matrix.
L = bwlabeln(BW, 26) % Label connected elements.
  4 个评论
Akakan-Abasi Okon
Akakan-Abasi Okon 2021-8-31
Hi @KALYAN ACHARJYA, Sorry I didn't respond on time. I was thinking of a better way to put the question. The objective here is to remove the scattered pixels making the image noisy without distorting so much of the main squares/rectangle hidden in the noisy image. I initially thought regrouping them would help but it will be fine to remove them rather.

请先登录,再进行评论。

回答(1 个)

Image Analyst
Image Analyst 2021-8-30
Why are you using bwlabeln()? For one thing, that's for 3-D images, not 2-D like you have. And what do you mean "of the same value"? Originally, you only have two values 0 and 1. Do you simply want a square that is all white with as many white dots there are in your original image?
numDots = nnz(BW);
rows = ceil(sqrt(numDots));
whiteSquare = ones(rows, rows);
numBlack = rows * rows - numDots;
if numBlack >= 1
whiteSquare(1:numBlack) = 0;
end
Of course if you label them each connected component will have it's own ID number. Not sure if you want 4 connected or 8 connected but I believe if you use 26 connected on a 2-D image you'll get 8 connected (if it doesn't throw an error).
  12 个评论
Image Analyst
Image Analyst 2021-9-1
Don't use the while. It's not needed and confusing since h<0 is a matrix -- a lot of values -- not a single value. What Walter gave you is sufficient and correct.
h(h == -1) = 0;
Again, delete the while and end lines.

请先登录,再进行评论。

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by