preprocessing.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. function init_preprocessing(input_width, display_container, sample_container, on_capture_callback, on_shadow_callback, on_calibration) {
  2. let zodiac = true;
  3. let video = null;
  4. let package = null;
  5. let thread = null
  6. let height = 0;
  7. let width = 0;
  8. const FPS = 30;
  9. let canvasFrame = null;
  10. let context = null;
  11. let src = null;
  12. let background = null;
  13. let dst = null;
  14. let ones = null;
  15. let zeros = null;
  16. let disp = null;
  17. let disp_warpped = null;
  18. let M_raw_to_capture_to_disp = null;
  19. let M_raw_to_capture = cv.matFromArray(2, 3, cv.CV_64FC1, [1, 0, 0, 0, 1, 0]);
  20. let capture_res = null;
  21. let raw_to_capture_to_disp_ratio = null;
  22. let capture_x = 0;
  23. let capture_y = 0;
  24. let capture_res_percent = 1;
  25. let capture_alpha = 0.05;
  26. let raw_offset_x = 0;
  27. let raw_offset_y = 0;
  28. let raw_to_disp_ratio = null;
  29. let M_raw_to_disp = null;
  30. let disp_width = input_width;
  31. let disp_height = disp_width;
  32. let disp_offset_x = 0;
  33. let disp_offset_y = 0;
  34. let mode = 0;
  35. let mode_steps = 0
  36. let background_update_alpha = 0.05
  37. // tracking
  38. let tx = -1;
  39. let ty = -1;
  40. let ta = 0.1;
  41. let epsilon = 200;
  42. let countdown = 1000;
  43. let stamp = new Date().getTime();
  44. let allow_capture = true;
  45. let allow_pre_capture = false;
  46. let first = true;
  47. function reset_state() {
  48. tx = -1;
  49. ty = -1;
  50. allow_pre_capture = false;
  51. first = true;
  52. allow_capture = true;
  53. }
  54. function in_criterior(x, y) {
  55. return (x - tx) * (x - tx) + (y - ty) * (y - ty) < epsilon;
  56. }
  57. $(document).ready(function() {
  58. init(640, 480);
  59. request_stream(assign_stream);
  60. });
  61. function request_stream(callback) {
  62. navigator.mediaDevices.getUserMedia({ video: { width: { min: 640 }, height: { min: 480 } }, audio: false })
  63. .then(function(stream) {
  64. callback(stream);
  65. })
  66. .catch(function(err) {
  67. });
  68. };
  69. function assign_stream(stream) {
  70. if(thread != null) clearTimeout(thread);
  71. video = document.getElementById("videoInput"); // video is the id of video tag
  72. video.srcObject = stream;
  73. video.play();
  74. thread = setTimeout(processVideo, 0);
  75. }
  76. function stop_stream(){
  77. clearTimeout(thread);
  78. thread = null;
  79. video.srcObject.getTracks()[0].stop();
  80. }
  81. function init(w, h) {
  82. width = w;
  83. height = h;
  84. body = $('body');
  85. videoElement = $('<video autoplay="true" control="true" playsinline="true" id="videoInput" width="' + width + '" height="' + height + '"></video>');
  86. body.append(videoElement);
  87. videoElement.hide();
  88. canvasElement = $('<canvas id="canvasFrame" width="' + width + '" height="' + height + '"></canvas>');
  89. body.append(canvasElement);
  90. canvasElement.hide();
  91. canvasFrame = document.getElementById("canvasFrame"); // canvasFrame is the id of <canvas>
  92. context = canvasFrame.getContext("2d");
  93. canvasElement = $('<canvas id="canvasOutput" width="' + disp_width + '" height="' + disp_height + '"class="rcorners"'+'></canvas>');
  94. display_container.append(canvasElement);
  95. rawFrame = document.getElementById("canvasOutput");
  96. rawContext = rawFrame.getContext("2d");
  97. capture_res = Math.min(width, height)*capture_res_percent;
  98. dataElement = $('<canvas id="dataFrame" width="' + capture_res + '" height="' + capture_res + '"></canvas>');
  99. body.append(dataElement);
  100. dataElement.hide();
  101. capture_x = width*0.5;
  102. capture_y = height/2;
  103. M_raw_to_capture = cv.matFromArray(2, 3, cv.CV_64FC1, [1.0, 0, -(capture_x - capture_res*0.5), 0, 1.0, -(capture_y - capture_res*0.5)]);
  104. previewElement = $('<canvas id="previewFrame" width="' + disp_width + '" height="' + disp_height + '"></canvas>');
  105. sample_container.prepend(previewElement);
  106. previewFrame = document.getElementById("previewFrame");
  107. previewContext = previewFrame.getContext("2d");
  108. raw_to_disp_ratio = disp_width * 1.0 / Math.min(width, height);
  109. raw_offset_x = (width - Math.min(width, height)) / 2;
  110. raw_offset_y = (height - Math.min(width, height)) / 2;
  111. M_raw_to_disp = cv.matFromArray(2, 3, cv.CV_64FC1, [raw_to_disp_ratio, 0, -raw_offset_x*raw_to_disp_ratio, 0, raw_to_disp_ratio, -raw_offset_y*raw_to_disp_ratio]);
  112. raw_to_capture_to_disp_ratio = disp_width * 1.0 / capture_res;
  113. M_raw_to_capture_to_disp =
  114. cv.matFromArray(2, 3, cv.CV_64FC1,
  115. [raw_to_capture_to_disp_ratio, 0, -(capture_x - capture_res*0.5)*raw_to_capture_to_disp_ratio, 0, raw_to_capture_to_disp_ratio, -(capture_y - capture_res*0.5)*raw_to_capture_to_disp_ratio]);
  116. src = new cv.Mat(height, width, cv.CV_8UC4);
  117. src_cap = new cv.Mat(capture_res, capture_res, cv.CV_8UC4, new cv.Scalar(255, 255, 255, 255));
  118. src_disp = new cv.Mat(disp_height, disp_width, cv.CV_8UC4, new cv.Scalar(255, 255, 255, 255));
  119. background = new cv.Mat(capture_res, capture_res, cv.CV_8UC4, new cv.Scalar(0, 0, 0, 255));
  120. diff = new cv.Mat(capture_res, capture_res, cv.CV_8UC4);
  121. dst = new cv.Mat(capture_res, capture_res, cv.CV_8UC1);
  122. ones = new cv.Mat(capture_res, capture_res, cv.CV_8UC1, new cv.Scalar(255, 255, 255, 255));
  123. zeros = new cv.Mat(capture_res, capture_res, cv.CV_8UC1, new cv.Scalar(0, 0, 0, 255));
  124. data_image = new cv.Mat(capture_res, capture_res, cv.CV_8UC4);
  125. disp = new cv.Mat(disp_height, disp_height, cv.CV_8UC4, new cv.Scalar(255, 255, 255, 255));
  126. preview_image = new cv.Mat(disp_height, disp_height, cv.CV_8UC4);
  127. reset_state();
  128. mode = 0;
  129. mode_steps = 0;
  130. background.setTo(new cv.Scalar(0, 0, 0, 255));
  131. }
  132. function collectBackground() {
  133. cv.addWeighted(background, 1.0 - background_update_alpha, src_cap, background_update_alpha, 0, background);
  134. }
  135. function processVideo() {
  136. let begin = Date.now();
  137. context.drawImage(video, 0, 0, width, height);
  138. src.data.set(context.getImageData(0, 0, width, height).data);
  139. cv.flip(src, src, 1);
  140. cv.warpAffine(src, src_cap, M_raw_to_capture, new cv.Size(capture_res, capture_res));
  141. // console.log(mode,'qw9q4d89qw49d8q4w9d84qw');
  142. if (mode == 0 && canCalibrate) {
  143. collectBackground();
  144. cv.absdiff(src_cap, background, diff);
  145. cv.cvtColor(diff, dst, cv.COLOR_RGBA2GRAY);
  146. kernel = new cv.Size(21, 21);
  147. cv.blur(dst, dst, kernel);
  148. maxTuple = cv.minMaxLoc(dst);
  149. xy = maxTuple.maxLoc;
  150. max_value = maxTuple.maxVal;
  151. if(max_value < 20 && mode_steps > 70) {
  152. mode = 2;
  153. mode_steps = 0;
  154. allow_capture = true;
  155. }
  156. if(max_value < 20) mode_steps = mode_steps + 1;
  157. else mode_steps = Math.max(mode_steps - 1, 0);
  158. if(on_calibration != null) {
  159. on_calibration(mode_steps*1.0/70);
  160. }
  161. cv.resize(src_cap, disp, new cv.Size(disp_width, disp_width));
  162. cv.imshow("canvasOutput", disp);
  163. // cv.warpAffine(src, src_disp, M_raw_to_disp, new cv.Size(disp_width, disp_width));
  164. // cv.imshow("canvasOutput", src_disp);
  165. }else if(mode == 1) {
  166. collectBackground();
  167. cv.absdiff(src_cap, background, diff);
  168. cv.cvtColor(diff, dst, cv.COLOR_RGBA2GRAY);
  169. kernel = new cv.Size(21, 21);
  170. cv.blur(dst, dst, kernel);
  171. maxTuple = cv.minMaxLoc(dst);
  172. xy = maxTuple.maxLoc;
  173. max_value = maxTuple.maxVal;
  174. if(max_value > 50) {
  175. allow_pre_capture = true;
  176. mode_steps = 0;
  177. }
  178. if(allow_pre_capture) {
  179. mode_steps = mode_steps + 1;
  180. }
  181. if (mode_steps > 30 && max_value < 20) {
  182. mode = 2;
  183. mode_steps = 0;
  184. allow_capture = true;
  185. }
  186. cv.warpAffine(src, src_disp, M_raw_to_disp, new cv.Size(disp_width, disp_width));
  187. cv.imshow("canvasOutput", src_disp);
  188. var dwcr = disp_width / (width - raw_offset_x*2);
  189. var dhcr = disp_height / (height - raw_offset_y*2);
  190. rawContext.strokeStyle = "blue";
  191. console.log((capture_x - capture_res*0.5 - raw_offset_x) * dwcr,
  192. (capture_y - capture_res*0.5 - raw_offset_y) * dhcr, capture_res * dwcr, capture_res * dhcr);
  193. rawContext.rect((capture_x - capture_res*0.5 - raw_offset_x) * dwcr,
  194. (capture_y - capture_res*0.5 - raw_offset_y) * dhcr, capture_res * dwcr, capture_res * dhcr);
  195. rawContext.stroke();
  196. }else if(mode == 2) {
  197. cv.absdiff(src_cap, background, diff);
  198. cv.cvtColor(diff, dst, cv.COLOR_RGBA2GRAY);
  199. kernel = new cv.Size(5, 5)
  200. cv.blur(dst, dst, kernel)
  201. cv.threshold(dst, dst, 100, 255, cv.THRESH_TRIANGLE);
  202. // cv.subtract(ones, dst, dst);
  203. // let M = cv.Mat.ones(7, 7, cv.CV_8U);
  204. // cv.morphologyEx(dst, dst, cv.MORPH_CLOSE, M);
  205. let contours = new cv.MatVector();
  206. let hierarchy = new cv.Mat();
  207. cv.findContours(dst, contours, hierarchy, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE);
  208. var max_i = -1;
  209. var max_size = 0;
  210. for (let i = 0; i < contours.size(); ++i) {
  211. var temp = contours.get(i)
  212. if (temp.rows > max_size) {
  213. max_size = temp.rows;
  214. max_i = i;
  215. }
  216. temp.delete();
  217. }
  218. if(max_i != -1 && max_size > 0)
  219. {
  220. data_image.setTo(new cv.Scalar(255, 255, 255, 255));
  221. let color = new cv.Scalar(0, 0, 0, 255);
  222. cv.drawContours(data_image, contours, max_i, color, cv.FILLED, cv.LINE_8, hierarchy, 1);
  223. let cnt = new Contour_Object(contours.get(max_i));
  224. if(cnt.area < capture_res*capture_res/2)
  225. {
  226. if(on_shadow_callback != null)
  227. on_shadow_callback(cnt);
  228. if (in_criterior(cnt.cx, cnt.cy)) {
  229. if (new Date().getTime() - stamp > countdown) {
  230. capture(cnt);
  231. }
  232. } else {
  233. stamp = new Date().getTime();
  234. }
  235. tx = tx * (1.0 - ta) + cnt.cx * ta;
  236. ty = ty * (1.0 - ta) + cnt.cy * ta;
  237. }else{
  238. if(on_shadow_callback != null)
  239. on_shadow_callback(null);
  240. }
  241. }else{
  242. if(on_shadow_callback != null)
  243. on_shadow_callback(null);
  244. }
  245. contours.delete();
  246. hierarchy.delete();
  247. cv.resize(src_cap, disp, new cv.Size(disp_width, disp_width));
  248. cv.imshow("canvasOutput", disp); // canvasOutput is the id of another <canvas>;
  249. // cv.imshow("canvasOutput", dst); // canvasOutput is the id of another <canvas>;
  250. }
  251. // schedule next one.
  252. let delay = 1000 / FPS - (Date.now() - begin);
  253. thread = setTimeout(processVideo, delay);
  254. }
  255. // schedule first one.
  256. let contour_object_list = {};
  257. function capture(contour_obj) {
  258. if (!allow_capture) return;
  259. allow_capture = false;
  260. contour_object_list[contour_obj.id] = contour_obj;
  261. cv.imshow("dataFrame", data_image);
  262. cv.resize(data_image, preview_image, new cv.Size(disp_width, disp_height));
  263. cv.imshow("previewFrame", preview_image);
  264. if(window.classify_contour != null) {
  265. window.classify_contour(contour_obj, on_inferred);
  266. }else{
  267. package = {
  268. reference: contour_obj.id,
  269. image: dataFrame.toDataURL()
  270. };
  271. $.post("/classify", package, function(data, status, xhr) {
  272. var json = JSON.parse(data);
  273. on_inferred(json.reference, json["classes"][0], json["raw"][0]);
  274. });
  275. }
  276. }
  277. function on_inferred(id, classes, raws){
  278. var contour_obj = contour_object_list[id];
  279. contour_obj["class"] = classes;
  280. contour_obj["score"] = raws;
  281. previewContext.fillStyle="#FFFFFF";
  282. previewContext.fillRect(40,35,40,20);
  283. previewContext.fillStyle="#000000";
  284. previewContext.font="18px Arial";
  285. previewContext.fillText(classes[0].toString(), 50, 50);
  286. reset_state();
  287. if(on_capture_callback != null) {
  288. on_capture_callback(contour_obj);
  289. }
  290. delete contour_object_list[id];
  291. };
  292. function Contour_Object(contours) {
  293. this.id = new Date().getTime();
  294. this.score = null;
  295. this.class = null;
  296. this.raw_contours = contours;
  297. var Moments = cv.moments(contours, false);
  298. this.cx = Moments.m10 / (Moments.m00 + 1e-6);
  299. this.cy = Moments.m01 / (Moments.m00 + 1e-6);
  300. var a = cv.contourArea(contours, true);
  301. this.ccw = a < 0;
  302. this.area = Math.abs(a);
  303. function point_dist(p0, p1) {
  304. return Math.sqrt((p0[0] - p1[0])*(p0[0] - p1[0]) + (p0[1] - p1[1])*(p0[1] - p1[1]));
  305. }
  306. function interpolate_point(p0, p1, alpha) {
  307. return [p0[0] * (1 - alpha) + p1[0] * (alpha), p0[1] * (1 - alpha) + p1[1] * (alpha)];
  308. }
  309. this.re_contour = function(size) {
  310. var len_contour = this.raw_contours.rows;
  311. var c_p = this.raw_contours.row(0).data32S;
  312. var contour_portions = [0.0];
  313. for(var i = 1; i<len_contour; ++i) {
  314. var n_p = this.raw_contours.row(i).data32S;
  315. var dist = point_dist(n_p, c_p);
  316. contour_portions.push(dist + contour_portions[i - 1]);
  317. c_p = n_p;
  318. }
  319. var n_p = this.raw_contours.row(0).data32S;
  320. var dist = point_dist(n_p, c_p);
  321. var total_length = dist + contour_portions[len_contour - 1];
  322. contour_portions.push(total_length);
  323. var out_contour = [];
  324. var index = 1
  325. for(var i = 0;i<size;++i) {
  326. var cs = total_length * i * 0.999 / (size - 1);
  327. while(contour_portions[index] < cs) {
  328. index = index + 1;
  329. }
  330. var alpha = (cs - contour_portions[index - 1]) / (contour_portions[index] - contour_portions[index - 1]);
  331. var new_point = interpolate_point(this.raw_contours.row(index-1).data32S, this.raw_contours.row(index % len_contour).data32S, alpha);
  332. if(this.ccw) out_contour.push(new_point);
  333. else out_contour.unshift(new_point);
  334. }
  335. return out_contour;
  336. }
  337. this.set_canvas = function(x1, y1, x2, y2, size) {
  338. var new_contour = null;
  339. var total = this.raw_contours.rows;
  340. if(size != null)
  341. {
  342. new_contour = this.re_contour(size);
  343. total = size;
  344. }
  345. var w = x2-x1;
  346. var h = y2-y1;
  347. var sx = (x1 + x2)/2;
  348. var sy = (y1 + y2)/2;
  349. var nps = [];
  350. for(var i = 0;i<total;++i){
  351. var temp = new_contour ? new_contour[i] : this.raw_contours.row(i).data32S;
  352. var x = (temp[0]*1.0 / capture_res - 0.5) * w;
  353. var y = (temp[1]*1.0 / capture_res - 0.5) * h;
  354. nps.push([x + sx, y + sy]);
  355. }
  356. return nps;
  357. }
  358. }
  359. return {
  360. restart: function() {
  361. reset_state();
  362. mode = 0;
  363. mode_steps = 0;
  364. },
  365. shutdown: function() {
  366. stop_stream();
  367. },
  368. reset_camera: function() {
  369. stop_stream();
  370. request_stream(assign_stream);
  371. }
  372. };
  373. };