HTML5 mobile camera capture - javascript

I would like to do the mobile camera capture by HTML5 like this
I have try to use below method but it needs to click somewhere for opening the camera that mean I could not preview the image in live.
<input id="fileselect" type="file" accept="image/*" capture="camera">
I also found the other method which is used a function called "getUserMedia" but it is not support on IOS8.
So how can I implement the mobile camera capture with HTML5?
Please help.

Below is a simple example of use of HTML5 to put a video viewer on the screen that also allows you to capture still images.
It has been tested on Chrome Version 40.0.2214.93 or later.
It has been done in an MVC app. If your replace the markup in your Index.cshtml with this code it should run OK. The only other dependency is the jquery.
#{
ViewBag.Title = "Home Page";
}
<style>
.videostream, #cssfilters-stream, #screenshot {
width: 307px;
height: 250px;
}
.videostream, #cssfilters-stream {
background: rgba(255,255,255,0.5);
border: 1px solid #ccc;
}
#screenshot {
vertical-align: top;
}
</style>
<div style="text-align:center;">
#*<div style="text-align:center;">*#
<div style="float:left;">
<video id="basic-stream" class="videostream" autoplay></video>
<p><button id="capture-button">Capture video</button></p>
</div>
<div style="float:left; padding-left:20px;">
<button id="SaveImageBtn" style="vertical-align:top; margin-top:100px; margin-right:20px;">Save -></button>
<canvas id="outputCanvas" class="videostream"></canvas>
</div>
</div>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script>
var video = document.querySelector('#basic-stream');
var button = document.querySelector('#capture-button');
var localMediaStream = null;
var canvas = document.querySelector('outputCanvas');
$(document).ready(function () {
$("#capture-button").click(function () {
RunIt();
});
$("#SaveImageBtn").click(function () {
var cvs = $("#outputCanvas")[0];
var ctx = cvs.getContext('2d');
ctx.drawImage(video, 0, 0, 300, 150);
console.log("Got here 01");
});
var videoObj = {"video": true};
var errBack = function (error) { alert("An error");};
function RunIt() {
navigator.webkitGetUserMedia(
{ "video": true, "audio": true },
function (s) {
video.src =
window.webkitURL.createObjectURL(s);
video.controls = true;
localMediaStream = s;
video.play();
},
function (e) { console.log(e); }
);
};
});
</script>

Try using some placeholder image.

Related

Playing two different ads with IMA and Shaka Player

