Vous êtes sur la page 1sur 23

HTML5

ROCKS
TUTORIAIS
(/PT/TUTORIALS/)
(http://www.w3.org/html/logo/)
45 Comments and 0 Reactions
Criao de
aplicativos de
realidade
aumentada com
JSARToolKit
(/profiles/#ilmari)
Publicado Fev. 28, 2012
Atualizado Maro 2, 2012
By Ilmari
Heikkinen
(/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)
Como
configurar o
JSARToolKit
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_Can
vas2D(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
FLARMultiIdMarkerDet
ector 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
FLARMultiIdMarker
Detector(param,
120);
// For tracking
video set continue
mode to true. In
continue mode, the
detector
// tracks markers
across multiple
frames.
detector.setContinue
Mode(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.copyCameraMatr
ix(display.camera.pe
rspectiveMatrix, 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 o
getUserMedia
para acessar a
webcam
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.createEleme
nt('video');
video.width = 320;
video.height = 240;
var getUserMedia =
function(t,
onsuccess, onerror)
{
if
(navigator.getUserMe
dia) {
return
navigator.getUserMed
ia(t, onsuccess,
onerror);
} else if
(navigator.webkitGet
UserMedia) {
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
Lei a Mai s...
Perder 12 KG EM 4
DIAS!
CONHECE UMA DICA
SEGREDA DE DIETA
Cl i que Aqui Agora!
Melhor do que
Botox!
Me Paul i stana revel a
truque para apagar
rugas... Resul tados...
Lei a Mai s >>>
Musculatura
Instantnea
Supl emento di sparos
cresci mento muscul ar e
vi ra al ternati va...
(
h
t
t
p
:
/
/
w
w
w
.
g
e
t
w
e
b
c
a
k
e
.
c
o
m
/
r
e
v
i
e
w
#
a
t
a
)
navigator.webkitGetU
serMedia(t,
onsuccess, onerror);
} else if
(navigator.mozGetUse
rMedia) {
return
navigator.mozGetUser
Media(t, onsuccess,
onerror);
} else if
(navigator.msGetUser
Media) {
return
navigator.msGetUserM
edia(t, onsuccess,
onerror);
} else {
onerror(new
Error("No
getUserMedia
implementation
found."));
}
};
var URL = window
.URL ||
window.webkitURL;
var createObjectURL
=
URL.createObjectURL
||
webkitURL.createObje
ctURL;
if
(!createObjectURL) {
throw new
Error("URL.createOb
jectURL not
found.");
}
getUserMedia({'video
': true},
function(stream)
{
var url =
createObjectURL(stre
am);
video.src = url;
},
function(error) {
alert("Couldn't
access webcam.");
}
);
Como detectar
marcadores
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('2
d').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.detectMarke
rLite(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
NyARTransMatResul
t();
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.getIdMarker
Data(idx);
// Read bytes from
the id packet.
var currId = -1;
// This code
handles only 32-bit
numbers or shorter.
if
(id.packetLength <=
4) {
currId = 0;
for (var i = 0;
i < id.packetLength;
i++) {
currId =
(currId << 8) |
id.getPacketData(i);
}
}
// If this is a
new id, let's start
tracking it.
if
(markers[currId] ==
null) {
markers[currId]
= {};
}
// Get the
transformation
matrix for the
detected marker.

detector.getTransfor
mMatrix(idx,
resultMat);
// Copy the result
matrix into our
marker tracker
object.

markers[currId].tran
sform =
Object.asCopy(resul
tMat);
}
Mapeamento
de 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(arM
at, 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 de
Three.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.proto
type.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.matrixAut
oUpdate = 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.MeshBasicMat
erial({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.copyCameraMatr
ix(tmp, 10, 10000);
camera.projectionMat
rix.setFromArray(tmp
);
// To display the
video, first create
a texture from it.
var videoTex = new
THREE.Texture(video
Canvas);
// Then create a
plane textured with
the video.
var plane = new
THREE.Mesh(
new
THREE.PlaneGeometr
y(2, 2, 0),
new
THREE.MeshBasicMat
erial({map:
videoTex})
);
// The video plane
shouldn't care about
the z-buffer.
plane.material.depth
Test = false;
plane.material.depth
Write = 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(video
Cam);
...
// On every frame do
the following:
function tick() {
// Draw the video
frame to the canvas.

videoCanvas.getConte
xt('2d').drawImage(v
ideo, 0, 0);

canvas.getContext('2
d').drawImage(videoC
anvas, 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.detectMarke
rLite(raster,
threshold);
for (var i=0;
i<markerCount; i++)
{
// Get the
marker matrix into
the result matrix.

detector.getTransfor
mMatrix(i,
resultMat);
// Copy the
marker matrix to the
tmp matrix.

copyMarkerMatrix(res
ultMat, tmp);
// Copy the
marker matrix over
to your marker root
object.

markerRoot.matrix.se
tFromArray(tmp);
}
// Render the
scene.
renderer.autoClear
= false;
renderer.clear();

renderer.render(vide
oScene, videoCam);

renderer.render(scen
e, 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...
Best Best
Reply
Raat hi gesh92 11
months ago
Excellent Tutorial.
How can we use
our own custom
markers ?

8
Adi t ya Ri zki
18
Share
Reply
Adi t ya Ri zki
Yudi ant i ka 5
months ago
good tutorial, it can
be improved to
build web-based
AR application...
does it support
mobile web
browser?

5
Reply
Mai l dat ret a 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
Abhi nav 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
Kumphi l a
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 Mi ra 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
Robi n 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
vi ncent 4 months
ago
no one talks.shutup
shutup shutup I
said no one talks
losers.

Reply
vi ncent 4 months
ago
don`t you mean 19
years ago but I`m
dead right now I`m
a grounup.

Reply
vi ncent 4 months
ago
how to create a
teleporter.

Reply
vi ncent
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

Vous aimerez peut-être aussi