3d Hill generating algorithm? - algorithm

Supposing you have a 3d box of cubes, with each cube having 3 indices: (x,y,z), and 1 additional attribute to specify if it represents land or air.
Let's say that we have a 3d array to represent this box of cubes, with each cube being an element in the 3d array.
The following array, for example, would represent a bowl shaped piece of land:
y=0:
0 0 0 0 0
0 0 0 0 0
1 1 1 1 1
1 1 1 1 1
y=1:
0 0 0 0 0
0 0 0 0 0
1 0 0 0 1
1 1 1 1 1
y=2:
0 0 0 0 0
0 0 0 0 0
1 0 0 0 1
1 1 1 1 1
y=3:
0 0 0 0 0
0 0 0 0 0
1 1 1 1 1
1 1 1 1 1
What is an algorithm such that given a selection box it would generate hills with f frequency and with average height of h, with v average variation in height?
We can assume that the lowest level of the bonding box is the "baseline", or "sea-level".
function makeTrees(double frequency, int height, double variation)
{
//return 3d array.
}
I'm writing a minecraft MCEdit filter plugin :P

Simplest way is to decompose the problem into three parts:
Write a routine to generate the cubes for a single hill of height h. Start off by making this a simple cone (play with apex angles till you find something that looks pleasing)
Generate a set of n heights between h-v and h+v, using the random number generator of your choice
Place n mountains randomly on your cube. It doesn't matter if they intersect - indeed, it will lead to a better-looking range.
However, I'd also suggest abandoning this approach, and simply generate a fractal terrain within your bounding cube, then discretize it. You can play with the paramaters to your fractal generator to bound the height and variance.

Assuming you would like sinusoidal hills of frequency f (or rather, wavenumber f, since "frequency" is usually used for temporal quantities) as a function of radius r = sqrt(x^2+y^2) from the center:
Define a threshold function like this:
Any element (x,y,z) with z < z_m will be land, and the rest will be air.

Related

How to calculate the max number of evenly spaced points on a grid

I need to create a grid that has x columns, y rows, where each cell in the grid can have a point in it, and each point is at least z horizontal/vertical spaces away from all other points.
1) Is there a simple method to calculate the maximum number of points I can place given the grid size and a spacing of z?
Here's an example 5x5 with z = 2. In this case the max number of points is 13.
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
and here's an example 5x5 where z = 3. In this case the max number of points is 6.
1 0 0 1 0
0 0 0 0 0
0 1 0 0 1
0 0 0 0 0
1 0 0 1 0
I'd like to be able, given x, y, and z, the number of points possible to plot.
2) What's the most efficient way of populating the grid in this manner?

do image segmentation given the boundary of regions in the image

I get an image and also the boundary of regions in the image. For example, I have a mask with logical type, the value of boundary is 1, while for other pixels, the value is 0. I want to label the regions segmented by the boundaries, while I am not sure how to segment and label the region based on the continuous boundary.
The boundary looks like this:
0 0 0 1 0 0 0 1 0 0
0 0 1 0 0 0 0 1 0 0
1 1 0 1 0 0 0 1 0 0
0 0 0 0 1 0 1 0 0 0
With the above diagram, there would be four regions that would be identified.
The function bwlabel from the image processing toolbox is the ideal function you should use to label each continuous region of non-zero pixels in a binary mask. However, you want to perform this on the zero pixels that are delineated by the "boundary" pixels that are set to 1. Therefore, simply use the inverse of the binary mask so that you are operating on the zero pixels instead of the non-zero pixels. Also from your definition, regions are separated using a 4 pixel connectivity. bwlabel by default uses 8 pixel connectivity when searching for continuous regions, which means that it looks in the N, NE, E, SE, S, SW, W and NW directions. You'll want to manually specify 4 pixel connectivity, which looks in only the directions of N, E, S and W.
Supposing your mask was stored in the variable L, simply do:
labels = bwlabel(~L, 4);
The output labels would be a map that tells you the membership of each pixel. Regions of the same membership tells you that those pixels belong to the same group.
Using your example, we get:
>> L = [0 0 0 1 0 0 0 1 0 0
0 0 1 0 0 0 0 1 0 0
1 1 0 1 0 0 0 1 0 0
0 0 0 0 1 0 1 0 0 0];
>> labels = bwlabel(~L, 4)
labels =
1 1 1 0 3 3 3 0 4 4
1 1 0 3 3 3 3 0 4 4
0 0 2 0 3 3 3 0 4 4
2 2 2 2 0 3 0 4 4 4
Each island of zeroes has a unique ID where pixels that belong to same ID belong to the same island or region. If you don't want to use bwlabel and do this from first principles, you can refer to my previous post using Depth First Search to find regions of connected components: How to find all connected components in a binary image in Matlab?. Be advised that this is not efficient code and so you should only use it for educational and research purposes. Using bwlabel is recommended as it is a fast function and well tested. You'll also have to modify the code so that it doesn't search in an 8 pixel connectivity and it should look at only a 4 pixel connectivity. Make sure you also inverse the input before using the code.