I have a simple setup where I have two buttons and a <video> element. I am using Shaka player to play an adaptive DASH file. I am also using Google's IMA Ads SDK to play ads along with the video.
The expected outcome is that when I press button 1, I should see the pre-roll 1 followed by video 1. When I press button 2, I should see the pre-roll 2 followed by video 2.
However, after clicking any button, the ad plays only once. If I toggle the buttons, the ads do not play thereafter. Am I missing anything here? Or do we need to somehow clear the ads request before making another request.
const adUrl1 = "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpreonly&ciu_szs=300x250%2C728x90&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=";
const adUrl2 = "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpremidpost&ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&cmsid=496&vid=short_onecue&correlator=";
const manifestUrl1 = "https://storage.googleapis.com/wvmedia/clear/h264/tears/tears.mpd";
const manifestUrl2 = "https://storage.googleapis.com/shaka-demo-assets/angel-one/dash.mpd";
let player, ui, video, controls, adManager;
async function initApp() {
shaka.polyfill.installAll();
if (shaka.Player.isBrowserSupported()) {
// When using the UI, the player is made automatically by the UI object.
video = document.getElementById('video');
ui = video['ui'];
controls = ui.getControls();
player = controls.getPlayer();
// Listen for error events.
player.addEventListener('error', onPlayerErrorEvent);
// controls.addEventListener('error', onUIErrorEvent);
adManager = player.getAdManager();
// Attach player and ui to the window to make it easy to access in the JS console.
window.player = player;
window.ui = ui;
window.video = video;
window.controls = controls;
window.adManager = adManager;
} else {
console.error("Browser not supported");
}
}
function initializeAdManager() {
const container = ui.getControls().getClientSideAdContainer();
adManager.initClientSide(container, video);
}
function onError(error) {
// Log the error.
console.error('Error code', error.code, 'object', error);
}
async function playAd1() {
console.log('playing Video with ads 1');
initializeAdManager();
fetchAd(adUrl1);
await playVideo(manifestUrl1);
}
async function playAd2() {
console.log('playing video with ads 2');
initializeAdManager();
fetchAd(adUrl2);
await playVideo(manifestUrl2);
}
async function playVideo(url) {
try {
await player.load(url);
} catch (e) {
onError(e);
}
}
function fetchAd(url) {
const adRequest = new google.ima.AdsRequest();
adRequest.adTagUrl = url;
adManager.requestClientSideAds(adRequest);
}
function onPlayerErrorEvent(errorEvent) {
// Extract the shaka.util.Error object from the event.
onPlayerError(errorEvent.detail);
}
function onPlayerError(error) {
// Handle player error
console.error('Error code', error.code, 'object', error);
}
function onUIErrorEvent(errorEvent) {
// Extract the shaka.util.Error object from the event.
onPlayerError(errorEvent.detail);
}
document.addEventListener('shaka-ui-loaded', initApp);
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-type"/>
<title id="sample_app_page_title">Ad Ping</title>
<!--for UI builds: -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/shaka-player/4.3.0/shaka-player.ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/shaka-player/4.3.0/controls.min.css" rel="stylesheet">
<!-- IMA HTML5 SDK (for serving Client Side ads): -->
<script src="https://imasdk.googleapis.com/js/sdkloader/ima3.js" type="text/javascript"></script>
</head>
<body>
<button onclick="playAd1()">Play Video with Ad1</button>
<button onclick="playAd2()">Play Video with Ad2</button>
<div>
<div data-shaka-player-cast-receiver-id="8D8C71A7" data-shaka-player-container>
<video data-shaka-player controls autoplay id="video" style="width:400px; height:200px" />
</div>
</div>
Figured the answer. Please check the following snippet to see this in action.
// Copyright 2013 Google Inc. All Rights Reserved.
// You may study, modify, and use this example for any purpose.
// Note that this example is provided "as is", WITHOUT WARRANTY
// of any kind either expressed or implied.
var adsManager;
var adsLoader;
var adDisplayContainer = document.getElementById('adContainer');
var intervalTimer;
var videoContent = document.getElementById('contentElement');
var testButton1 = document.getElementById('playButton');
var testButton2 = document.getElementById('testButton');
const adUrl1 = "https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dskippablelinear&correlator=";
var adUrl2 = "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpreonly&ciu_szs=300x250%2C728x90&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=";
const video1 = "https://storage.googleapis.com/gvabox/media/samples/stock.mp4";
const video2 = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
function init() {
testButton1.addEventListener('click', function(e){
e.preventDefault();
videoContent.setAttribute('src', video1);
requestAds(adUrl1);
});
testButton2.addEventListener('click', function(e) {
e.preventDefault();
videoContent.setAttribute('src', video2);
requestAds(adUrl2);
});
}
function setUpIMA() {
// Create the ad display container.
createAdDisplayContainer();
videoContent.load();
adDisplayContainer.initialize();
// Create ads loader.
adsLoader = new google.ima.AdsLoader(adDisplayContainer);
// Listen and respond to ads loaded and error events.
adsLoader.addEventListener(
google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
onAdsManagerLoaded,
false);
adsLoader.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
onAdError,
false);
}
function createAdDisplayContainer() {
// We assume the adContainer is the DOM id of the element that will house
// the ads.
adDisplayContainer = new google.ima.AdDisplayContainer(
document.getElementById('adContainer'), videoContent);
}
function onAdsManagerLoaded(adsManagerLoadedEvent) {
// Get the ads manager.
var adsRenderingSettings = new google.ima.AdsRenderingSettings();
adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true;
///adsRenderingSettings.AUTO_SCALE;
//console.log(typeof(auto));
//console.log(AUTO_SCALE);
// videoContent should be set to the content video element.
adsManager = adsManagerLoadedEvent.getAdsManager(
videoContent, adsRenderingSettings);
// Add listeners to the required events.
adsManager.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
onAdError);
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
onContentPauseRequested);
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
onContentResumeRequested);
adsManager.addEventListener(
google.ima.AdEvent.Type.ALL_ADS_COMPLETED,
onAdEvent);
// Listen to any additional events, if necessary.
adsManager.addEventListener(
google.ima.AdEvent.Type.LOADED,
onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.STARTED,
onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.COMPLETE,
onAdEvent);
try {
// Initialize the ads manager. Ad rules playlist will start at this time.
adsManager.init(adsRenderingSettings.AUTO_SCALE, adsRenderingSettings.AUTO_SCALE, google.ima.ViewMode.NORMAL);
//console.log("size change");
adsManager.resize(640,360, google.ima.ViewMode.NORMAL);
// Call play to start showing the ad. Single video and overlay ads will
// start at this time; the call will be ignored for ad rules.
adsManager.start();
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
videoContent.play();
}
}
function onAdEvent(adEvent) {
// Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
// don't have ad object associated.
var ad = adEvent.getAd();
switch (adEvent.type) {
case google.ima.AdEvent.Type.LOADED:
// This is the first event sent for an ad - it is possible to
// determine whether the ad is a video ad or an overlay.
if (!ad.isLinear()) {
// Position AdDisplayContainer correctly for overlay.
// Use ad.width and ad.height.
videoContent.play();
}
break;
case google.ima.AdEvent.Type.STARTED:
if (ad.isLinear()) {
// For a linear ad, a timer can be started to poll for
// the remaining time.
intervalTimer = setInterval(
function() {
var remainingTime = adsManager.getRemainingTime();
},
300); // every 300ms
//console.log(intervalTimer);
//if(intervalTimer == )
}
break;
case google.ima.AdEvent.Type.COMPLETE:
// This event indicates the ad has finished - the video player
// can perform appropriate UI actions, such as removing the timer for
// remaining time detection.
if (ad.isLinear()) {
clearInterval(intervalTimer);
}
break;
}
}
function requestAds(url){
setUpIMA();
if (adsManager) {
//console.log(adsManager);
adsManager.destroy();
//adsManager = null;
//console.log(adsManager);
}
var adsRequest = new google.ima.AdsRequest();
adsRequest.adTagUrl = url;
// Specify the linear and nonlinear slot sizes. This helps the SDK to
// select the correct creative if multiple are returned.
adsRequest.linearAdSlotWidth = 640;
adsRequest.linearAdSlotHeight = 400;
adsRequest.nonLinearAdSlotWidth = 640;
adsRequest.nonLinearAdSlotHeight = 150;
//log("adsRequest: " + tag);
adsLoader.requestAds(adsRequest);
}
function onAdError(adErrorEvent) {
// Handle the error logging.
console.log(adErrorEvent.getError());
adsManager.destroy();
alert('error in VAST response');
}
function onContentPauseRequested() {
videoContent.pause();
// This function is where you should setup UI for showing ads (e.g.
// display ad timer countdown, disable seeking etc.)
// setupUIForAds();
}
function onContentResumeRequested() {
videoContent.play();
// This function is where you should ensure that your UI is ready
// to play content. It is the responsibility of the Publisher to
// implement this function when necessary.
// setupUIForContent();
}
// Wire UI element references and UI event listeners.
init();
#mainContainer {
position: relative;
width: 640px;
height: 360px;
}
#content, #adContainer {
position: absolute;
top: 0px;
left: 0px;
width: 640px;
height: 360px;
}
#contentElement {
width: 640px;
height: 360px;
overflow: hidden;
}
#playButton, #testButton{
margin-top:10px;
vertical-align: top;
width: 350px;
height: 60px;
padding: 0;
font-size: 22px;
color: white;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
background: #2c3e50;
border: 0;
border-bottom: 2px solid #22303f;
cursor: pointer;
-webkit-box-shadow: inset 0 -2px #22303f;
box-shadow: inset 0 -2px #22303f;
}
<script src="https://imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
<div id="mainContainer">
<div id="content">
<video id="contentElement">
<!-- <source src="https://storage.googleapis.com/interactive-media-ads/media/android.mp4" /> -->
</video>
</div>
<div id="adContainer"></div>
</div>
<button id="playButton">Btn1 </button>
<button id="testButton">Btn 2</button>

