Color a voronoi diagram in MATLAB according to the color values of the initial points

Viewed 612

I have a matrix of points named start_coord containing their x and y coordinates, as well as a column denoting their classification (1-5). I.e. the first row looks like [75, 100, 4].

I've calculated a voronoi diagram of this data using the code below

[vc_x, vc_y] = voronoi(start_coord(:,1), start_coord(:,2));

How would I go about coloring the resulting polygons by the classification value of the point contained within each polygon, i.e. the third column in start_coord?

EDIT For quick plotting of polygons by color reference the answer in the comments below, which helped inform this edit. For getting the voronoi polygons for thousands of points written to an array that can be saved as an image refer to this code:

new_map = zeros(sm_size(1), sm_size(2));
        start_coord = readmatrix(char(join([csv_path, '/', run_types(run), common_name_csv], "")));
        sc_size = size(start_coord);
        
        dt = delaunayTriangulation(start_coord(:,1:2));
        [V,R] = voronoiDiagram(dt);
                
        for i = 1:sc_size(1)
            A=V(R{i},:);
            B=A(any(~isinf(A),2),:); % omit points at infinity
            bw = poly2mask(B(:,1), B(:,2), sm_size(1), sm_size(2));
            new_map(bw == 1) = color_map(start_coord(i,3));
        end

new_map can then be saved as an array or converted to RGB and saved as an image.

1 Answers

Use voronoiDiagram to get the polygons.

dt = delaunayTriangulation(start_coord(:,1:2));
[V,R] = voronoiDiagram(dt);

Then R{i} will be the vertices of polygon from start_coord(i,:) So set the color to start_coord(i,3)'s color and:

A=V(R{i},:);
B=A(any(~isinf(A),2),:); % omit points at infinity
plot(polyshape(B));

The only hiccup there is that the vertices at infinity get chopped off. But maybe that will get you close enough to what you want. If you need to fill to the edge, check out the VoronoiLimit function (which I have not tested).

e.g.:

X = [-1.5 3.2; 1.8 3.3; -3.7 1.5; -1.5 1.3; ...
0.8 1.2; 3.3 1.5; -4.0 -1.0;-2.3 -0.7; ...
0 -0.5; 2.0 -1.5; 3.7 -0.8; -3.5 -2.9; ...
-0.9 -3.9; 2.0 -3.5; 3.5 -2.25];

X(:,3) = [ 1 2 1 3 1 2 2 2 2 3 3 3 3 3 3]';

ccode = ["red","green","blue"];

dt = delaunayTriangulation(X(:,1:2));
[V,R] = voronoiDiagram(dt);
figure
voronoi(X(:,1),X(:,2))
hold on
for i = 1:size(X,1)
    A=V(R{i},:);
    B=A(any(~isinf(A),2),:);
    if(size(B,1)>2)
        plot(polyshape(B),'FaceColor',ccode(X(i,3)));
    end
end

Result: enter image description here

Related