// FILE: scilabHelloVision1_1b.sce - Works!
// DATE: 02/07/20 11:54
// AUTH: P.Oh
// REFS: video_capture.dem.sce in Scilab (may need install of image tools)
//       Scilab Computer Vision Module (scicv) is the Scilab interface to the 
//       OpenCV library https://atoms.scilab.org/toolboxes/scicv/0.3
// VERS: 1.0a: Simply displays what the webcam sees
//       1.1a: Add a 2nd window to also display what the webcam sees
//             Requires using subplot to have 2 images
//       1.1b: Attempt grey-scale displays
// DESC: Display what USB webcam sees


// (1) initialize the Scilab Computer Vision Module
scicv_Init(); 

// (2) Get ID of the webcam (assumes only 1 webcam connected)
videoCapture = new_VideoCapture(0); 

// (3) Set up a current graphic figure (window) - which will display our video

f = scf(0); 

// (4) Make window pretty
// uicontrol allows one to write text in figure with Background color and position 
// Values used sets white background approximately centered below frame 
 
// uicontrol(f, "string", "Input", "backgroundColor", [1,1,1], "position", [100,40,320,20]);
// uicontrol(g, "string", "Output", "backgroundColor", [1,1,1], "position", [100,40,320,20]);

// (5) Endless loop that grabs frame, displays it, and repeats
while is_handle_valid(f)

    [ret, frame] = VideoCapture_read(videoCapture); // grab and return a frame
  
    if is_handle_valid(f) then      
        // ret is TRUE, so display frame
        subplot(1,3,1); // Set up 1 row and 2 columns of sub-plots.  Draw in Plot 1
        matplot(frame);

        // Draw in Plot 2: Grey-scale version of RGB color frame
        greyFrame = cvtColor(frame, CV_BGR2GRAY);
        subplot(1,3,2);
        matplot(greyFrame);

        // Draw in Plot 3
        // thresholded frame
        // THRESH_BINARY
        // THRESH_BINARY_INV
        thresholdValue = 50; // 0 (whiter stuff becomes white) and 255 (blacker stuff becomes black)
        [thresh, thresholdedFrame]  = threshold(greyFrame, thresholdValue, 255, THRESH_BINARY);
        subplot(1,3,3);
        matplot(thresholdedFrame);
    end // end if  
end // end while

delete("all"); // kill all frames
