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

조회 수: 5 (최근 30일)
lena kappa
lena kappa 2023년 3월 5일
편집: lena kappa 2023년 3월 6일
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?

채택된 답변

DGM
DGM 2023년 3월 6일
편집: DGM 2023년 3월 6일
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
lena kappa
lena kappa 2023년 3월 6일
편집: lena kappa 2023년 3월 6일
@DGM thank you!
lena kappa
lena kappa 2023년 3월 6일
편집: lena kappa 2023년 3월 6일
Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by