Debian Codegraph @

eyes17/blockly/cv/cvutils.js

raw
1 var utils;
2 var streaming = false;
3 var video=null,src=null,dst=null, cap = null, videoInput= null;
4 var frames = {};
5 var framedata = {};
6 var backgrounds = {};
7 var begin=0;
8
9 var camcallback = null;
10 var cameraType = null;
11
12 var cameraReady = function(){
13 if(camcallback == null){
14 console.log('no callback for camera permission granted. '+camcallback);
15 return;
16 }
17
18 var startvid = function() {
19 onVideoStarted();
20 camcallback();
21 };
22
23 if(utils == null){
24 utils = new Utils();
25 utils.loadOpenCv(() => {
26 utils.stopCamera();
27 video = document.createElement('video');
28 video.id = 'videoInput'; video.width = "160px"; video.height = "120px";
29 cvresults.append(video);
30 utils.startCamera('qvga', startvid, 'videoInput');
31 });
32 }else{
33 utils.stopCamera();
34 video = document.createElement('video');
35 video.id = 'videoInput'; video.width = "160px"; video.height = "120px";
36 cvresults.append(video);
37 utils.startCamera('qvga', startvid, 'videoInput');
38 }
39
40 }
41 var startCV = function(cam, callback){
42 cameraType = cam; //user/environment. front or back cam
43 camcallback = callback;
44 /* if(typeof JSBridge != 'undefined'){
45 if(!JSBridge.isCameraAvailable()){
46 JSBridge.getCameraPermission();
47 return;
48 }
49 }*/
50 cameraReady();
51
52 }
53
54 function onVideoStarted() {
55 videoInput = document.getElementById('videoInput');
56 videoInput.width = videoInput.videoWidth;
57 videoInput.height = videoInput.videoHeight;
58 streaming = true;
59 //setTimeout(processVideo, 0);
60 }
61
62
63 function stopCV(){
64 streaming = false;
65 framedata = {};
66 frames = {};
67 }
68 function processVideo() {
69 let video = document.getElementById('videoInput');
70 let src = new cv.Mat(video.height, video.width, cv.CV_8UC4);
71 let dst = new cv.Mat(video.height, video.width, cv.CV_8UC1);
72 let cap = new cv.VideoCapture(video);
73
74 const FPS = 5;
75
76
77 try {
78 if (!streaming) {
79 // clean and stop.
80 src.delete();
81 dst.delete();
82 return;
83 }
84 begin = Date.now();
85 // start processing.
86 cap.read(src);
87 cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY);
88
89 keypoints = simpleBlobDetector(src);
90
91 for (const keypoint of keypoints) {
92 const center = new cv.Point(keypoint.pt.x, keypoint.pt.y)
93 cv.circle(dst, center, keypoint.size, [255, 0, 0, 255], 3)
94 }
95
96 cv.imshow('canvasOutput', dst);
97 // schedule the next one.
98 let delay = 1000/FPS - (Date.now() - begin);
99 setTimeout(processVideo, delay);
100 } catch (err) {
101 utils.printError(err);
102 }
103 };
104
105
106 function getFrame(id, preview, callback) {
107 cap = new cv.VideoCapture(video);
108 if(preview)
109 if(!(id in frames)){
110 frames[id] = document.createElement('canvas');
111 frames[id].id = id; frames[id].width = 64; frames[id].height = 48;
112 cvresults.append(frames[id]);
113 console.log(frames[id]);
114 }
115 framedata[id] = new cv.Mat(video.height, video.width, cv.CV_8UC4);
116 cap.read(framedata[id]);
117 if(preview)cv.imshow(id, framedata[id]);
118 FPS = 10;
119 let delay = 1000/FPS - (Date.now() - begin);
120 setTimeout(function(){callback(id);}, delay);
121 return id;
122 };
123
124
125 function toGray(id,myid, preview) {
126 if(preview)
127 if(!(myid in frames)){
128 frames[myid] = document.createElement('canvas');
129 frames[myid].id = myid; frames[myid].width = 64; frames[myid].height = 48;
130 cvresults.append(frames[myid]);
131 }
132 let dst = new cv.Mat(video.height, video.width, cv.CV_8UC1);
133 cv.cvtColor(framedata[id], dst, cv.COLOR_RGBA2GRAY);
134 framedata[id] = dst;
135 if(preview)cv.imshow(myid, framedata[id]);
136 return id;
137 };
138
139 function subtractBG(id,myid, preview) {
140 if(preview)
141 if(!(myid in frames)){
142 frames[myid] = document.createElement('canvas');
143 frames[myid].id = myid; frames[myid].width = 64; frames[myid].height = 48;
144 cvresults.append(frames[myid]);
145 }
146 if(!(id in backgrounds)){
147 backgrounds[id] = new cv.BackgroundSubtractorMOG2(500, 16, false);
148 }
149 let fgmask = new cv.Mat(video.height, video.width, cv.CV_8UC1);
150 backgrounds[id].apply(framedata[id],fgmask);
151 cv.bitwise_not(fgmask, fgmask);
152 framedata[id] = fgmask;
153 if(preview)cv.imshow(myid, framedata[id]);
154 return id;
155 };
156
157
158
159 function cv_subtract(id,id2,myid, preview) {
160 if(preview)
161 if(!(myid in frames)){
162 frames[myid] = document.createElement('canvas');
163 frames[myid].id = myid; frames[myid].width = 64; frames[myid].height = 48;
164 cvresults.append(frames[myid]);
165 }
166 let fgmask = new cv.Mat(video.height, video.width, cv.CV_8UC1);
167 let fgbg = new cv.BackgroundSubtractorMOG2(500, 16, true);
168 cv.subtract(framedata[id], framedata[id2], dst, mask, dtype);
169 cv.bitwise_not(dst, dst);
170 framedata[id] = dst;
171 if(preview)cv.imshow(myid, framedata[id]);
172 return id;
173 };
174
175 function getBiggestCircle(id,myid, preview) {
176 if(preview)
177 if(!(myid in frames)){
178 frames[myid] = document.createElement('canvas');
179 frames[myid].id = myid; frames[myid].width = 64; frames[myid].height = 48;
180 cvresults.append(frames[myid]);
181 }
182
183 keypoints = simpleBlobDetector(framedata[id]);
184 msg=[0,0,0];
185 biggest = 0;
186 for (const keypoint of keypoints) {
187 if(keypoint.size > biggest){
188 msg=[keypoint.pt.x,keypoint.pt.y,keypoint.size];
189 biggest = keypoint.size;
190 }
191 }
192 if(preview)
193 if(biggest>0){ // At least one found
194 const center = new cv.Point(msg[0], msg[1])
195 cv.circle(framedata[id], center, msg[2], [255, 0, 0, 255], 3)
196 cv.imshow(myid, framedata[id]);
197 }
198
199 return myInterpreter.nativeToPseudo(msg);
200 };
201
202 function getBlobs(id, myid, preview) {
203 if(preview)
204 if(!(myid in frames)){
205 frames[myid] = document.createElement('canvas');
206 frames[myid].id = myid; frames[myid].width = 64; frames[myid].height = 48;
207 cvresults.append(frames[myid]);
208 }
209
210 keypoints = simpleBlobDetector(framedata[id]);
211 msg=[];
212 for (const keypoint of keypoints) {
213 if(keypoint.size>5){
214 blb=[keypoint.pt.x,keypoint.pt.y,keypoint.size];
215 const center = new cv.Point(blb[0], blb[1])
216 cv.circle(framedata[id], center, blb[2], [0, 0, 0, 255], 2)
217 msg.push(blb);
218 }
219 }
220 if(preview)cv.imshow(myid, framedata[id]);
221 return myInterpreter.nativeToPseudo(msg);
222 };
223 function getLines(id,myid, preview) {
224 if(preview)
225 if(!(myid in frames)){
226 frames[myid] = document.createElement('canvas');
227 frames[myid].id = myid; frames[myid].width = 64; frames[myid].height = 48;
228 cvresults.append(frames[myid]);
229 }
230 const grayScaleImage = framedata[id].clone();
231 console.log('he');
232 let lines = new cv.Mat();
233 let color = new cv.Scalar(255, 0, 0);
234 cv.Canny(grayScaleImage, grayScaleImage, 50, 200, 3);
235 cv.HoughLinesP(grayScaleImage, lines, 1, Math.PI / 180, 2, 0, 0);
236 // draw lines
237 msg = [];
238 for (let i = 0; i < lines.rows; ++i) {
239 let startPoint = new cv.Point(lines.data32S[i * 4], lines.data32S[i * 4 + 1]);
240 let endPoint = new cv.Point(lines.data32S[i * 4 + 2], lines.data32S[i * 4 + 3]);
241 cv.line(framedata[id], startPoint, endPoint, color);
242 msg += [lines.data32S[i * 4], lines.data32S[i * 4 + 1],lines.data32S[i * 4 + 2], lines.data32S[i * 4 + 3] ];
243 }
244 if(preview)cv.imshow(myid, framedata[id]);
245 grayScaleImage.delete(); lines.delete();
246 return msg;
247
248 };
249
250
251 function Utils() { // eslint-disable-line no-unused-vars
252 let self = this;
253
254 const OPENCV_URL = 'cv/opencv4.5.js';
255 this.loadOpenCv = function(onloadCallback) {
256 let script = document.createElement('script');
257 script.setAttribute('async', '');
258 script.setAttribute('type', 'text/javascript');
259 script.addEventListener('load', async () => {
260 if (cv.getBuildInformation)
261 {
262 console.log(cv.getBuildInformation());
263 onloadCallback();
264 }
265 else
266 {
267 // WASM
268 if (cv instanceof Promise) {
269 cv = await cv;
270 console.log(cv.getBuildInformation());
271 onloadCallback();
272 } else {
273 cv['onRuntimeInitialized']=()=>{
274 console.log(cv.getBuildInformation());
275 onloadCallback();
276 }
277 }
278 }
279 });
280 script.addEventListener('error', () => {
281 self.printError('Failed to load ' + OPENCV_URL);
282 });
283 script.src = OPENCV_URL;
284 let node = document.getElementsByTagName('script')[0];
285 node.parentNode.insertBefore(script, node);
286 };
287
288
289 this.printError = function(err) {
290 console.log(err);
291 };
292
293
294 function onVideoCanPlay() {
295 if (self.onCameraStartedCallback) {
296 self.onCameraStartedCallback(self.stream, self.video);
297 }
298 };
299
300 this.startCamera = function(resolution, callback, videoId) {
301
302 const constraints = {
303 'qvga': {width: {exact: 320}, height: {exact: 240}, facingMode: cameraType},
304 'vga': {width: {exact: 640}, height: {exact: 480}}, facingMode: cameraType};
305 let video = document.getElementById(videoId);
306 if (!video) {
307 video = document.createElement('video');
308 }
309
310 let videoConstraint = constraints[resolution];
311 if (!videoConstraint) {
312 videoConstraint = true;
313 }
314
315
316
317 navigator.mediaDevices.getUserMedia({video: videoConstraint, audio: false})
318 .then(function(stream) {
319 video.srcObject = stream;
320 video.play();
321 self.video = video;
322 self.stream = stream;
323 self.onCameraStartedCallback = callback;
324 video.addEventListener('canplay', onVideoCanPlay, false);
325 })
326 .catch(function(err) {
327 self.printError('Camera Error: ' + err.name + ' ' + err.message);
328 });
329 };
330
331 this.stopCamera = function() {
332 if (this.video) {
333 this.video.pause();
334 this.video.srcObject = null;
335 this.video.removeEventListener('canplay', onVideoCanPlay);
336 }
337 if (this.stream) {
338 this.stream.getVideoTracks()[0].stop();
339 }
340 };
341 };
342
343
344 // Port of https://github.com/opencv/opencv/blob/a50a355/modules/features2d/src/blobdetector.cpp
345 // By https://gist.github.com/janpaul123/8b9061d1d093ec0b36dac2230434d34a
346 // But with special `faster` option which has slightly different semantics,
347 // but is a whole bunch faster.
348
349 function diff(v1, v2) {
350 if (v1.x !== undefined) return { x: v1.x - v2.x, y: v1.y - v2.y };
351 return v1.map((value, index) => value - v2[index]);
352 }
353
354 function norm(vector) {
355 if (vector.x !== undefined) return norm([vector.x, vector.y]);
356 return Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0));
357 }
358
359 var defaultParams = {
360 thresholdStep: 10,
361 minThreshold: 20,
362 maxThreshold: 240,
363 minRepeatability: 2,
364 minDistBetweenBlobs: 10,
365
366 filterByColor: true,
367 blobColor: 0,
368
369 filterByArea: true,
370 minArea: 25,
371 maxArea: 5000,
372
373 filterByCircularity: false,
374 minCircularity: 0.8,
375 maxCircularity: 1000000,
376
377 filterByInertia: false,
378 //minInertiaRatio: 0.6,
379 minInertiaRatio: 0.1,
380 maxInertiaRatio: 1000000,
381
382 filterByConvexity: true,
383 //minConvexity: 0.8,
384 minConvexity: 0.90,
385 maxConvexity: 1000000,
386
387 faster: true,
388 };
389
390 function setParam(p, val){
391 defaultParams[p] = val;
392 console.log(defaultParams[p]);
393 }
394
395 function findBlobs(image, binaryImage, params) {
396 const contours = new cv.MatVector();
397 const hierarchy = new cv.Mat();
398 if (params.faster) {
399 cv.findContours(binaryImage, contours, hierarchy, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE);
400 } else {
401 cv.findContours(binaryImage, contours, hierarchy, cv.RETR_LIST, cv.CHAIN_APPROX_NONE);
402 }
403 hierarchy.delete();
404
405 const centers = [];
406 const objectsToDelete = [];
407 for (let i = 0; i < contours.size(); i++) {
408 const contour = contours.get(i);
409 objectsToDelete.push(contour);
410 const area = cv.contourArea(contour);
411
412 if (area == 0) continue;
413
414 let center, moms;
415 if (params.faster) {
416 const { x, y, width, height } = cv.boundingRect(contour);
417 center = {
418 confidence: 1,
419 location: { x: x + width / 2, y: y + height / 2 },
420 radius: (width + height) / 4,
421 };
422 } else {
423 moms = cv.moments(contour);
424 center = {
425 confidence: 1,
426 location: { x: moms.m10 / moms.m00, y: moms.m01 / moms.m00 },
427 };
428 }
429
430 if (params.filterByArea) {
431 if (area < params.minArea || area >= params.maxArea) continue;
432 }
433
434 if (params.filterByCircularity) {
435 const perimeter = cv.arcLength(contour, true);
436 const ratio = 4 * cv.CV_PI * area / (perimeter * perimeter);
437 if (ratio < params.minCircularity || ratio >= params.maxCircularity) continue;
438 }
439
440 if (params.filterByInertia) {
441 if (params.faster) {
442 throw new Error('Cannot both set params.faster and params.filterByInertia');
443 }
444
445 const denominator = Math.sqrt(
446 Math.pow(2 * moms.mu11, 2) + Math.pow(moms.mu20 - moms.mu02, 2)
447 );
448 let ratio;
449 if (denominator > 0.01) {
450 const cosmin = (moms.mu20 - moms.mu02) / denominator;
451 const sinmin = 2 * moms.mu11 / denominator;
452 const cosmax = -cosmin;
453 const sinmax = -sinmin;
454
455 const imin =
456 0.5 * (moms.mu20 + moms.mu02) -
457 0.5 * (moms.mu20 - moms.mu02) * cosmin -
458 moms.mu11 * sinmin;
459 const imax =
460 0.5 * (moms.mu20 + moms.mu02) -
461 0.5 * (moms.mu20 - moms.mu02) * cosmax -
462 moms.mu11 * sinmax;
463 ratio = imin / imax;
464 } else {
465 ratio = 1;
466 }
467
468 if (ratio < params.minInertiaRatio || ratio >= params.maxInertiaRatio) continue;
469
470 center.confidence = ratio * ratio;
471 }
472
473 if (params.filterByConvexity) {
474 const hull = new cv.Mat();
475 cv.convexHull(contour, hull);
476 const hullArea = cv.contourArea(hull);
477 const ratio = area / hullArea;
478 hull.delete();
479 if (ratio < params.minConvexity || ratio >= params.maxConvexity) continue;
480 }
481
482 if (params.filterByColor) {
483 if (
484 binaryImage.ucharAt(Math.round(center.location.y), Math.round(center.location.x)) !=
485 params.blobColor
486 )
487 continue;
488 }
489
490 if (!params.faster) {
491 const dists = [];
492 for (let pointIdx = 0; pointIdx < contour.size().height; pointIdx++) {
493 const pt = contour.intPtr(pointIdx);
494 dists.push(norm(diff(center.location, { x: pt[0], y: pt[1] })));
495 }
496 dists.sort();
497 center.radius =
498 (dists[Math.floor((dists.length - 1) / 2)] + dists[Math.floor(dists.length / 2)]) / 2;
499 }
500
501 centers.push(center);
502 }
503 objectsToDelete.forEach(obj => obj.delete());
504 contours.delete();
505 return centers;
506 }
507
508 function simpleBlobDetector(grayScaleImage, params) {
509 params = { ...defaultParams, ...params };
510
511 let centers = [];
512 for (
513 let thresh = params.minThreshold;
514 thresh < params.maxThreshold;
515 thresh += params.thresholdStep
516 ) {
517 const binaryImage = new cv.Mat(grayScaleImage.rows, grayScaleImage.cols, cv.CV_8UC1);
518 cv.threshold(grayScaleImage, binaryImage, thresh, 255, cv.THRESH_BINARY);
519 let curCenters = findBlobs(grayScaleImage, binaryImage, params);
520 binaryImage.delete();
521 let newCenters = [];
522
523 for (let i = 0; i < curCenters.length; i++) {
524 let isNew = true;
525 for (let j = 0; j < centers.length; j++) {
526 const dist = norm(
527 diff(centers[j][Math.floor(centers[j].length / 2)].location, curCenters[i].location)
528 );
529 isNew =
530 dist >= params.minDistBetweenBlobs &&
531 dist >= centers[j][Math.floor(centers[j].length / 2)].radius &&
532 dist >= curCenters[i].radius;
533 if (!isNew) {
534 centers[j].push(curCenters[i]);
535
536 let k = centers[j].length - 1;
537 while (k > 0 && centers[j][k].radius < centers[j][k - 1].radius) {
538 centers[j][k] = centers[j][k - 1];
539 k--;
540 }
541 centers[j][k] = curCenters[i];
542 break;
543 }
544 }
545 if (isNew) newCenters.push([curCenters[i]]);
546 }
547 centers = centers.concat(newCenters);
548 }
549
550 //grayScaleImage.delete();
551
552 const keyPoints = [];
553 for (let i = 0; i < centers.length; i++) {
554 if (centers[i].length < params.minRepeatability) continue;
555 const sumPoint = { x: 0, y: 0 };
556 let normalizer = 0;
557 for (let j = 0; j < centers[i].length; j++) {
558 sumPoint.x += centers[i][j].confidence * centers[i][j].location.x;
559 sumPoint.y += centers[i][j].confidence * centers[i][j].location.y;
560 normalizer += centers[i][j].confidence;
561 }
562 sumPoint.x *= 1 / normalizer;
563 sumPoint.y *= 1 / normalizer;
564 let size = Math.round(centers[i][Math.floor(centers[i].length / 2)].radius * 2);
565 size = Math.min(
566 size,
567 sumPoint.x * 2,
568 sumPoint.y * 2,
569 (grayScaleImage.cols - sumPoint.x) * 2,
570 (grayScaleImage.rows - sumPoint.y) * 2
571 );
572 keyPoints.push({ pt: sumPoint, size });
573 }
574
575 return keyPoints;
576 }
577
578
579
580
581 /*---Start the camera----*/
582 Blockly.Blocks['start_camera'] = {
583 init: function() {
584 this.appendDummyInput()
585 .appendField("Start Camera(Beta)")
586 .appendField(new Blockly.FieldDropdown([["FRONT","user"],["BACK","environment"]]), "CAMERA");
587 this.setPreviousStatement(true, null);
588 this.setNextStatement(true, null);
589 this.setColour(52);
590 this.setTooltip("Start Camera");
591 this.setHelpUrl("");
592 }
593 };
594
595
596
597 Blockly.JavaScript['start_camera'] = function(block) {
598 var cam = block.getFieldValue("CAMERA");
599 var code = "startCV('"+cam+"');\n";
600 return code;
601 };
602
603
604 Blockly.Python['start_camera'] = function(block) {
605 var code = '# Camera Not implemented in Python\n';
606 return code;
607 };
608
609 /*---Start the camera----*/
610 Blockly.Blocks['choose_blob_shade'] = {
611 init: function() {
612 this.appendDummyInput()
613 .appendField("Blob Colour is ")
614 .appendField(new Blockly.FieldDropdown([["BLACK","0"],["WHITE","1"]]), "SHADE");
615 this.setPreviousStatement(true, null);
616 this.setNextStatement(true, null);
617 this.setColour(52);
618 this.setTooltip("Start Camera");
619 this.setHelpUrl("");
620 }
621 };
622
623 Blockly.JavaScript['choose_blob_shade'] = function(block) {
624 var shade = block.getFieldValue("SHADE");
625 var code = "set_param('blobColor',"+parseInt(shade)+");\n";
626 return code;
627 };
628
629 Blockly.Python['choose_blob_shade'] = function(block) {
630 var code = '';
631 return code;
632 };
633
634
635 Blockly.Blocks['get_frame'] = {
636 init: function() {
637 this.appendDummyInput()
638 .appendField("Get Frame");
639 this.appendDummyInput()
640 .appendField(new Blockly.FieldCheckbox("FALSE"), "PREVIEW")
641 .appendField("Preview");
642 this.setOutput(true);
643 this.setColour(52);
644 this.setTooltip("Get a single frame from the camera");
645 this.setInputsInline(false);
646 this.setHelpUrl("");
647 }
648 };
649
650
651
652 Blockly.JavaScript['get_frame'] = function(block) {
653 var pv = block.getFieldValue('PREVIEW')=='TRUE' ? true:false;
654 console.log(block.id);
655 var code = "get_frame('"+block.id+"',"+pv+")";
656 return [code,Blockly.JavaScript.ORDER_NONE];
657 };
658 Blockly.Python['get_frame'] = function(block) { return '# Camera Not implemented in Python\n'; };
659
660 // To Grayscale
661 Blockly.Blocks['to_gray'] = {
662 init: function() {
663 this.appendValueInput("ID")
664 .appendField("To Grayscale. Frame:");
665 this.appendDummyInput()
666 .appendField(new Blockly.FieldCheckbox("FALSE"), "PREVIEW")
667 .appendField("Preview");
668 this.setOutput(true);
669 this.setColour(52);
670 this.setInputsInline(false);
671 this.setTooltip("convert frame to gray");
672 this.setHelpUrl("");
673 }
674 };
675
676 Blockly.JavaScript['to_gray'] = function(block) {
677 var id = Blockly.JavaScript.valueToCode(block, 'ID', Blockly.JavaScript.ORDER_NONE);
678 var pv = block.getFieldValue('PREVIEW')=='TRUE' ? true:false;
679 var code = "to_gray("+id+",'"+block.id+"',"+pv+")";
680 return [code,Blockly.JavaScript.ORDER_NONE];
681 };
682 Blockly.Python['to_gray'] = function(block) { return ''; };
683
684 // Subtract Background
685 Blockly.Blocks['subtract_bg'] = {
686 init: function() {
687 this.appendValueInput("ID")
688 .appendField("Subtract Background from:");
689 this.appendDummyInput()
690 .appendField("MOG2 Algorithm");
691 this.appendDummyInput()
692 .appendField(new Blockly.FieldCheckbox("FALSE"), "PREVIEW")
693 .appendField("Preview");
694 this.setOutput(true);
695 this.setColour(52);
696 this.setInputsInline(false);
697 this.setTooltip("subtract background");
698 this.setHelpUrl("");
699 }
700 };
701
702 Blockly.JavaScript['subtract_bg'] = function(block) {
703 var id = Blockly.JavaScript.valueToCode(block, 'ID', Blockly.JavaScript.ORDER_NONE);
704 var pv = block.getFieldValue('PREVIEW')=='TRUE' ? true:false;
705 var code = "subtract_bg("+id+",\""+block.id+"\","+pv+")";
706 return [code,Blockly.JavaScript.ORDER_NONE];
707 };
708 Blockly.Python['subtract_bg'] = function(block) { return ''; };
709
710 // SUBTRACT FRAMES
711 Blockly.Blocks['cv_subtract'] = {
712 init: function() {
713 this.appendValueInput("ID")
714 .appendField("From Frame1:");
715 this.appendValueInput("ID2")
716 .appendField("Subtract Frame2:");
717 this.appendDummyInput()
718 .appendField("Store mask to Frame1");
719 this.appendDummyInput()
720 .appendField(new Blockly.FieldCheckbox("FALSE"), "PREVIEW")
721 .appendField("Preview");
722 this.setOutput(true);
723 this.setColour(52);
724 this.setInputsInline(false);
725 this.setTooltip("Background Subtraction");
726 this.setHelpUrl("");
727 }
728 };
729
730 Blockly.JavaScript['cv_subtract'] = function(block) {
731 var id = Blockly.JavaScript.valueToCode(block, 'ID', Blockly.JavaScript.ORDER_NONE);
732 var id2 = Blockly.JavaScript.valueToCode(block, 'ID2', Blockly.JavaScript.ORDER_NONE);
733 var pv = block.getFieldValue('PREVIEW')=='TRUE' ? true:false;
734 var code = "cv_subtract("+id+","+id2+",'"+block.id+"',"+pv+")";
735 return [code,Blockly.JavaScript.ORDER_NONE];
736 };
737 Blockly.Python['cv_subtract'] = function(block) { return ''; };
738
739
740
741 // GET BLOBS
742 Blockly.Blocks['get_blobs'] = {
743 init: function() {
744 this.appendValueInput("ID")
745 .appendField("Get Blobs. Frame: ");
746 this.appendDummyInput()
747 .appendField(new Blockly.FieldCheckbox("FALSE"), "PREVIEW")
748 .appendField("Preview");
749 this.setOutput(true, null);
750 this.setColour(52);
751 this.setTooltip("get blobs");
752 this.setInputsInline(false);
753 this.setHelpUrl("");
754 }
755 };
756
757 Blockly.JavaScript['get_blobs'] = function(block) {
758 var id = Blockly.JavaScript.valueToCode(block, 'ID', Blockly.JavaScript.ORDER_NONE);
759 var pv = block.getFieldValue('PREVIEW')=='TRUE' ? true:false;
760 var code = "get_blobs("+id+",\""+block.id+"\","+pv+")";
761 return [code,Blockly.JavaScript.ORDER_NONE];
762 };
763 Blockly.Python['get_blobs'] = function(block) { return ['', Blockly.Python.ORDER_NONE]; };
764
765
766 Blockly.Blocks['get_biggest_circle'] = {
767 init: function() {
768 this.appendValueInput("ID")
769 .appendField("Biggest Circle: ");
770 this.appendDummyInput()
771 .appendField(new Blockly.FieldCheckbox("FALSE"), "PREVIEW")
772 .appendField("Preview");
773 this.appendDummyInput()
774 .appendField("Returns X,Y,Radius");
775 this.setOutput(true, null);
776 this.setColour(52);
777 this.setTooltip("get circle");
778 this.setInputsInline(false);
779 this.setHelpUrl("");
780 }
781 };
782
783
784
785 Blockly.JavaScript['get_biggest_circle'] = function(block) {
786 var id = Blockly.JavaScript.valueToCode(block, 'ID', Blockly.JavaScript.ORDER_NONE);
787 var pv = block.getFieldValue('PREVIEW')=='TRUE' ? true:false;
788 var code = "get_biggest_circle("+id+",\""+block.id+"\","+pv+")";
789 return [code,Blockly.JavaScript.ORDER_NONE];
790 };
791 Blockly.Python['get_biggest_circle'] = function(block) { return ['', Blockly.Python.ORDER_NONE]; };
792
793
794 Blockly.Blocks['get_lines'] = {
795 init: function() {
796 this.appendValueInput("ID")
797 .appendField("Get Lines ");
798 this.appendDummyInput()
799 .appendField(new Blockly.FieldCheckbox("FALSE"), "PREVIEW")
800 .appendField("Preview");
801 this.setOutput(true, null);
802 this.setColour(52);
803 this.setTooltip("get lines");
804 this.setInputsInline(false);
805 this.setHelpUrl("");
806 }
807 };
808
809
810
811 Blockly.JavaScript['get_lines'] = function(block) {
812 var id = Blockly.JavaScript.valueToCode(block, 'ID', Blockly.JavaScript.ORDER_NONE);
813 var pv = block.getFieldValue('PREVIEW')=='TRUE' ? true:false;
814 var code = "get_lines("+id+",\""+block.id+"\","+pv+")";
815 return [code,Blockly.JavaScript.ORDER_NONE];
816 };
817 Blockly.Python['get_lines'] = function(block) { return ['', Blockly.Python.ORDER_NONE]; };
818
819
820
821 function initCV(interpreter, scope) {
822
823 interpreter.setProperty(scope, 'startCV', interpreter.createAsyncFunction(
824 function(cam,callback) {
825 startCV(cam,callback);
826 })
827 );
828
829 interpreter.setProperty(scope, 'get_frame', interpreter.createAsyncFunction(
830 function(id,preview,callback) {
831 return getFrame(id,preview, callback);
832 })
833 );
834 interpreter.setProperty(scope, 'set_param', interpreter.createNativeFunction(
835 function(p,val) {
836 return setParam(p,val);
837 })
838 );
839
840 interpreter.setProperty(scope, 'to_gray', interpreter.createNativeFunction(
841 function(id,myid,preview) {
842 return toGray(id,myid,preview);
843 })
844 );
845 interpreter.setProperty(scope, 'subtract_bg', interpreter.createNativeFunction(
846 function(id,myid,preview) {
847 return subtractBG(id,myid,preview);
848 })
849 );
850 interpreter.setProperty(scope, 'cv_subtract', interpreter.createNativeFunction(
851 function(id,id2,myid,preview) {
852 return cv_subtract(id,id2, myid,preview);
853 })
854 );
855 interpreter.setProperty(scope, 'get_lines', interpreter.createNativeFunction(
856 function(id,myid,preview) {
857 return getLines(id,myid,preview);
858 })
859 );
860 interpreter.setProperty(scope, 'get_blobs', interpreter.createNativeFunction(
861 function(id, myid,preview) {
862 return getBlobs(id, myid,preview);
863 })
864 );
865
866 interpreter.setProperty(scope, 'get_biggest_circle', interpreter.createNativeFunction(
867 function(id,myid,preview) {
868 return getBiggestCircle(id,myid,preview);
869 })
870 );
871
872 }
873
874
875
876
877
878
879
880
881
882