フィルターのクリア

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

1 回表示 (過去 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