From bf50d05c582c37c4ba4149c7ea843262e796aadf Mon Sep 17 00:00:00 2001
From: Guillaume Pasero <guillaume.pasero@c-s.fr>
Date: Fri, 23 Aug 2019 15:04:05 +0200
Subject: [PATCH] BUG: fix potential TopologyException in GDAL

---
 .../AppSegmentation/app/otbLSMSVectorization.cxx | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/Modules/Applications/AppSegmentation/app/otbLSMSVectorization.cxx b/Modules/Applications/AppSegmentation/app/otbLSMSVectorization.cxx
index 467a0d8a05..506fbef994 100644
--- a/Modules/Applications/AppSegmentation/app/otbLSMSVectorization.cxx
+++ b/Modules/Applications/AppSegmentation/app/otbLSMSVectorization.cxx
@@ -292,7 +292,7 @@ private:
 
       //Creation of a multipolygon where are stored the geometries to be merged
       OGRMultiPolygon geomToMerge;
-      geomToMerge.addGeometry(firstFeature.GetGeometry());
+      AddValidGeometry(geomToMerge, firstFeature.GetGeometry());
       bool merging = true;
       otb::ogr::Feature nextFeature(nullptr);
       bool haveMerged=false;
@@ -309,7 +309,7 @@ private:
           //Storing of the new geometry if labels are identical
           if(merging)
             {
-            geomToMerge.addGeometry(nextFeature.GetGeometry());
+            AddValidGeometry(geomToMerge, nextFeature.GetGeometry());
             layer.DeleteFeature(nextFeature.GetFID());
             haveMerged=true;
             }
@@ -378,6 +378,18 @@ private:
     otbAppLogINFO(<<"Elapsed time: "<<(double)(toc - tic) / CLOCKS_PER_SEC<<" seconds");
   }
 
+  void AddValidGeometry(OGRMultiPolygon &multi, OGRGeometry const * g)
+  {
+    if (g->IsValid())
+      {
+      multi.addGeometry(g);
+      }
+    else
+      {
+      multi.addGeometryDirectly( g->Simplify(0.0) );
+      }
+  }
+
 };
 }
 }
-- 
GitLab