“Photo finish” with HTML5 and webcam

Few days ago, I was looking with my colleagues at the results of second etape of Tour de France. I was wondering how they take “finish picture”.

ASSOCIATED PRESS/ASO

ASSOCIATED PRESS/ASO

After a little bit of googling we found out that there is really simple idea behind it.

So after few hours of coding I created simple HTML5 version of a photo finish that uses webcam.


Try it here

You need to:

  • allow webcam acces
  • click on preview
  • press play
  • move something (at reasonable speed = very very slow) in front of webcam
  • wait for results šŸ™‚

Principe is really simple. I just take a vertical line of pixels (with getUserMedia) and append this line to a picture (canvas).
Just look in the source codes and you will find out how simple it is. Basically you need to look on “draw” function:

//counter for "frame"
var cols = 0;
//line width
var size = 1;
function draw(cb) {
    //draw temporary image from video
    context.drawImage(video, 0, 0, width, height);
    //Get vertical line of pixels (center of webcam video)
    var snapshot = context.getImageData(width / 2, 0, size, height);
    //move image to right
    var oldImage = contextDest.getImageData(0, 0, width, height);
    contextDest.putImageData(oldImage, size, 0);
    //prepend this line to image
    contextDest.putImageData(snapshot, 0, 0);
    //increment "frame" cols counter
    cols += size;
    //if count of cols is the same as image width than save this frame
    if (cols >= width) {
        //convert image to base64 string
        var url = canvasDest.toDataURL("image/png");
        //create image from base64 string
        var newImg = $('<img alt="" />');
        newImg.attr('class', 'result');
        newImg.attr('src', url);
        //append to rersults
        $('#results').prepend(newImg);
        newImg = null;
        //reset "frame" counter
        cols = 0;
    }
}

It is just a fun project so don’t expect results like from Tour de France. The webcam is running at 30 FPS so it can not detect fast moving objects (like cyclists) but if you areĀ organisingĀ snail raceĀ it should work.

Reason why I created this was that I’mĀ planningĀ to orderĀ RaspberryĀ Pi and I was thinking that photo finish will be a nice first project on Raspberry Pi.


View source code on github.com

All code is open source and dual licensed under GPL and MIT. Feel free to use it.
If you have any question feel free to ask.

4 thoughts on ““Photo finish” with HTML5 and webcam

  1. Bernard Barrois

    I use “CL-Eye Test DirectShow ” and Code Labratories pilote vesrion 5.3.0.341 (2012) to connect the Eye.
    But i don’t no how tochange the rate in HTML5 page and do a “photofinish du pauvre” (a low cost photofinish) for our FabLabFest.
    Thanks for help.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *