![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1312045/image.jpeg)
How to randomly generate point cloud in irregular range?
조회 수: 6 (최근 30일)
이전 댓글 표시
I'm currently building a 3D point cloud and I've sliced the point cloud. Assuming that the slice map is irregular, I want to randomly generate a point cloud within a certain range, and let the point cloud generate a complete plane, and finally allow me to calculate the volume accuracy increase. The current idea is to project the 3D point cloud into a 2D point cloud, and then randomly generate the point cloud within a given range, but I don't know any way to specify my irregular range.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1311980/image.png)
The blank is the part where I need to randomly generate the point cloud.
댓글 수: 0
채택된 답변
John D'Errico
2023년 3월 2일
It is not at all clear what you are looking to do from your question. But I believe you are asking how, given a 2-dimensional arbitrary domain, to then populate that region randomly (so I can only assume uniformly) with points.
You can use my randpoly tool to do this task. It lies on the File Exchange for free download.
As an example,
PS = polyshape([0 0;1 0;1 1;.6 .3]);
xy = randpoly(100,PS);
plot(xy(:,1),xy(:,2),'ro')
hold on
plot(PS)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1312045/image.jpeg)
As long as you can describe the region of interest as a polygon, or a polyshape, you can populate that region with uniformly random points. In the example above, I creatd the polyshape first, since that is a nice tool to also plot the region. As you can see, all points fell inside the region.
RANDPOLY uses a constructive scheme to generate random points in the 2-d region. It dissections your polygon bounded region into a triangulation, and then uniformly generates points inside each triangle proportionally to the area of each triangle. This insures a uniform sampling over the domain. It does NOT use a rejection scheme, which can be extremely inefficient.
추가 답변 (1개)
Image Analyst
2023년 3월 2일
Is your domain a digital image (an array) or is it analytical (like just a bunch of x,y coordinates that define locations or regions). If an image and you can create a binary image (mask) of the white part where you want to place the random points (blue pixels), then you can generate a huge number of coordinates (way more than you think you'll need) and just see if it's in the mask or not. If it is, place it. If it's not, then try the next point. Then repeat until you've placed as many as you want.
댓글 수: 3
Image Analyst
2023년 3월 3일
You should have attached your digital image. But it looks like you actually have just coordinates, not an image, since you accepted John's answer which works with just polygons and coordinates. If you really have a digital image instead (like the attached one I made from your screenshot), and "The blank is the part where I need to randomly generate the point cloud." you can use this code to randomly generate points in the blank/white part.
% Demo by Image Analyst
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
%===============================================================================
% Get the name of the image the user wants to use.
baseFileName = 'BlueMask.png';
folder = pwd;
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
%=======================================================================================
% Read in image.
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display image.
subplot(1, 3, 1);
imshow(rgbImage, []);
impixelinfo;
axis on;
caption = sprintf('Original RGB Image\n%s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
g = gcf;
g.WindowState = "maximized";
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
%--------------------------------------------------------------------------------------------------
% Get the white parts of the image
mask = (rgbImage(:, :, 1) == 255) & (rgbImage(:, :, 2) == 255) & (rgbImage(:, :, 3) == 255);
% Display image.
subplot(1, 3, 2);
imshow(mask, []);
impixelinfo;
axis on;
title('White Mask', 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
drawnow;
%--------------------------------------------------------------------------------------------------
% Ask user for number of dots to draw.
defaultValue = 3000;
titleBar = 'Enter an integer value';
userPrompt = 'Enter the number of dots you want added';
dialogBoxWidth = 100;
caUserInput = inputdlg(userPrompt, titleBar, [1, dialogBoxWidth], {num2str(defaultValue)});
if isempty(caUserInput),return,end % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
numDots = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(numDots)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
numDots = defaultValue;
message = sprintf('I said it had to be an integer.\nTry replacing the user.\nI will use %d and continue.', numDots);
uiwait(warndlg(message));
end
%--------------------------------------------------------------------------------------------------
% Get way more random dot coordinates than we'll need
areaFraction = nnz(mask) / (rows * columns);
numTrialDots = round(2 * numDots / areaFraction)
randomX = randi(columns, numTrialDots, 1);
randomY = randi(rows, numTrialDots, 1);
numDotsSuccessfullyPlaced = 0;
for k = 1 : numTrialDots
row = randomY(k);
col = randomX(k);
% See if this one is in the white mask region.
if mask(row, col)
% It is. So place the dot. Burn a black single pixel dot into the image.
rgbImage(row, col, :) = [0, 0, 0];
numDotsSuccessfullyPlaced = numDotsSuccessfullyPlaced + 1;
if numDotsSuccessfullyPlaced == numDots
% We've got all the user wanted so exit.
break;
end
end
end
% Display final image.
subplot(1, 3, 3);
imshow(rgbImage, []);
impixelinfo;
axis on;
caption = sprintf('Final RGB Image with %d dots', numDotsSuccessfullyPlaced);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1313240/image.png)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!