Criação de Aplicativos de Realidade Aumentada Com JSARToolKit - HTML5 Rocks

Embed Size (px)

Citation preview

  • HTML5ROCKSTUTORIAIS(/PT/TUTORIALS/)

    (http://www.w3.org/html/logo/)

    45 Comments and 0 Reactions

    Criao deaplicativos derealidadeaumentada comJSARToolKit

    (/profiles/#ilmari)

    Publicado Fev. 28, 2012 Atualizado Maro 2, 2012

    By IlmariHeikkinen

    (/profiles/#ilmari)

    NAVEGADORES SUPORTADOS:

    Heads up! This article

    discusses APIs that are

    not yet fully

    standardized and still in

    flux. Be cautious when

    using experimental APIs

    in your own projects.

    Introduo

    Este artigo sobre o uso da

    biblioteca JSARToolKit

    (https://github.com/kig/JSARToolKit)

    (link em ingls) com a API

    getUserMedia WebRTC

    (http://webrtc.org) (link

    em ingls) para executar

    aplicativos de realidade

    aumentada na Web. Para a

    renderizao, estou usando

    o WebGL pelo maior

    desempenho que ele

    oferece. O resultado final

    deste artigo um aplicativo

  • de demonstrao que

    coloca um modelo 3D em

    cima de um marcador de

    realidade aumentada no

    vdeo da webcam.

    JSARToolKit uma

    biblioteca de realidade

    aumentada para JavaScript.

    uma biblioteca de cdigo

    aberto disponibilizada por

    GPL e uma porta direta do

    Flash FLARToolKit

    (http://www.libspark.org/wiki/saqoosha/FLARToolKit/en)

    (link em ingls) que

    desenvolvi para a

    demonstrao de

    remixagem de realidade

    (https://developer.mozilla.org/en-

    US/demos/detail/remixing-

    reality/launch) (link em

    ingls) do Mozilla. A prpria

    FLARToolKit uma porta do

    Java NyARToolKit

    (http://nyatla.jp/nyartoolkit/wp/)

    (link em ingls) que uma

    porta do C ARToolKit

    (http://www.hitl.washington.edu/artoolkit/)

    (link em ingls). Foi um

    longo caminho, mas aqui

    estamos.

    A JSARToolKit opera nos

    elementos do canvas. Como

    necessrio ler a imagem a

    partir do canvas, a imagem

    precisa vir da mesma

    origem que a pgina ou

    usar CORS

    (http://updates.html5rocks.com/2011/07/Using-

    Cross-domain-images-in-

    WebGL) (link em ingls)

    para contornar a poltica de

    mesma origem.

    Resumidamente, defina a

    propriedade crossOrigin

    na imagem ou elemento de

  • vdeo pretendido como

    uma textura para '' ou

    "anonymous" .

    Quando voc passa um

    canvas para JSARToolKit

    para anlise, o JSARToolKit

    retorna uma lista de

    marcadores AR localizados

    na imagem e as matrizes

    de transformao

    correspondentes. Para

    desenhar um objeto 3D em

    cima de um marcador, voc

    transfere a matriz de

    transformao para

    qualquer biblioteca de

    renderizao 3D que

    estiver usando para que o

    seu objeto seja

    transformado usando a

    matriz. Depois, desenhe o

    quadro do vdeo no cenrio

    WebGL e desenhe o objeto

    em cima dele e est pronto.

    Para analisar o vdeo

    usando o JSARToolKit,

    desenhe o vdeo em um

    canvas e, em seguida,

    passe o canvas para o

    JSARToolKit. Faa isso para

    cada quadro e voc tem o

    rastreamento AR de vdeo.

    O JSARToolKit rpido o

    suficiente para fazer isso

    em tempo real nos

    mecanismos JavaScript

    modernos , at mesmo em

    quadros de vdeo de

    640x480. Contudo, quanto

    maior o quadro de vdeo,

    mais demorado o

    processamento. 320x240

    um bom tamanho de

    quadro de vdeo, mas se

    voc planeja usar

  • marcadores pequenos ou

    vrios marcadores, prefira

    640x480.

    Demonstrao

    Para visualizar a

    demonstrao de webcam,

    necessrio ter o WebRTC

    ativado no navegador (no

    Google Chrome, acesse

    about:flags e ative o

    MediaStream). Tambm

    necessrio imprimir o

    marcador AR abaixo. Voc

    tambm pode tentar abrir a

    imagem do marcador no

    telefone ou tablet e mostr-

    la na webcam.

    Marcador AR.

    Segue uma demonstrao

    do que estamos almejando.

    Esta demonstrao cria

    uma apresentao de

    slides de imagens usando

    os marcadores AR. Mostre

    um marcador para a

    cmera, que ela colocar a

    foto nele. Mova o marcador

    para fora da vista da

    cmera e mostre-o

    novamente, que a imagem

    muda.

  • (AR_mediaStream.html)

    Demonstrao de AR na webcam(AR_mediaStream.html) (link em

    ingls) (se no tiver WebRTC, esta uma verso com o vdeo

    predefinido. (AR_slideshow.html)

    Comoconfigurar oJSARToolKit

    A API JSARToolKit muito

    parecida com a do Java, por

    isso necessrio um pouco

    de ginstica para us-la. A

    ideia bsica que voc

    tenha um objeto detector

    que opere em um objeto de

    varredura. Entre o detector

    e a varredura est um

    objeto de parmetro da

    cmera que transforma as

    coordenadas da varredura

    em coordenadas da

    cmera. Para obter os

    marcadores detectados,

    voc itera sobre eles e

    copia as matrizes de

    transformao sobre seu

    cdigo.

    O primeiro passo criar o

    objeto de varredura, o

    objeto de parmetro da

    cmera e o objeto detector.

    // Create a RGB raster object for the 2D canvas.// JSARToolKit uses raster objects to read image data.// Note that you

  • need to set canvas.changed = true on every frame.var raster = new NyARRgbRaster_Canvas2D(canvas);

    // FLARParam is the thing used by FLARToolKit to set camera parameters.// Here we create a FLARParam for images with 320x240 pixel dimensions.var param = new FLARParam(320, 240);

    // The FLARMultiIdMarkerDetector is the actual detection engine for marker detection.// It detects multiple ID markers. ID markers are special markers that encode a number.var detector = new FLARMultiIdMarkerDetector(param, 120);

    // For tracking video set continue mode to true. In continue mode, the detector// tracks markers across multiple frames.detector.setContinueMode(true);

    // Copy the camera perspective matrix from the FLARParam to the WebGL library camera matrix.// The second and third parameters determine the zNear and zFar planes for the perspective matrix.param.copyCameraMatrix(display.camera.perspectiveMatrix, 10, 10000);

    POSTAGENS & TUTORIAIS (/PT/TUTORIALS/) CARACTERSTICAS DO HTML5 SLIDES (/PT/SLIDES) RECURSOS (/PT/RESOURCES) POR QUE HTML5?

    CONTRIBUIR (HTTPS://GITHUB.COM/HTML5ROCKS/WWW.HTML5ROCKS.COM/BLOB/MASTER/CONTRIBUTING.MD)Related Searches:

  • Como usar ogetUserMediapara acessar awebcam

    Na sequncia, vou criar um

    elemento de vdeo que

    obtm o vdeo da webcam

    pelas APIs WebRTC. Para

    vdeos pr-gravados,

    configure apenas o atributo

    de origem do vdeo para o

    URL do vdeo. Se estiver

    fazendo a deteco de

    marcador das imagens

    estticas, voc pode usar

    um elemento de imagem

    da mesma maneira.

    Como o WebRTC e o

    getUserMedia so

    tecnologias que surgiram

    recentemente, necessrio

    detect-las com elementos.

    Para obter mais detalhes,

    consulte o artigo de Eric

    Bidelman sobre Captura de

    udio e vdeo em HTML5

    (/tutorials/getusermedia/intro/)

    (link em ingls).

    var video = document.createElement('video');video.width = 320;video.height = 240;

    var getUserMedia = function(t, onsuccess, onerror) { if (navigator.getUserMedia) { return navigator.getUserMedia(t, onsuccess, onerror); } else if (navigator.webkitGetUserMedia) { return

    Como usar o getUserMedia para acessar a

    Este artigo est disponvel tambm nos

    (/en/tutorials/webgl/jsartoolkit_webrtc/)

    (/es/tutorials/webgl/jsartoolkit_webrtc/)

    (/ru/tutorials/webgl/jsartoolkit_webrtc/)

    (/ja/tutorials/webgl/jsartoolkit_webrtc/)

    (/zh/tutorials/webgl/jsartoolkit_webrtc/)

    English To Spanish

    Translation

    HTML Reference

    Spaghetti Sauce

    Recipe

    Firefox Browser

    Duomo Of Florence

    John Resig

    Italian Pasta

    Recipes

    Rich Internet

    Applications

    Pasta Recipes

    Spaghetti Sauce

    English And

    Spanish Words

    Leia Mais...

    Perder 12 KG EM 4DIAS!CONHECE UMA DICASEGREDA DE DIETA

    Clique Aqui Agora!

    Melhor do queBotox!Me Paulistana revelatruque para apagarrugas... Resultados...

    Leia Mais >>>

    MusculaturaInstantneaSuplemento disparoscrescimento muscular evira alternativa...

    (http://w

    ww.g

    etw

    ebcake

    .com

    /revi

    ew#ata

    )

  • navigator.webkitGetUserMedia(t, onsuccess, onerror); } else if (navigator.mozGetUserMedia) { return navigator.mozGetUserMedia(t, onsuccess, onerror); } else if (navigator.msGetUserMedia) { return navigator.msGetUserMedia(t, onsuccess, onerror); } else { onerror(new Error("No getUserMedia implementation found.")); }};

    var URL = window

    .URL || window.webkitURL;var createObjectURL = URL.createObjectURL || webkitURL.createObjectURL;if (!createObjectURL) { throw new Error("URL.createObjectURL not found.");}

    getUserMedia({'video': true}, function(stream) { var url = createObjectURL(stream); video.src = url; }, function(error) { alert("Couldn't access webcam."); });

    Como detectarmarcadores

  • Quando o detector estiver

    funcionando corretamente,

    podemos comear

    aliment-lo com imagens

    para detectar as matrizes

    AR. Primeiro, desenhe a

    imagem no canvas do

    objeto de varredura, e

    ento, execute o detector

    no objeto de varredura. O

    detector retorna o nmero

    de marcadores localizados

    na imagem.

    // Draw the video frame to the raster canvas, scaled to 320x240.canvas.getContext('2d').drawImage(video, 0, 0, 320, 240);

    // Tell the raster object that the underlying canvas has changed.canvas.changed = true;

    // Do marker detection by using the detector object on the raster object.// The threshold parameter determines the threshold value// for turning the video frame into a 1-bit black-and-white image.//var markerCount = detector.detectMarkerLite(raster, threshold);

    A ltima etapa iterar os

    marcadores detectados e

    obter suas matrizes de

    transformao. Use as

    matrizes de transformao

    para colocar os objetos 3D

    sobre os marcadores.

    // Create a

  • // Create a NyARTransMatResult object for getting the marker translation matrices.var resultMat = new NyARTransMatResult();

    var markers = {};

    // Go through the detected markers and get their IDs and transformation matrices.for (var idx = 0; idx < markerCount; idx++) { // Get the ID marker data for the current marker. // ID markers are special kind of markers that encode a number. // The bytes for the number are in the ID marker data. var id = detector.getIdMarkerData(idx);

    // Read bytes from the id packet. var currId = -1; // This code handles only 32-bit numbers or shorter. if (id.packetLength

  • transformation matrix for the detected marker. detector.getTransformMatrix(idx, resultMat);

    // Copy the result matrix into our marker tracker object. markers[currId].transform = Object.asCopy(resultMat);}

    Mapeamentode matriz

    Este o cdigo para copiar

    as matrizes do JSARToolKit

    sobre as matrizes do

    glMatrix (que so

    FloatArrays

    (https://developer.mozilla.org/en/JavaScript_typed_arrays)

    [link em ingls] de 16

    elementos com coluna de

    translao nos ltimos

    quatro elementos).

    Funciona como por mgica

    (leia-se: no sei como as

    matrizes do ARToolKit so

    configuradas. Meu palpite

    eixo Y invertido.) De

    qualquer maneira, esse

    feitio de inverso de sinal

    faz a matriz JSAToolKit

    funcionar da mesma forma

    que uma glMatrix.

    Para usar a biblioteca com

    outra biblioteca, como

    Three.js, preciso escrever

    uma funo que converta

    as matrizes ARToolKit para

    a o formato da matriz da

    biblioteca. Voc tambm

    precisa conhecer bastante

  • o mtodo

    FLARParam.copyCameraMatrix.

    O mtodo

    copyCameraMatrix escreve

    a matriz da perspectiva

    FLAParam em uma matriz

    glMatrix.

    function copyMarkerMatrix(arMat, glMat) { glMat[0] = arMat.m00; glMat[1] = -arMat.m10; glMat[2] = arMat.m20; glMat[3] = 0; glMat[4] = arMat.m01; glMat[5] = -arMat.m11; glMat[6] = arMat.m21; glMat[7] = 0; glMat[8] = -arMat.m02; glMat[9] = arMat.m12; glMat[10] = -arMat.m22; glMat[11] = 0; glMat[12] = arMat.m03; glMat[13] = -arMat.m13; glMat[14] = arMat.m23; glMat[15] = 1;}

    Integrao deThree.js

    Three.js um mecanismo

    popular de JavaScript 3D.

    Vou mostrar como usar a

    sada do JSRToolkit em

    Three.js. So necessrias

    trs coisas: um

    quadrngulo de tela cheia

    com a imagem de vdeo

    desenhada nele, uma

    cmera com a matriz de

  • perspectiva FLAParam e um

    objeto com matriz de

    marcador conforme a

    transformao ocorre. Vou

    gui-los pela integrao do

    cdigo abaixo.

    Este um link (em ingls)

    para a demonstrao do

    Three.js

    (AR_mediaStream_three.html)

    em ao. Ela tem uma sada

    de depurao ativada,

    assim, possvel ver parte

    do funcionamento interno

    da biblioteca JSARToolKit.

    // I'm going to use a glMatrix-style matrix as an intermediary.// So the first step is to create a function to convert a glMatrix matrix into a Three.js Matrix4.THREE.Matrix4.prototype.setFromArray = function(m) { return this.set( m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14], m[3], m[7], m[11], m[15] );};

    // glMatrix matrices are flat arrays.var tmp = new Float32Array(16);

    // Create a camera and a marker root object for your Three.js scene.var camera = new THREE.Camera();scene.add(camera);

    var markerRoot = new THREE.Object3D();

  • markerRoot.matrixAutoUpdate = false;

    // Add the marker models and suchlike into your marker root object.var cube = new THREE.Mesh( new THREE.CubeGeometry(100,100,100), new THREE.MeshBasicMaterial({color: 0xff00ff}));cube.position.z = -50;markerRoot.add(cube);

    // Add the marker root to your scene.scene.add(markerRoot);

    // Next we need to make the Three.js camera use the FLARParam matrix.param.copyCameraMatrix(tmp, 10, 10000);camera.projectionMatrix.setFromArray(tmp);

    // To display the video, first create a texture from it.var videoTex = new THREE.Texture(videoCanvas);

    // Then create a plane textured with the video.var plane = new THREE.Mesh( new THREE.PlaneGeometry(2, 2, 0), new THREE.MeshBasicMaterial({map: videoTex}));

    // The video plane shouldn't care about the z-buffer.plane.material.depth

  • Test = false;plane.material.depthWrite = false;

    // Create a camera and a scene for the video plane and// add the camera and the video plane to the scene.var videoCam = new THREE.Camera();var videoScene = new THREE.Scene();videoScene.add(plane);videoScene.add(videoCam);

    ...

    // On every frame do the following:function tick() { // Draw the video frame to the canvas. videoCanvas.getContext('2d').drawImage(video, 0, 0); canvas.getContext('2d').drawImage(videoCanvas, 0, 0, canvas.width, canvas.height);

    // Tell JSARToolKit that the canvas has changed. canvas.changed = true;

    // Update the video texture. videoTex.needsUpdate = true;

    // Detect the markers in the video frame. var markerCount = detector.detectMarkerLite(raster, threshold); for (var i=0; i

  • detector.getTransformMatrix(i, resultMat);

    // Copy the marker matrix to the tmp matrix. copyMarkerMatrix(resultMat, tmp);

    // Copy the marker matrix over to your marker root object. markerRoot.matrix.setFromArray(tmp); }

    // Render the scene. renderer.autoClear = false; renderer.clear(); renderer.render(videoScene, videoCam); renderer.render(scene, camera);}

    Resumo

    Neste artigo, passamos

    pelo bsico da JSARToolKit.

    Agora, voc est pronto

    para construir seus

    prprios aplicativos de

    realidade aumentada

    usando a webcam com o

    JavaScript.

    A integrao da JSARToolKit

    com a Three.js um tanto

    chatinha, mas certamente

    possvel. No tenho certeza

    se minha demonstrao

    est certa, avisem-me se

    conhecerem uma forma

    melhor de conseguir a

    integrao. Aceito

  • correes

    (http://code.google.com/p/html5rocks/wiki/ContributorsGuide)

    :) (link em ingls)

    Referncias

    JSARToolKit

    (https://github.com/kig/JSARToolKit/)

    (link em ingls)

    Magi

    (https://github.com/kig/magi/)

    (link em ingls)

    Three.js

    (https://github.com/mrdoob/three.js/)

    (link em ingls)

    Salvo se observado

    (http://code.google.com/policies.html#restrictions)

    o contrrio, o contedo desta

    pgina est licenciado de acordo

    com a Licena da Atribuio 3.0 do

    Creative Commons

    (http://creativecommons.org/licenses/by/3.0/)

    e os exemplos de cdigo esto

    licenciados de acordo com a Licena

    do Apache 2.0

    (http://www.apache.org/licenses/LICENSE-

    2.0).

    45 comments

    Leave a

    message...

    BestBest

    Reply

    Raathigesh92 11

    months ago

    Excellent Tutorial.

    How can we use

    our own custom

    markers ?

    8

    Aditya Rizk i

    18

    Share

  • Reply

    Aditya Rizk i

    Yudiant ika 5

    months ago

    good tutorial, it can

    be improved to

    build web-based

    AR application...

    does it support

    mobile web

    browser?

    5

    Reply

    Maildatreta a year

    ago

    So easy when it

    was in Java or

    ActionScript...

    Jesus what a

    mess...

    7 1

    Reply

    weavermount a

    year ago

    Hello. This is super

    cool. I got them

    demo hosted at

    html5rocks to work,

    but when I

    download it, I get a

    "Not allowed to load

    local resource" and

    "Failed to load

    resource" I think I

    might have to use

    terminal flags, but

    I'm on a mac, and

    am not sure how to

    launch Chrome 18 /

    Canary with

    terminal options.

    Any thoughts? I

    really love to hack

    on this.

    3

    Abhinav 21 days

    ago

    Share

    Share

    Share

  • Reply

    Sir,

    Please can you

    explain your

    encoding for storing

    marker data and its

    comparision with

    the image.

    Thanks.

    2

    Reply

    Waseem Ansar 3

    months ago

    Please tell me how

    to use our own

    custom marker for

    own AR

    applications?

    1

    Reply

    sheraz

    3

    months ago

    Waseem

    Ansar

    wao

    waseem

    KOMATSU

    Kensaku a year

    ago

    Great work!! I'm so

    impressed. But, I

    found that current

    AR demo site

    doesn't work well,

    because 1st

    argument of

    webkitGetUserMedia

    changed from

    "video" to {video:

    true}. I've copied

    your code and did

    some patch coding

    (my patch is little bit

    Share

    Share

    Share

  • Reply

    dirty ... ). Now I'm

    providing

    in http://webrtc.cloudfoundry.com...

    and it seems good

    to me:)

    1

    Reply

    Pakorn

    Kumphila

    5

    months ago

    KOMATSU

    Kensaku

    Thank you.

    for a guide

    me.

    Reply

    ZERONE a year

    ago

    Excelente Libreria

    C: aunque me

    gustaria ver el

    codigo de la

    intregracion con

    tree.js!!

    1

    Reply

    ZERONE

    a

    year ago

    ZERONE

    Yo os no

    kise escribir

    Estafadores

    como llego

    esa palabra

    ahy.. mis

    mas

    sinceras

    disculpas!!

    1

    Joan Mira 2

    months ago

    Great tutorial, but

    Share

    Share

    Share

    Share

  • Reply

    Great tutorial, but

    how can we get the

    coordinates (x,y) of

    the tracked boxes

    in the

    debugcanvas?

    Thanks!

    Reply

    Robin 2 months

    ago

    This was fairly clear

    and easy when it

    was in AS3, gotta

    say it's rather

    messy in

    JavaScript, but I

    guess that's due to

    the difference in

    programming style.

    I'm not a fan of the

    way object oriented

    programming

    works in Javascript

    anyway.

    With the

    FLARtoolkit (AS3) I

    used to have a

    'marker generator'

    (Air-application to

    create your own

    marker matrix from

    an image). I

    downloaded that

    somewhere, but I

    don't remember

    where. Does

    anyone know if

    something like that

    exists for use with

    this library as well?

    Hans 2 months

    ago

    hello. this was a

    great code. does it

    support mobile web

    Share

    Share

  • Reply

    support mobile web

    browser? it can run

    on chrome, but

    when i try on opera

    browser in android

    smartphone it can't

    access camera

    (getusermedia).

    can somebody help

    me to fix this?

    Reply

    vincent 4 months

    ago

    no one talks.shutup

    shutup shutup I

    said no one talks

    losers.

    Reply

    vincent 4 months

    ago

    don`t you mean 19

    years ago but I` m

    dead right now I` m

    a grounup.

    Reply

    vincent 4 months

    ago

    how to create a

    teleporter.

    Reply

    vincent

    4

    months ago

    vincent

    sutup

    Guest 5 months

    ago

    can u help me

    fix,they not work for

    me and sorry about

    Share

    Share

    Share

    Share

    Share

  • Reply

    me and sorry about

    my bad English.

    abu daan 7

    months ago

    If you use the code

    of this example with

    a newer version of

    Threejs, the Z- and

    Y-axis are

    swapped.

    You can solve this

    by changing the

    copyMatrix()

    function like so:

    Share