From 6ca0ca5fcbbdba3c48aa29489a4f7ddbd0ff6429 Mon Sep 17 00:00:00 2001
From: Jean-Yves TINEVEZ <tinevez@pasteur.fr>
Date: Sun, 26 Jul 2020 12:31:08 +0200
Subject: [PATCH] mesh_to_heightmap: Create a height-map from a mesh.

Brute force, thanks to the power of linear scattered interpolant.
---
 src/@deproj/deproj.m            |  4 +++-
 src/@deproj/mesh_to_heightmap.m | 30 ++++++++++++++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 src/@deproj/mesh_to_heightmap.m

diff --git a/src/@deproj/deproj.m b/src/@deproj/deproj.m
index f76b75a..13c595f 100644
--- a/src/@deproj/deproj.m
+++ b/src/@deproj/deproj.m
@@ -131,7 +131,8 @@ classdef deproj
         % Read a PLY file.
         [ V, F, comments ] = ply_read( file_path )
 
-        
+        % Create a height-map from a mesh.
+        [ H, min_y, min_x ] = mesh_to_heightmap( V, pixel_size )
 
     end
     
@@ -144,6 +145,7 @@ classdef deproj
         % Returns the cells from a BW image with ridges.
         [ objects, junction_graph ] = mask_to_objects( I, downsample )
         
+        
     end
 end
 
diff --git a/src/@deproj/mesh_to_heightmap.m b/src/@deproj/mesh_to_heightmap.m
new file mode 100644
index 0000000..26f0fe9
--- /dev/null
+++ b/src/@deproj/mesh_to_heightmap.m
@@ -0,0 +1,30 @@
+function [ H, min_y, min_x ] = mesh_to_heightmap( V, pixel_size )
+%MESH_TO_HEIGHTMAP Create a height-map from a mesh.
+% Of course there are plenty of restriction on the mesh for this to be
+% valid. Mainly: we need the mesh to be so that there is only 1 Z for each
+% X, Y couple. Secondly, the X and Y coordinates need to be positive.
+
+    % Convert to pixel-coordinates.
+    x = V( :, 1 );
+    y = V( :, 2 );
+    xp = x / pixel_size;
+    yp = y / pixel_size;
+    z = V( :, 3 ) - min( V( :, 3 ) );
+
+    % Allocate target image.
+    max_x = 1 + ceil( max( xp ) );
+    max_y = 1 + ceil( max( yp ) );
+    min_x = 1 + floor( min( xp ) );
+    min_y = 1 + floor( min( yp ) );
+
+    % Interpolate.
+    si = scatteredInterpolant( xp, yp, z, 'linear', 'none' );
+
+    % Create elevation on the the grid.
+    [ X, Y ] = meshgrid( min_x : max_x, min_y : max_y );
+    z_im = si( X(:), Y(:) );
+    z_im( isnan( z_im ) ) = 0.;
+    H = reshape( z_im', [ ( max_y - min_y + 1 ) ( max_x- min_x + 1  ) ] );
+    
+end
+
-- 
GitLab