Create random parallel black lines in a white box until tis filled

1 view (last 30 days)
Hi everyone I am creating a white box and creating an initial black line that goes through the box and then i am trying to create random lines parallel to the initial one up until the whole box is filled.
My code is this one:
clc; clear; close;
% Define the size of the square
squareSize = 100;
% Create a square with white background
square = ones(squareSize, squareSize);
% Calculate the middle row of the square
middleRow = round(squareSize/2);
% Define the initial line thickness
lineThickness = 1;
% Draw a black line in the middle row of the square with the given thickness
square(max(1, middleRow-floor(lineThickness/2)):min(squareSize, middleRow+ceil(lineThickness/2)), :) = 0;
% Display the square with the black line
%imshow(square);
% Save the image with the initial line thickness
imwrite(square, 'line_thicknessrandom_1.png');
% Draw random lines parallel to the initial line
i = 1;
while any(square(:)==1)
% Generate random y-coordinate for the line
randRow = randi([1, squareSize]);
% Check if the random line overlaps with any existing line
while any(square(max(1, randRow-floor(lineThickness/2)):min(squareSize, randRow+ceil(lineThickness/2)), :)==0)
% Generate new random y-coordinate for the line
randRow = randi([1, squareSize]);
end
% Draw a black line at the non-overlapping random y-coordinate with the same thickness as the initial line
square(max(1, randRow-floor(lineThickness/2)):min(squareSize, randRow+ceil(lineThickness/2)), :) = 0;
% Save the image with the updated line thickness and random lines
filename = sprintf('line_thicknessrandom_%d.png', i+1);
imwrite(square, filename);
% Increment the counter variable
i = i + 1;
end
and while it does create a lot o parallel lines it stops at a certain point before the whole box is filled.
Does anyone know how to fix this?

Accepted Answer

DGM
DGM on 6 Mar 2023
Edited: DGM on 6 Mar 2023
The lines you're drawing are 2px wide, so the inner loop will never be satisfied once the only remaining stripes are 1px wide. You'll have to decide what you want to do, since filling those remaining lines strictly violates the conditions your code has in place for line placement.
  4 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!