<jupyter_start><jupyter_text><jupyter_code>from IPython.display import display, Javascript
from google.colab.output import eval_js
from base64 import b64decode

def take_photo(filename='photo.jpg', quality=0.8):
  js = Javascript('''
    async function takePhoto(quality) {
      const div = document.createElement('div');
      const capture = document.createElement('button');
      capture.textContent = 'Capture';
      div.appendChild(capture);

      const video = document.createElement('video');
      video.style.display = 'block';
      const stream = await navigator.mediaDevices.getUserMedia({video: true});

      document.body.appendChild(div);
      div.appendChild(video);
      video.srcObject = stream;
      await video.play();

      // Resize the output to fit the video element.
      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);

      // Wait for Capture to be clicked.
        

      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas.getContext('2d').drawImage(video, 0, 0);
      stream.getVideoTracks()[0].stop();
      div.remove();
      return canvas.toDataURL('image/jpeg', quality);
    }
    ''')
  display(js)
  data = eval_js('takePhoto({})'.format(quality))
  binary = b64decode(data.split(',')[1])
  with open(filename, 'wb') as f:
    f.write(binary)
  return filename
from IPython.display import Image
try:
  filename = take_photo()
  print('Saved to {}'.format(filename))
  
  # Show the image which was just taken.
  display(Image(filename))
except Exception as err:
  # Errors will be thrown if the user does not have a webcam or if they do not
  # grant the page permission to access it.
  print(str(err))
import cv2
import sys

(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')￼

if __name__ == '__main__' :

    # Set up tracker.
    # Instead of MIL, you can also use

    tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']
    tracker_type = tracker_types[2]

    if int(minor_ver) < 3:
        tracker = cv2.Tracker_create(tracker_type)
    else:
        if tracker_type == 'BOOSTING':
            tracker = cv2.TrackerBoosting_create()
        if tracker_type == 'MIL':
            tracker = cv2.TrackerMIL_create()
        if tracker_type == 'KCF':
            tracker = cv2.TrackerKCF_create()
        if tracker_type == 'TLD':
            tracker = cv2.TrackerTLD_create()
        if tracker_type == 'MEDIANFLOW':
            tracker = cv2.TrackerMedianFlow_create()
        if tracker_type == 'GOTURN':
            tracker = cv2.TrackerGOTURN_create()
        if tracker_type == 'MOSSE':
            tracker = cv2.TrackerMOSSE_create()
        if tracker_type == "CSRT":
            tracker = cv2.TrackerCSRT_create()

    # Read video
    video = cv2.VideoCapture("videos/chaplin.mp4")

    # Exit if video not opened.
    if not video.isOpened():
        print "Could not open video"
        sys.exit()

    # Read first frame.
    ok, frame = video.read()
    if not ok:
        print 'Cannot read video file'
        sys.exit()
    
    # Define an initial bounding box
    bbox = (287, 23, 86, 320)

    # Uncomment the line below to select a different bounding box
    bbox = cv2.selectROI(frame, False)

    # Initialize tracker with first frame and bounding box
    ok = tracker.init(frame, bbox)

    while True:
        # Read a new frame
        ok, frame = video.read()
        if not ok:
            break
        
        # Start timer
        timer = cv2.getTickCount()

        # Update tracker
        ok, bbox = tracker.update(frame)

        # Calculate Frames per second (FPS)
        fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);

        # Draw bounding box
        if ok:
            # Tracking success
            p1 = (int(bbox[0]), int(bbox[1]))
            p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
            cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
        else :
            # Tracking failure
            cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)

        # Display tracker type on frame
        cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
    
        # Display FPS on frame
        cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);

        # Display result
        cv2.imshow("Tracking", frame)

        # Exit if ESC pressed
        k = cv2.waitKey(1) & 0xff
        if k == 27 : break

from IPython.display import HTML, Image
from google.colab.output import eval_js
from base64 import b64decode
from PIL import Image

html_canvas = """
<canvas id="canvas"></canvas>
<button id="capture">Capture</button>
<script>
var canvas = document.getElementById('canvas');
var width = %d;
var height = %d;
canvas.style.width = width+'px';
canvas.style.height = height+'px';
var ctx = canvas.getContext('2d');
ctx.canvas.width = width;
ctx.canvas.height = height;
var base_image = new Image();
base_image.src = '%s';
base_image.width = width+'px';
base_image.height = height+'px';
base_image.onload = function(){
  ctx.drawImage(base_image,0,0,width,height);
}
initDraw(canvas,ctx);
var x,y,width,height;
function initDraw(canvas,ctx) {
    function setMousePosition(e) {
        var ev = e || window.event; //Moz || IE
        if (ev.pageX) { //Moz
            mouse.x = ev.pageX + window.pageXOffset;
            mouse.y = ev.pageY + window.pageYOffset;
        } else if (ev.clientX) { //IE
            mouse.x = ev.clientX + document.body.scrollLeft;
            mouse.y = ev.clientY + document.body.scrollTop;
        }
    };

    var mouse = {
        x: 0,
        y: 0,
        startX: 0,
        startY: 0
    };
    var left=null,top=null,width=0,height=0;
    canvas.onmousemove = function (e) {
        setMousePosition(e);
        if (left !== null) {
            ctx.clearRect(0,0,canvas.width,canvas.height);
            ctx.drawImage(base_image,0,0,canvas.width,canvas.height);
            width = Math.abs(mouse.x - mouse.startX);
            height = Math.abs(mouse.y - mouse.startY);
            left = (mouse.x - mouse.startX < 0) ? mouse.x : mouse.startX;
            top = (mouse.y - mouse.startY < 0) ? mouse.y : mouse.startY;
            ctx.beginPath();
            ctx.lineWidth = "3";
            ctx.strokeStyle = "yellow";
            ctx.strokeRect(left, top, width, height);
            console.log(left,top,width,height);
            
            ctx.stroke();
        }
    }

    canvas.onclick = function (e) {
        if (left !== null) {
            window.x = left;
            window.y = top;
            window.width = width;
            window.height = height;
            left = null;
            canvas.style.cursor = "default";
            console.log("finsihed.");
        } else {
            console.log("begun.");
            mouse.startX = mouse.x;
            mouse.startY = mouse.y;
            left = mouse.x;
            top = mouse.y;
            canvas.style.cursor = "crosshair";
        }
    }
    
    
}
var button = document.getElementById('capture');
var data = new Promise(resolve=>{
  button.onclick = ()=>{
    resolve([x,y,width,height]);
  }
});
</script>
"""

def selectROI(filename='1.jpg', w=400, h=200, line_width=1):
  img = Image.open('/usr/local/share/jupyter/nbextensions/{}'.format(filename))
  display(HTML(html_canvas%(img.size[0],img.size[1],'/nbextensions/{}'.format(filename))))
  data = eval_js("data")
  return tuple(data)
selectROI()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13500906970717802, 'fraction_numerical': 0.019175952319253693, 'mean_word_length': 2.432192085371276, 'pattern_counts': {'":': 1, '<': 14, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '604642', 'license': 'MIT', 'n_tokens_mistral': 2595, 'n_tokens_neox': 2475, 'n_words': 575, 'path': 'colab_SelectROI.ipynb', 'repo_name': 'sbh69840/google-colab-selectROI', 'size': '7718'}