From 0d7603d5b50506712ec9e04121d9329157355a55 Mon Sep 17 00:00:00 2001
From: Yuriy Maksymets <iurii.maksymets@gmail.com>
Date: Sun, 10 Nov 2019 18:26:16 +0000
Subject: [PATCH] Visual representation of recognized line

---
 src/app.js    | 17 +++++++++++++++++
 src/shapes.js |  5 ++++-
 2 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/src/app.js b/src/app.js
index 3c7cdea..9af5845 100644
--- a/src/app.js
+++ b/src/app.js
@@ -7,6 +7,7 @@ import * as canvas from "./canvas.js"
 import * as HTML from "./elements.js"
 import { connect } from "./room.js"
 import * as toolSelection from "./tool-selection.js"
+import recognizeFromPoints from "./shapes.js"
 
 const TEST_ROOM = "imperial"
 
@@ -101,9 +102,25 @@ const onRoomConnect = (room_) => {
 
   room.addEventListener("addOrUpdatePath", ({ detail: { id, points } }) => {
     canvas.renderPath(id, points)
+    drawRecognized(points)
   })
 }
 
+const mp = (x, y) => [x, y, 1, "black", true]
+function drawRecognized(points) {
+  const recognizedShape = recognizeFromPoints(points)
+  if (recognizedShape.shape) {
+    console.log(recognizedShape)
+    const [x, y] = points[0]
+    const a = (recognizedShape.angle * Math.PI) / 180
+    const [x0, y0] = [x - 2000 * Math.cos(a), y + 2000 * Math.sin(a)]
+    const [x1, y1] = [x + 2000 * Math.cos(a), y - 2000 * Math.sin(a)]
+    canvas.renderPath("lastRecognizedLine", [mp(x0, y0), mp(x1, y1)])
+  } else {
+    canvas.renderPath("lastRecognizedLine", [])
+  }
+}
+
 const tryRoomConnect = async (roomID) => {
   return await connect(roomID)
     .then(onRoomConnect)
diff --git a/src/shapes.js b/src/shapes.js
index 28268de..c5a37bf 100644
--- a/src/shapes.js
+++ b/src/shapes.js
@@ -9,7 +9,7 @@ function sin(a) {
 }
 
 const rhoStep = 5
-const angleStep = rhoStep * 2
+const angleStep = 10
 const numAngleCells = 180 / angleStep
 const rhoMax = 1000
 
@@ -18,6 +18,7 @@ function findMaxInHough(accum, threshold) {
   //   let bestRho = 0
   let bestTheta = 0
   for (let i = 0; i < numAngleCells; i++) {
+    if (!accum[i]) continue
     for (let j = 0; j < accum[i].length; j++) {
       if (accum[i][j] > max) {
         max = accum[i][j]
@@ -56,6 +57,7 @@ function constructHoughAccumulator(accumulator, x, y) {
 }
 
 function recognizeFromPoints(points) {
+  if (!(points && points.length)) return {}
   const accum = Array(numAngleCells)
   points.forEach((x) => constructHoughAccumulator(accum, ...x))
   const angle = findMaxInHough(accum, points.length - 1)
@@ -64,6 +66,7 @@ function recognizeFromPoints(points) {
     return {
       shape: Shapes.line,
       angle: 90 - angle,
+      hough: accum,
       points,
     }
   }
-- 
GitLab