bad output of canvas generated image

SO the code below is simply meant to allow users upload a video and then when the press the button 'choose thumbnail' an image is generated from a canvas which represents the current image which was showing when the video was playing...that is,the image becomes the thumbnail of the video which the user chooses by seeking a particular video time,pauses the video and creates the thumbnail which is an image of the video when it was paused.
Everything is going fine except that the image is too long..in a way...the image is created in the dimensions that I want BUT some a lot of extra white space is still counted as the image....that is a lot of white space round it is the image.
This screenshots may help...
var _CANVAS = document.querySelector("#myCanvas"),
_CTX = _CANVAS.getContext("2d"),
_VIDEO = document.querySelector("#main-video");
document.getElementById("image").src = _CANVAS.toDataURL();
function showit() {
document.getElementById("other").style.display = 'block';
}
// Upon click this should should trigger click on the #file-to-upload file input element
// This is better than showing the not-good-looking file input element
document.querySelector("#diver").addEventListener('click', function() {
document.querySelector("#file-to-upload").click();
});
// When user chooses a MP4 file
document.querySelector("#file-to-upload").addEventListener('change', function() {
// Validate whether MP4
if (['video/mp4'].indexOf(document.querySelector("#file-to-upload").files[0].type) == -1) {
alert('Error : Only MP4 format allowed');
return;
}
// Hide upload button
document.querySelector("#upload-button").style.display = 'none';
// Object Url as the video source
document.querySelector("#main-video source").setAttribute('src', URL.createObjectURL(document.querySelector("#file-to-upload").files[0]));
// Load the video and show it
_VIDEO.load();
_VIDEO.style.display = 'inline';
// Load metadata of the video to get video duration and dimensions
_VIDEO.addEventListener('loadedmetadata', function() {
console.log(_VIDEO.duration);
var video_duration = _VIDEO.duration,
duration_options_html = '';
// Set options in dropdown at 4 second interval
for (var i = 0; i < Math.floor(video_duration); i = i + 2) {
duration_options_html += '<option value="' + i + '">' + i + '</option>';
}
document.querySelector("#set-video-seconds").innerHTML = duration_options_html;
// Show the dropdown container
document.querySelector("#thumbnail-container").style.display = 'block';
// Set canvas dimensions same as video dimensions
_CANVAS.width = _VIDEO.videoWidth;
_CANVAS.height = _VIDEO.videoHeight;
});
});
// On changing the duration dropdown, seek the video to that duration
document.querySelector("#set-video-seconds").addEventListener('change', function() {
_VIDEO.currentTime = document.querySelector("#set-video-seconds").value;
// Seeking might take a few milliseconds, so disable the dropdown and hide download link
});
// Seeking video to the specified duration is complete
document.querySelector("#main-video").addEventListener('timeupdate', function() {
// Re-enable the dropdown and show the Download link
document.querySelector("#set-video-seconds").disabled = false;
document.querySelector("#get-thumbnail").style.display = 'inline';
});
// On clicking the Download button set the video in the canvas and download the base-64 encoded image data
document.querySelector("#get-thumbnail").addEventListener('click', function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.drawImage(_VIDEO, 1, 1, _VIDEO.videoWidth / 8, _VIDEO.videoHeight / 8);
document.getElementById("image").src = c.toDataURL();
});
document.querySelector("#get-thumbnail").setAttribute('href', c.toDataURL());
document.querySelector("#get-thumbnail").setAttribute('download', 'thumbnai.png');
body {
margin: 0;
}
#video-demo-container {
width: 400px;
margin: 40px auto;
}
#main-video {
display: none;
max-width: 400px;
}
#thumbnail-container {
display: none;
}
#get-thumbnail {
display: none;
}
#video-canvas {
display: block;
}
#upload-button {
width: 150px;
display: block;
margin: 20px auto;
}
#file-to-upload {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=no">
</head>
<body>
<div style="border:2px dashed blue;" id="diver">
<div id="video-demo-container">
<button id="upload-button">Select MP4 Video</button>
<input type="file" id="file-to-upload" accept="video/mp4" />
<video id="main-video" controls>
<source type="video/mp4">
</video>
<p id="yes"></p>
</div>
</div>
<p id="thumbnail-container"><button onclick="showit()">Confirm</button> <button>Undo</button></p>
<br>
<!-- other content to choose -->
<div style="border:2px solid green;display:none" id="other">
<br>
<div style="margin-left:10%;">
<p style="font-size:160%">
<font style="font-weight:bolder">(1)</font>Choose thumbnail</p>
<font style="font-weight:bolder;margin-left:3%;">(a)Choose from video clip:</font><br><br>
<div id="allfloat">
<div style="margin-left:5%;">
Seek to
<select id="set-video-seconds"></select> seconds <br><br>
<button id="get-thumbnail" href="#" style="text-decoration:none;background-color:blue;padding-left,padding-right:2%;color:white;">Create Thumbnail</button>
</div>
<p style="font-weight:bolder;margin-left:5%;">Thumbnail:</p>
<img id="image" src width="200%" height="200%" style="margin-left:5%">
</div>
</div>
</div>
<canvas id="myCanvas" style="display:none;">
Your browser does not support the HTML5 canvas tag.
</canvas>
u see what I'm talking about.the image is somehow so large but I can't see the 'large part' of the image.
Also,I don't know what they mean as 'c is undefined'
Thanks in advance...
(1) Fix c is undefined error :
Cut the var c and var ctx declarations from //On clicking the Download button section and paste them with your other var declarations. This will give it global access (not just local access for only that specific function) :
// when you do this part
var _CANVAS = document.querySelector("#myCanvas");
var _CTX = _CANVAS.getContext("2d");
var _VIDEO = document.querySelector("#main-video");
// also add this part below it
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
(2) Fix scale or quality :
When drawing the thumbnail with ctx.drawImage, use values of c.width and c.height. Example:
// On clicking the Download button set the video in the canvas and download the base-64 encoded image data
document.querySelector("#get-thumbnail").addEventListener('click', function() {
ctx.drawImage(_VIDEO, 1, 1, c.width, c.height); //use c.width not _VIDEO.videoWidth... etc
document.getElementById("image").src = c.toDataURL();
});
That should give a clear image at same size as video resolution.
Let me know how it goes. Thanks.