How to make all entries of 4x4 matrix to either 1 or 0 when only one operation is allowed?

I have a 4x4 matrix. Say
0 1 1 0
0 0 1 0
0 1 1 0
0 1 1 1
My task is to transform the matrix to either
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
or
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
Single operation is defined as pick any element of the matrix and then replace the element and elements to its left, right, up and down with their xor with 1.
Example
0 1 1 0
0 0 1 0
0 1 1 0
0 1 1 1
operation on marked element will transform the matrix to
0 1 0 0
0 1 0 1
0 1 0 0
0 1 1 1
My objective is to calculate the minimum number of operations needed to get the final result.
I don't even understand under what category this problem lies? Is this branch and bound, bactracking or something else.
What you've described is called lights out puzzle. There's relevant OEIS that gives you the minimal number of nontrivial switch flippings needed to solve the all-ones lights out problem on an n X n square.
Wikipedia describes a general sketch of algorithm how to solve it. You might be also interested in this answer here on SO, which includes a link to example implementation. Citing the answer:
The idea is to set up a matrix representing the button presses a column vector representing the lights and then to use standard matrix simplification techniques to determine which buttons to press. It runs in polynomial time and does not require any backtracking.

Explanation of Matlab's bwlabel,regionprops & centroid functions

I have spent all day reading up on the above MATLAB functions. I can't seem to find any good explanations online, even on the MathWorks website!
I would be very grateful if anyone could explain bwlabel, regionprops and centroid. How do they work if applied to a grayscale image?
Specifically, they are being used in this code below. How do the above functions apply to the code below?
fun=#minutie; L = nlfilter(K,[3 3],fun);
%% Termination LTerm=(L==1);
figure; imshow(LTerm)
LTermLab=bwlabel(LTerm);
propTerm=regionprops(LTermLab,'Centroid');
CentroidTerm=round(cat(1,LTerm(:).Centroid));
figure; imshow(~K)
set(gcf,'position',[1 1 600 600]); hold on
plot(CentroidTerm(:,1),CentroidTerm(:,2),'ro')
That's quite a mouthful to explain!... nevertheless, I'd love to explain it to you. However, I'm a bit surprised that you couldn't understand the documentation from MathWorks. It's actually quite good at explaining a lot (if not all...) of their functions.
BTW, bwlabel and regionprops are not defined for grayscale images. You can only apply these to binary images.
Update: bwlabel still has the restriction of accepting a binary image but regionprops no longer has this restriction. It can also take in a label matrix that is usually output from bwlabel as well as binary images.
Assuming binary images is what you want, my explanations for each function is as follows.
bwlabel
bwlabel takes in a binary image. This binary image should contain a bunch of objects that are separated from each other. Pixels that belong to an object are denoted with 1 / true while those pixels that are the background are 0 / false. For example, suppose we have a binary image that looks like this:
0 0 0 0 0 1 1 1 0 0
0 1 0 1 0 0 1 1 0 0
0 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 1 1
0 0 1 1 1 1 0 0 1 1
You can see in this image that there are four objects in this image. The definition of an object are those pixels that are 1 that are connected in a chain by looking at local neighbourhoods. We usually look at 8-pixel neighbourhoods where you look at the North, Northeast, East, Southeast, South, Southwest, West, Northwest directions. Another way of saying this is that the objects are 8-connected. For simplicity, sometimes people look at 4-pixel neighbourhoods, where you just look at the North, East, South and West directions. This woudl mean that the objects are 4-connected.
The output of bwlabel will give you an integer map where each object is assigned a unique ID. As such, the output of bwlabel would look something like this:
0 0 0 0 0 3 3 3 0 0
0 1 0 1 0 0 3 3 0 0
0 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 4
0 0 0 0 0 0 0 0 4 4
0 0 2 2 2 2 0 0 4 4
Because MATLAB processes things in column major, that's why the labelling is how you see above. As such, bwlabel gives you the membership of each pixel. This tells you where each pixel belongs to if it falls on an object. 0 in this map corresponds to the background. To call bwlabel, you can do:
L = bwlabel(img);
img would be the binary image that you supply to the function and L is the integer map I just talked about. Additionally, you can provide 2 outputs to bwlabel, and the second parameter tells you how many objects exist in the image. As such:
[L, num] = bwlabel(img);
With our above example, num would be 4. As another method of invocation, you can specify the connected pixel neighbourhoods you would examine, and so you can do this:
[L, num] = bwlabel(img, N);
N would be the pixel neighbourhood you want to examine (i.e. 4 or 8).
regionprops
regionprops is a very useful function that I use daily. regionprops measures a variety of image quantities and features in a black and white image. Specifically, given a black and white image it automatically determines the properties of each contiguous white region that is 8-connected. One of these particular properties is the centroid. This is also the centre of mass. You can think of this as the "middle" of the object. This would be the (x,y) locations of where the middle of each object is located. As such, the Centroid for regionprops works such that for each object that is seen in your image, this would calculate the centre of mass for the object and the output of regionprops would return a structure where each element of this structure would tell you what the centroid is for each of the objects in your black and white image. Centroid is just one of the properties. There are other useful features as well, but I'm assuming you don't want to do this. To call regionprops, you would do this:
s = regionprops(img, 'Centroid');
The above code will calculate the centroids of each of your objects in the image. You can specify additional flags to regionprops to specify each feature that you want. I do highly encourage that you take a look at all of the possible features that regionprops can calculate, as there are many that are useful in a variety of different applications and situations.
Also, by omitting any flags as input into the function, you would calculate all of the features in your image by default. Therefore, if we were to declare the image that we have seen above in MATLAB, this is what would happen after I run regionprops. After, let's calculate what the centroids are:
img = logical(...
[0 0 0 0 0 1 1 1 0 0;
0 1 0 1 0 0 1 1 0 0;
0 1 1 1 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 1;
0 0 0 0 0 0 0 0 1 1;
0 0 1 1 1 1 0 0 1 1]);
s = regionprops(img, 'Centroid');
... and finally when we display the centroids:
>> disp(cat(1,s.Centroid))
3.0000 2.6000
4.5000 6.0000
7.2000 1.4000
9.6000 5.2000
As such, the first centroid is located at (x,y) = (3, 2.6), the next centroid is located at (x,y) = (4.5, 6) and so on. Take special note that the x co-ordinate is the column while the y co-ordinate is the row.
Hope this is clear!