How do I replace an image on a canvas onclick?

I'm using fabricjs to place an image on a canvas. I'd like to learn what I need to do to to replace the already drawn image with another one from a url onclick.
My limited understanding has me thinking I need to maybe set a var for each image but I'm not sure how to connect that with the fabricjs canvas. I've spent the last few hours trying different things without any luck.
I tried submitting a similar question but deleted it because I thought maybe it was too complicated an ask. Any help would be greatly appreciated. Here's my code now:
var canvas = new fabric.Canvas('c');
fabric.Image.fromURL('http://lorempixel.com/400/400/', function(img) {
var oImg = img.set({
selectable: false
})
canvas.add(oImg).renderAll();
});
canvas {
border: 1px solid #dddddd;
border-radius: 3px;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<canvas id="c" width="400" height="400"></canvas>
This is how you could achieve that :
var canvas = new fabric.Canvas('c');
var image, isImageLoaded;
fabric.Image.fromURL('//lorempixel.com/200/200/', function(img) {
isImageLoaded = true;
image = img.set({
selectable: false
})
canvas.add(image).renderAll();
});
function replaceImage(imgUrl) {
if (!isImageLoaded) return; //return if initial image not loaded
var imgElem = image._element; //reference to actual image element
imgElem.src = imgUrl; //set image source
imgElem.onload = () => canvas.renderAll(); //render on image load
}
canvas.on('mouse:down', function() {
replaceImage('//lorempixel.com/200/200/');
});
canvas {
border: 1px solid #dddddd;
border-radius: 3px;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<canvas id="c" width="200" height="200"></canvas>
PS: apology for not giving that much explanation.
You can do this much simpler. Don't see why you'd use an extra lib for something like this. I wrote something small in plain JS which hopefully helps you further.
document.getElementById("image").onclick = function(){
document.getElementById("image").src = "http://lorempixel.com/400/400/";
};
<img id="image" src="http://lorempixel.com/400/400/">
var canvas = new fabric.Canvas('c');
var oImg;
loadImage();
function loadImage(){
fabric.Image.fromURL('https://lorempixel.com/400/400/', function(img) {
oImg && canvas.remove(oImg); //If image element alread added to canvas remove it.
oImg = img.set({
selectable: false
})
canvas.add(oImg); //add new image to canvas
oImg.on('mousedown',onImgMouseDown); //add mouse down lisner to image
});
}
function onImgMouseDown(){
loadImage();
}
canvas {
border: 1px solid #dddddd;
border-radius: 3px;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<canvas id="c" width="400" height="400"></canvas>
Alternative you add mousedown listener to image , and check if element added ,then remove it from canvas. then add new one to canvas.

Count number of faces using javascript

Is there a way that I can count the number of faces in a live camera.
For example I've three persons in front of a webcam and I'm having 2 pages say, Success.html and error .html and as part of the underlying way to judge the redirection to Success or error pages the condition would be, if only one face is detected, it should be sent to success, else, it should be sent to error .
I'm using tracking.js to detect the face in my web page and currently my code is as below.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>tracking.js - face with camera</title>
<link rel="stylesheet" href="assets/demo.css">
<script src="js/tracking-min.js"></script>
<script src="js/data/face-min.js"></script>
<script src="js/dat.gui.min.js"></script>
<script src="assets/stats.min.js"></script>
<style>
video, canvas {
margin-left: 230px;
margin-top: 120px;
position: absolute;
}
</style>
</head>
<body>
<div class="demo-title">
<p>
tracking.js -
get user's webcam and detect faces
</p>
</div>
<div class="demo-frame">
<div class="demo-container">
<video id="video" width="320" height="240" preload autoplay loop
muted></video>
<canvas id="canvas" width="320" height="240"></canvas>
</div>
</div>
<script>
window.onload = function() {
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var tracker = new tracking.ObjectTracker('face');
tracker.setInitialScale(4);
tracker.setStepSize(2);
tracker.setEdgesDensity(0.1);
tracking.track('#video', tracker, {
camera : true
});
tracker.on('track', function(event) {
context.clearRect(0, 0, canvas.width, canvas.height);
event.data
.forEach(function(rect) {
console.log('face detected');
});
});
</script>
</body>
</html>
Here in my console I'm able to print, face detected.
please let me know how can I detect multiples faces in this window.
Thanks
From the documentation:
myTracker.on('track', function(event) {
if (event.data.length === 0) {
// No targets were detected in this frame.
} else {
event.data.forEach(function(data) {
// Plots the detected targets here.
});
}
});
It seems to be event.data.length that gives you the number of tracked elements.
Fom the docs at https://trackingjs.com/docs.html#trackers
myTracker.on('track', function(event) {
if (event.data.length === 0) {
// No targets were detected in this frame.
} else {
event.data.forEach(function(data) {
// Plots the detected targets here.
});
}
});
Use event.data.length to count the amount of faces.
On your piece of code :
tracker.on('track', function(event) {
context.clearRect(0, 0, canvas.width, canvas.height);
// console log amount of elements found
console.log(event.data.length);
event.data.forEach(function(rect) {
console.log('face detected');
});
});

Use/Access Android and iOS (Mobile) Camera

I make an HTML5-CSS-JS Android (and iOS) Application and i try to get access to the mobile device camera.
I tried two ways to get access to camera and both ways work fine when i use them from a Browser, but when i build my .APK file and i open my App none of them is working the same way as from a Browser:
First 1) I tried Input Tag and when i click to choose/browse it allows me only to select an Existing file NOT to capture or record a new one:
<input type="file" accept="image/*" capture="camera"/>
Then 2) I found (navigator.getUserMedia) this code on web that works also from a browser but when i open my App it seems like no working and not requesting for device hardware access at all:
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({ audio: true, video: { width: 1280, height: 720 } },
function(stream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(stream);
video.onloadedmetadata = function(e) {
video.play();
};
},
function(err) {
console.log("The following error occured: " + err.name);
}
);
} else {
console.log("getUserMedia not supported");
}
/*****************************************************************/
function init()
{
if(navigator.webkitGetUserMedia)
{
navigator.webkitGetUserMedia({video:true}, onSuccess, onFail);
}
else
{
alert('webRTC not available');
}
}
function onSuccess(stream)
{
document.getElementById('camFeed').src = webkitURL.createObjectURL(stream);
}
function onFail()
{
alert('could not connect stream');
}
function takePhoto()
{
var c = document.getElementById('photo');
var v = document.getElementById('camFeed');
c.getContext('2d').drawImage(v, 0, 0, 320, 240);
}
<div style="width:352px; height:625px; margin:0 auto; background-color:#fff;" >
<div>
<video id="camFeed" width="320" height="240" autoplay>
</video>
</div>
<div>
<canvas id="photo" width="320" height="240">
</canvas>
</div>
<div style="margin:0 auto; width:82px;">
<input type="button" value="Take Photo" onclick="takePhoto();">
</div>
</div>
Anyone has an idea of how can I access camera on Android or iOS?
I tried it with and without camera permissions but this was not the problem.
Help... Thank you in Advance. (If my question is not clear comment please.)
Here is the basic code, it will allow you to record/capture the file.
HTML:
<input id="reviewVideoCapture" type="file" accept="video/*"/>
JS (Using JQuery):
var videoFile = $('#reviewVideoCapture').get(0).files[0];
Use this if you want to upload the video somewhere:
<form enctype="multipart/form-data" action="/api/photo" method="POST" >
<input id="reviewVideoCapture" type="file" accept="video/*"/>
<input id="submitFormButton" type="submit">
</form>
Even though this works, I would still not recommend doing it this way. The results on mobile are buggy and hard to work with. The better way is to use cordova/ionic. A good example on how to do this can be found here:
https://github.com/yafraorg/ionictests

Categories