How can I find the most dense regions in an image?

Consider a black and white image like this
What I am trying to do is to find the region where the white points are most dense. In this case there are 20-21 such dense regions (i.e. the clusters of points makes a dense region).
Can anyone give me any hint on how this can be achieved?
If you have access to the Image Processing Toolbox, you can take advantage of a number of filtering and morphological operations it contains. Here's one way you could approach your problem, using the functions imfilter, imclose, and imregionalmax:
% Load and plot the image data:
imageData = imread('lattice_pic.jpg'); % Load the lattice image
subplot(221);
imshow(imageData);
title('Original image');
% Gaussian-filter the image:
gaussFilter = fspecial('gaussian', [31 31], 9); % Create the filter
filteredData = imfilter(imageData, gaussFilter);
subplot(222);
imshow(filteredData);
title('Gaussian-filtered image');
% Perform a morphological close operation:
closeElement = strel('disk', 31); % Create a disk-shaped structuring element
closedData = imclose(filteredData, closeElement);
subplot(223);
imshow(closedData);
title('Closed image');
% Find the regions where local maxima occur:
maxImage = imregionalmax(closedData);
maxImage = imdilate(maxImage, strel('disk', 5)); % Dilate the points to see
% them better on the plot
subplot(224);
imshow(maxImage);
title('Maxima locations');
And here's the image the above code creates:
To get things to look good I just kept trying a few different combinations for the parameters for the Gaussian filter (created using fspecial) and the structuring element (created using strel). However, that little bit of trial and error gave a very nice result.
NOTE: The image returned from imregionalmax doesn't always have just single pixels set to 1 (to indicate a maxima). The output image often contains clusters of pixels because neighboring pixels in the input image can have equal values, and are therefore both counted as maxima. In the code above I also dilated these points with imdilate just to make them easier to see in the image, which makes an even bigger cluster of pixels centered on the maxima. If you want to reduce the cluster of pixels to a single pixel, you should remove the dilation step and modify the image in other ways (add noise to the result or filter it, then find the new maxima, etc.).
Sliding Window (simple but slow)
You could create a sliding window (e.g. 10x10 pixels size) which iterates over the image, and for each position you count the number of white pixels in this 10x10 field, and store the positions with the highest counts.
This whole process is O(n*m) where n is the number of pixels of the image, and m the size of the sliding window.
In other words, you convolve the image with a mean filter (here the box filter), and then use the extrema.
Sliding Window (fast)
At first, calculate a summed area table, which can be done very efficiently in a single pass:
create a 2D array sat with the same size as the original image img.
Iterate over each index, and calculate for each index x and y
sat[x, y] = img[x, y] + sat[x-1, y] + sat[x, y-1] - sat[x-1, y-1]
For example, given an image where 0 is dark and 1 is white, this is the result:
img sat
0 0 0 1 0 0 0 0 0 1 1 1
0 0 0 1 0 0 0 0 0 2 2 2
0 1 1 1 0 0 0 1 2 5 5 5
0 1 0 0 0 0 0 2 3 6 6 6
0 0 0 0 0 0 0 2 3 6 6 6
Now iterate over the summed area table's indices with a sliding window, and calculate the number of white pixels in it by using the corners A, B, C, D of the sliding window:
img sat window
0 0 0 1 0 0 0 0 0 1 1 1 0 A-----B 1
0 0 0 1 0 0 0 0 0 2 2 2 0 | 0 2 | 2
0 1 1 1 0 0 0 1 2 5 5 5 0 | 2 5 | 5
0 1 0 0 0 0 0 2 3 6 6 6 0 | 3 6 | 6
0 0 0 0 0 0 0 2 3 6 6 6 0 D-----C 6
Calculate
density(x', y') = sat(A) + sat(C) - sat(B) - sat(D)
Which in the above example is
density(1, 0) = 0 + 6 - 1 - 2 = 3
This process requires a temporary image, but it is just O(n), so speed is independent of the sliding window's size.
if you have the image processing toolbox, blur it with a gaussian filter, then find the peaks/extrema.
vary the size of the gaussian filter to get the number of 'dense' regions you want.
Maybe a naive approach:
You define a square of n*n which is the maximum size of the region in which you measure the density. For each point in the image you consider the point as the center of the square and count around the number of black (b) and white (w) points. Using the difference b-w you can determine in which square(s) is the most white.
The most dense regions must be determined in a fuzzy way. If one region has 600 white points and another 599 then, for the human eye, they are the same density. 600 is 100% dense while 599 is 99% dense and 1% non-dense. Use an epsilon for this.
n can be predefined or based on some function (ie. percent of image size).
You could also use a circle/ellipse instead of square/rectangle. Choose what fits your needs best

Resources