INGENIERO ELECTROMECÁNICO
Madrid
Julio 2015
AUTORIZACIÓN PARA LA DIGITALIZACIÓN, DEPÓSITO Y DIVULGACIÓN EN ACCESO
ABIERTO (RESTRINGIDO) DE DOCUMENTACIÓN
En caso de ser cotitular, el autor (firmante) declara asimismo que cuenta con el
consentimiento de los restantes titulares para hacer la presente cesión. En caso de previa
cesión a terceros de derechos de explotación de la obra, el autor declara que tiene la oportuna
autorización de dichos titulares de derechos a los fines de esta cesión o bien que retiene la
facultad de ceder estos derechos en la forma prevista en la presente cesión y así lo acredita.
Con el fin de dar la máxima difusión a la obra citada a través del Repositorio institucional de la
Universidad y hacer posible su utilización de forma libre y gratuita ( con las limitaciones que
más adelante se detallan) por todos los usuarios del repositorio y del portal e-ciencia, el autor
CEDE a la Universidad Pontificia Comillas de forma gratuita y no exclusiva, por el máximo plazo
legal y con ámbito universal, los derechos de digitalización, de archivo, de reproducción, de
distribución, de comunicación pública, incluido el derecho de puesta a disposición electrónica,
tal y como se describen en la Ley de Propiedad Intelectual. El derecho de transformación se
cede a los únicos efectos de lo dispuesto en la letra (a) del apartado siguiente.
1
Especificar si es una tesis doctoral, proyecto fin de carrera, proyecto fin de Máster o cualquier otro
trabajo que deba ser objeto de evaluación académica
1
(a) Transformarla para adaptarla a cualquier tecnología susceptible de incorporarla a internet;
realizar adaptaciones para hacer posible la utilización de la obra en formatos electrónicos, así
como incorporar metadatos para realizar el registro de la obra e incorporar “marcas de agua”
o cualquier otro sistema de seguridad o de protección.
(b) Reproducirla en un soporte digital para su incorporación a una base de datos electrónica,
incluyendo el derecho de reproducir y almacenar la obra en servidores, a los efectos de
garantizar su seguridad, conservación y preservar el formato. .
(c) Comunicarla y ponerla a disposición del público a través de un archivo abierto institucional,
accesible de modo libre y gratuito a través de internet.2
El autor, en tanto que titular de una obra que cede con carácter no exclusivo a la Universidad
por medio de su registro en el Repositorio Institucional tiene derecho a:
b) Comunicar y dar publicidad a la obra en la versión que ceda y en otras posteriores a través
de cualquier medio.
c) Solicitar la retirada de la obra del repositorio por causa justificada. A tal fin deberá ponerse
en contacto con el vicerrector/a de investigación (curiarte@rec.upcomillas.es).
d) Autorizar expresamente a COMILLAS para, en su caso, realizar los trámites necesarios para
la obtención del ISBN.
2
En el supuesto de que el autor opte por el acceso restringido, este apartado quedaría redactado en los
siguientes términos:
(c) Comunicarla y ponerla a disposición del público a través de un archivo institucional, accesible de
modo restringido, en los términos previstos en el Reglamento del Repositorio Institucional
3
En el supuesto de que el autor opte por el acceso restringido, este apartado quedaría eliminado.
2
d) Recibir notificación fehaciente de cualquier reclamación que puedan formular terceras
personas en relación con la obra y, en particular, de reclamaciones relativas a los derechos de
propiedad intelectual sobre ella.
El autor se compromete a:
a) Garantizar que el compromiso que adquiere mediante el presente escrito no infringe ningún
derecho de terceros, ya sean de propiedad industrial, intelectual o cualquier otro.
b) Garantizar que el contenido de las obras no atenta contra los derechos al honor, a la
intimidad y a la imagen de terceros.
c) Asumir toda reclamación o responsabilidad, incluyendo las indemnizaciones por daños, que
pudieran ejercitarse contra la Universidad por terceros que vieran infringidos sus derechos e
intereses a causa de la cesión.
La obra se pondrá a disposición de los usuarios para que hagan de ella un uso justo y
respetuoso con los derechos del autor, según lo permitido por la legislación aplicable, y con
fines de estudio, investigación, o cualquier otro fin lícito. Con dicha finalidad, la Universidad
asume los siguientes deberes y se reserva las siguientes facultades:
- La Universidad informará a los usuarios del archivo sobre los usos permitidos, y no garantiza
ni asume responsabilidad alguna por otras formas en que los usuarios hagan un uso posterior
de las obras no conforme con la legislación vigente. El uso posterior, más allá de la copia
privada, requerirá que se cite la fuente y se reconozca la autoría, que no se obtenga beneficio
comercial, y que no se realicen obras derivadas.
- La Universidad no revisará el contenido de las obras, que en todo caso permanecerá bajo la
responsabilidad exclusiva del autor y no estará obligada a ejercitar acciones legales en nombre
del autor en el supuesto de infracciones a derechos de propiedad intelectual derivados del
depósito y archivo de las obras. El autor renuncia a cualquier reclamación frente a la
Universidad por las formas no ajustadas a la legislación vigente en que los usuarios hagan uso
de las obras.
3
ESCUELA TÉCNICA SUPERIOR DE INGENIERIA (ICAI)
INGENIERO ELECTROMECÁNICO
Madrid
Julio 2015
Desarrollo de un control visual basado en un sensor Kinect
para la navegación autónoma en un entorno forestal
Introducción
Tomando como base del control visual el sensor Kinect para obtener los datos del
entorno en tiempo real y elaborar un mapeado tridimensional, necesario para sentar las
bases de la navegación autónoma y poder generar las órdenes para guiar al vehículo.
El proceso seguido (tal y como es mostrado en la figura 1) consiste en procesar las
imágenes de color y profundidad del entorno, obtenidas por medio del sensor Kinect,
para recrear el entorno en tres dimensiones.
Resultados
Para determinar la viabilidad del proyecto, se han realizado a lo largo del trabajo varios
experimentos que se detallan a continuación. En primer lugar se realizaron pruebas al
sensor Kinect para comprobar su funcionamiento en entornos exteriores con árboles, sin
embargo, la imagen de profundidad proporcionada en condiciones de alta intensidad
luminosa, no era suficientemente fiable para desarrollar un control visual; por otra parte,
se llevaron a cabo experimentos para comparar la última versión del Kinect (Kinect
One) con el Kinect 360, que es el usado en este proyecto, aprobando el uso del nuevo
Kinect para entornos exteriores.
Debido a ciertos problemas con la velocidad de proceso, se realizaron experimentos
sobre la creación de la escena, mostrando poca fiabilidad a la hora de detectar los
fotogramas base en la panorámica y largos tiempos de procesamiento, que impiden que
el programa pueda trabajar a tiempo real.
Finalmente se logra representar con éxito la escena tridimensional (figura 3), sin
embargo, los cálculos para la localización espacial de los fotogramas, no son
suficientemente precisos para formar un mapeado detallado.
Referencias
[1] Revista ambienta, Agricultura de precisión
http://www.revistaambienta.es/WebAmbienta/marm/Dinamicas/secciones/articul
os/AP.htm
[2] Logo de Microsoft Visual Studio
https://www.visualstudio.com/
[3] Logo de OpenCV
http://opencv.org/
[4] Logo de OpenGL
https://www.opengl.org/
[5] Vídeo de la escena, disponible en YouTube
https://youtu.be/TM1jzjGJ7K0
[6] Vídeo de la escena, disponible en YouTube
https://youtu.be/eR4S4tpCaIE
Development of a visual control based on a Kinect sensor
for the autonomous navigation through a forest
environment
ABSTRACT
Introduction
Robotics is a branch of technology which deals with the study and functioning of
robots, along with their design, construction and use.
Robots are great allies in the performance of repetitive tasks which require high
accuracy or which take place in hostile environments for human beings. They can be
found in a wide variety of fields, going from surgical robots and mechanical arms in
assembly lines to space explorer robots or unmanned aircrafts.
These developments will produce a greater industrialization in some fields such as
agriculture, by assisting the operator on managing the crops, both in terms of crops
inspection or crops treatment tasks. It will simplify these tasks, decrease the costs and
increase the productivity.
Just like what happened with the leap from draft animals to tractors, which caused great
developments in agriculture, the main aim of robotics is to optimize the guiding and
management of the machines which are utilized. [1]
Therefore, the objective of this project is making the autonomous and safe navigation of
a vehicle possible in environments with trees, such as forests or tree cropping areas,
whether with or without fruit. The vehicle must go across an area or a crop with total
coverture, carrying out inspection tasks; for this, it will be essential to have a suitable
sensorial system which allows to construct an approximate image of its surroundings;
the Kinect sensor is proposed as the key element for the development of the guiding
system of the vehicle, because it provides an acceptable reaction speed for a medium
range (several meters) at a reasonable price if compared to other devices.
Methodology
Taking the Kinect sensor as the base of the visual control for getting the data of the
surroundings in real time and creating a tridimensional mapping, which is necessary for
setting the bases of the autonomous navigation and for being able to produce the
instructions for guiding the vehicle
The proceedings (as showed in figure 1) consist in the treatment of the Depth and Color
Image of the environment, which are obtained through the Kinect sensor, for the
recreation of an spatial representation of the surroundings.
Results
For determining the viability of the project, several experiments have been carried out
The details of these experiments are the ones which go next:
First of all, some tests were carried out for verifying the functioning of the Kinect
sensor outdoors, in spaces without trees; however, the depth image given by the sensor
in cases of high light intensity conditions was not reliable enough for developing a
visual control. Besides, certain tests were also carried out to compare the newest version
of Kinect (Kinect One) with Kinect 360, which is the one utilized in this project; the
results where favorable for the new one, showing its reliability outdoors.
Due to certain problems with processing speed, experiments involving the creation of
the panoramic image were executed, showing low reliability when it came to the
detection of the base frames in the panoramic image and also showing long processing
times, which make functioning in real time impossible for the program.
Finally the tridimensional scene is successfully displayed (figure 3); however, the
calculations required for the spatial location of the frames are not accurate enough to
create a detailed mapping.
A program which intends to solve the need for the autonomous navigation of a vehicle
has been developed using the Kinect sensor. The program processes the data provided
by the sensor and spatially locates the frames; this way, it successfully recreates the
tridimensional mapping of the surroundings. However, certain problems related to the
accuracy of calculations or to the long time of processing make it impossible for the
program to work in real time, and this does not allow the program to fulfill the
requested need.
References
[1] Ambienta Magazine, mechanization on agriculture
http://www.revistaambienta.es/WebAmbienta/marm/Dinamicas/secciones/articul
os/AP.htm
[2] Microsoft Visual Studio
https://www.visualstudio.com/
[3] OpenCV Logo
http://opencv.org/
[4] OpenGL Logo
https://www.opengl.org/
[5] Scene video, available on YouTube
https://youtu.be/TM1jzjGJ7K0
[6] Scene video, available on YouTube
https://youtu.be/eR4S4tpCaIE
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
ÍNDICE DE LA MEMORIA
Índice de la memoria
2.3.3 Stitching........................................................................................................... 34
ÍNDICE DE LA MEMORIA
Bibliografía................................................................................................................ 103
ÍNDICE DE LA MEMORIA
Memoria
Índice de tablas
ÍNDICE DE FIGURAS
Índice de figuras
ÍNDICE DE FIGURAS
ÍNDICE DE FIGURAS
ÍNDICE DE FIGURAS
Parte I MEMORIA
7
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
8
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Introducción
Capítulo 1 INTRODUCCIÓN
Entre los ejemplos podemos encontrar los robots enviados al espacio para
la exploración, brazos mecánicos en las cadenas de montaje, robots
quirúrgicos, aspiradoras etc.
Es tal el crecimiento, que día a día nos llegan nuevas noticias de avances
en el campo de la navegación automática, ya sea en aviones no tripulados,
popularmente conocidos por drones, o en coches que pueden circular sin
ayuda humana por carreteras o incluso en la conducción sin piloto de un
tractor agrícola. [1]
9
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Introducción
Otros usan sonares en conjunto con una cámara simple (webcam), como
forma de evitar obstáculos [3] [4], como ejemplo, el robot de la figura 2.
10
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Introducción
Estas cámaras (digitales) pueden tener muy baja resolución o muy alta,
pero para una navegación más efectiva, es mejor conocer la profundidad,
y para ello, no sirve con una imagen sin más, que es todo lo que
proporciona una cámara, para tener visión estereoscópica, se requiere
conocer la profundidad, y esto se realiza por medio de más cámaras o
sensores adicionales (infrarrojos por ejemplo), como ejemplo, el Mars
Rover de la figura 3.
11
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Introducción
1.3 OBJETIVOS
12
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Introducción
Por tanto el objetivo es construir, con la ayuda del Kinect, una imagen en
tiempo real de la que se puedan extraer características de la escena que
nos permitan en un futuro generar las órdenes para que el vehículo
navegue en el entorno siguiendo la información proveniente de dicho
sensor.
13
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Introducción
Hardware:
- Ordenador portátil
- Sensor Kinect
Software:
- Librería OpenCV
- Librería OpenGL
14
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Capítulo 2 DESARROLLO
En esta parte se van a explicar las distintas partes en los que se organiza el
trabajo y la relación entre ellas, siguiendo la figura 5.
15
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
16
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Este sensor (originalmente llamado Project Natal) [8], fue diseñado por
Alex Kipman, y Microsoft lo desarrolló durante veinte años, como un
conjunto de sensores detectores de presencia (para responder a los
movimientos físicos), su objetivo inicial era permitir a los usuarios
17
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
interactuar y controlar la consola Xbox sin tener contacto físico con ella,
mediante un interfaz de usuario, por medio de gestos y comandos de voz.
Kinect 1.8
Flujo de datos
Sensores:
18
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
19
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
20
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
21
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Además del panel central, tiene ventanas secundarias que informan del
color (figura 11) y la profundidad (figura 12), donde las zonas más claras
indican una mayor profundidad
22
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
23
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
24
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
25
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
En este trabajo se han escogido los programas escritos en C++ que aunque
presenten una interfaz más simple (menos vistosa) a cambio tienen mayor
compatibilidad con otras librerías de tratamiento de imagen, por ejemplo
OpenCV.
26
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
27
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
manera:
int p = 0;
int l;
int inv_d[640];
int inv_I[640];
for (int k = 0; k <= 479; k++){
l = 0;
for (l = 0; l <= 639; l++){
USHORT depth = pPixelRun->depth;
USHORT index = pPixelRun->playerIndex;
inv_d[l] = depth;
inv_I[l]=index;
pPixelRun++;
}
for (int h = 0; h <= 639; h++){
LUT_depth[frame_complete] = inv_d[639 - h];
LUT_index[frame_complete] = inv_I[639 - h];
++rgbrun;
*rgbrun =
m_depthColorTable[LUT_index[frame_complete]][LUT_depth[frame_complete]];
if (n_image == 1){
LUT_depth_matrixIMPAR[h][k] = LUT_depth[p] *
255 / 1250;
}else{
LUT_depth_matrixPAR[h][k] = LUT_depth[p] * 255
/ 1250;
}
p++;
frame_complete++;
}
}
28
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
LUT_B_matrixPAR[x][y] = m_pBuffer[p];
LUT_B_matrix[x][y] = m_pBuffer[p];
p++;
LUT_G_matrixPAR[x][y] = m_pBuffer[p];
LUT_G_matrix[x][y] = m_pBuffer[p];
p++;
LUT_R_matrixPAR[x][y] = m_pBuffer[p];
LUT_R_matrix[x][y] = m_pBuffer[p];
p++;
p++;
}
}
}
29
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
PANORÁMICA
30
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Una vez tenemos los valores de las imágenes RGB, tenemos que pasarlos
al formato adecuado para trabajar con ellos, en este caso el formato Mat,
que no es más que una versión alterada de una matriz normal, en la que
cada componente de la matriz almacena tres valores, estos valores pueden
ir de 0 a 255 como en la figura 18 o como números decimales entre el 0 y el
1, tal como se muestra en la figura 19. [14]
31
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
32
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
33
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
2.3.3 STITCHING
34
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
35
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
36
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Estos puntos de interés son lugares de la imagen que están bien definidos,
tanto matemáticamente como gráficamente en la imagen, y permanecen
estables frente a perturbaciones (filtrado de imagen, cambios de color, su
estructura sigue destacando frente a los demás), aquí se comparan estos
puntos de interés en dos imágenes, y se detecta la correlación ambas.
[16][17]
37
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Una vez tengo los puntos de interés detectados, para evitar tiempo de
trabajo y posibles errores debidos a pequeñas deformaciones, se hace un
filtrado de puntos de interés, para obtener solo los más relevantes, y que
puedan determinar con certeza la localización del recorte en la escena, por
medio del siguiente código:
BFMatcher matcher(NORM_L2);
vector<DMatch> matches_N;
matcher.match(queryDescriptors_N, trainDescriptors_N, matches_N);
Mat img_matches_N;
drawMatches(queryImg_N, queryKeypoints_N, trainImg_N,
trainKeypoints_N, matches_N, img_matches_N);
vector< DMatch > good_matches;
double min_dist = 100;
for (int i = 0; i < queryDescriptors_N.rows; i++)
{
if (matches_N[i].distance < 3 * min_dist)
{
good_matches.push_back(matches_N[i]);
}
}
obj_N.push_back(queryKeypoints_N[good_matches[i].queryIdx].pt);
scene_N.push_back(trainKeypoints_N[good_matches[i].trainIdx].pt);
}
vector<Point2f> obj_corners(4);
obj_corners[0] = cvPoint(0, 0); obj_corners[1] =
cvPoint(queryImg_N.cols, 0);
obj_corners[2] = cvPoint(queryImg_N.cols, queryImg_N.rows);
obj_corners[3] = cvPoint(0, queryImg_N.rows);
perspectiveTransform(obj_corners, scene_corners, H);
38
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
39
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
if (select == 0){
X_Base = x_central;
Y_Base = y_central;
}else{
X_New = x_central;
Y_New = y_central;
}
}
40
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Mat_Omega[numero][1] = -l + 640 / 2;
Mat_Omega[numero][2] = -k + 480 / 2;
Mat_Omega[numero][3] = LUT_depth_matrixPAR[l][k];
Mat_Omega[numero][4] = LUT_1RGB[640 - l][k][0];
Mat_Omega[numero][5] = LUT_1RGB[640 - l][k][1];
Mat_Omega[numero][6] = LUT_1RGB[640 - l][k][2];
}
vueltas++;
41
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
42
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
43
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Para determinar los puntos 2 y 0´de la figura 26, tengo que determinar
cuáles son los puntos del recuadro gris que se encuentran dentro del rojo,
para ello tengo que determinar con cuantos lados del polígono
interseccionan avanzando en la misma dirección (y paralelamente a un
eje), esto se puede apreciar en la figura 27, donde se muestran varios
puntos R.V y N y se aprecia el numero de intersecciones; la prolongación
de los puntos que están dentro del polígono, interseccionan una sola vez
con los lados, mientras que los que no pertenecen al área interna del
polígono, interseccionan dos veces o ninguna.
44
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
if (vecX_Base[r1] != vecX_Base[r2]){
alpha1 = (vecY_Base[r1] - vecY_Base[r2]) /
(vecX_Base[r1] - vecX_Base[r2]);
}
char szb[255];
sprintf_s(szb, "\n alpha: %f ", alpha1);
float Beta1 = vecY_Base[r1] - alpha1*vecX_Base[r1];
sprintf_s(szb, "\n beta: %f ", Beta1);
if (alpha1!=0){
C_X = (w_Y - Beta1) / alpha1;
}
else{
C_X = vecX_Base[r1];
45
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
if (vecX_Base[r1] != vecX_Base[r2]){
if (alpha1 != 0){
C_X = (w_Y - Beta1) / alpha1;
}
else{
C_X = vecX_Base[r1];
}
46
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
OutputDebugStringA(sza);
if (primera+segunda+tercera+cuarta==1){
rr = 1;
///pertenece
}
return rr;
Tras repetir el para el otro polígono y para todos los puntos, finalmente
obtengo al menos dos puntos que se encuentran en el área de intersección.
Comparando las diferencias en los valores de profundidad de los puntos
(estos puntos pertenecen a los dos fotogramas al mismo tiempo)
determino el ángulo de giro respecto al eje X y al eje Y, determinándolo a
partir de las diferencias de valores de profundidad y las coordenadas en
X, como se explica en la figura 28, cabe resaltar que ciertas operaciones
trigonométricas, necesarias para realizar los cálculos, ralentizan o incluso
pueden detener el proceso.
47
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Mat_Omega[numero][0] = numero;
48
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
}
vueltas++;
}
49
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
50
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(1280, 960);
glutInitWindowPosition(50, 50);
glutCreateWindow(title);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
initGL();
51
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
glBegin(GL_POINTS);
for (int i = 0; i < numero;i++){
glColor3f(Mat_Omega[i][4]/255.f, Mat_Omega[i][5]/255.f,
Mat_Omega[i][6]/255.f);
glVertex3f(Mat_Omega[i][1]/3, Mat_Omega[i][2]/3,
Mat_Omega[i][3]/3);
}
glEnd();
glutSwapBuffers();
angleCube -= 0.2;
}
52
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
53
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
54
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
55
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
Una vez se han eliminando los valores residuales (medidas con valor de
profundidad nulo) detectados antes, se procede a juntar varios fotogramas
y representarlos, como muestra la figura 34; en esta representación, se
puede apreciar un círculo rojo, éste señala áreas que quedan inaccesibles a
la vista (el display tiene un rango limite en la distancia de los puntos), que
se mostraran en el display conforme se vallan acercando.
56
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
57
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
58
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Desarrollo
59
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
60
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Capítulo 3 RESULTADOS/EXPERIMENTOS
ILUMINACIÓN
61
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
pertenecen a zonas donde se está reflejando la luz del sol, por lo que se
están produciendo pequeños deslumbramientos.
62
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Por último, la figura 39 fue tomada durante la noche, sin fuentes de luz, tal
y como se aprecia en la imagen a color, sin embargo, la imagen de
profundidad aparece bien definida, no existen zonas de deslumbramiento
y se perciben perfectamente los contornos de las figuras.
En este apartado se compararán las dos versiones del sensor Kinect, por
un lado, la más reciente, y perteneciente a la segunda generación, el Kinect
One, y por el otro el Kinect 360 que es la versión previa, y el que se usa en
este proyecto.
63
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Para ello, se van a tomar capturas en entornos con alta luminosidad (que
como se vio en el apartado 3.1.1, son las que inhabilitan al Kinect 360 para
su uso en exteriores).
La figura 40 muestra la captura del Kinect One, tanto imagen a color como
de profundidad, el Kinect One es capaz de captar la imagen de
profundidad con pocos errores, además de tener una calidad superior.
Por otra parte, la figura 41, muestra la captura que el sensor Kinect 360 es
capaz de realizar en entornos luminosos, en este caso, el sensor no percibe
imagen de profundidad alguna.
64
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
65
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
66
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Para ello, se capturan las imágenes mostradas en la figura 44, que serán las
que conformen la escena mediante ambas herramientas, para comparar su
efectividad.
67
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
68
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Herramienta Tiempo(s)
Stitching 11.5
69
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
70
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
71
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
72
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Figura 54 Stitching-arriba 2
73
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Figura 55 Localización-arriba 2
74
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Figura 57 Stitching-abajo
75
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Figura 58 Localización-abajo
76
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
El Stitching devuelve esta vez una escena no uniforme, tal y como aparece
en la figura 60, sin embargo, se corresponde bastante bien con la realidad.
Figura 60 Stitching-derecha
77
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Figura 61 Localización-derecha
78
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Figura 63 Stitching-izquierda
79
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Figura 64 Localización-izquierda
80
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
81
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Para ello se han tomado dos fotogramas (figura 65), que difieren en la
luminosidad y se intentará formar una escena con ellos.
Figura 65 Stitching-luz
82
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Para ello, se han tomado dos imágenes en las que un objeto es omitido (la
lámpara) tal y como se muestra en la figura 66.
83
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
84
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
TRIDIMENSIONAL
85
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Mientras que en el giro sobre el eje Y (figura 71), se aprecia que el plano
rojo aparece girado 45 grados también respecto el plano blanco, el eje de
86
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
giro, es el eje central del plano rojo, que en este caso, coincide con el centro
del plano blanco.
87
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
Por otra parte, a la hora de tener escenas muy grandes, es necesario una
visión general de las mismas (figura 72), para ello, se aplica el reescalado
inverso, además en caso de no ser suficiente, el reescalado es acumulativo,
es decir, al activar el comando que disminuye la escala, se puede volver a
activar para disminuir aun más la escala.
88
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
En la figura 74, se han ido añadiendo figuras una tras otra hasta llegar al
límite.
89
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
90
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
En esta primera escena (figura 77), el mapeado está formado por la unión
de tres fotogramas, cabe resaltar, que hay zonas en las que se superponen
los fotogramas (por ejemplo solo se ve la mitad del televisor), esto es un
problema de la herramienta de representación, que en caso de
superposición, representa el más cercano al observador.
91
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
92
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
93
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
94
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
95
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Resultados/Experimentos
96
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Conclusiones
Capítulo 4 CONCLUSIONES
En primer lugar se han extraído con éxito los datos proporcionados por el
sensor Kinect, tanto de color como de profundidad, y esos datos han sido
invertidos para coincidir con la imagen real.
97
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Conclusiones
Por otra parte la viabilidad del Kinect (versión 1.8) como sensor no es del
todo adecuada, debido a la alta posibilidad de deslumbramiento en
exteriores, que “cegarían” la cámara y podría transmitir errores (dan los
valores erróneos de cero milímetros de distancia en las áreas
deslumbradas, inhibiendo su capacidad para detectar obstáculos próximos
en esas zonas, ver apartados 3.1.1 y 3.1.2)
98
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Futuros desarrollos
Además, el sensor Kinect 360 que se usa en este proyecto, no es apto para
condiciones en el exterior (apartado 3.1.1) ya que en situaciones de alta
luminosidad no funciona correctamente.
99
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Futuros desarrollos
inputs más comunes del usuario como getchar() o waitKey(); otra forma
seria ajustando el bucle de OpenGL y haciendo que este regule el
programa, pero es poco recomendable (apartado 2.4.1)
100
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Futuros desarrollos
101
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
102
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Bibliografía
BIBLIOGRAFÍA
http://es.wikipedia.org/wiki/Kinect
[11] Microsoft Download Center Kinect for Windows SDK v 1.8
https://www.microsoft.com/en-us/download/details.aspx?id=40278
103
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Bibliografía
104
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Bibliografía
https://www.youtube.com/watch?v=V-SSGvK6s-
A&list=PLITBzsKx59J3E5b9FjKyEqoPBxli_1gjI
[26] Point Cloud Library
http://pointclouds.org/about/
[27] Wikibooks OpenGL
https://en.wikibooks.org/wiki/OpenGL_Programming
[28] OpenCV Download
http://opencv.org/downloads.html
[29] OpenGL Download
https://www.opengl.org/wiki/Getting_Started
105
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Bibliografía
106
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Bibliografía
Parte II ESTUDIO
ECONÓMICO
107
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
108
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Estudio económico
Con el Kinect, se tiene una mayor fiabilidad en los datos, ya que ha sido
programado y testeado; cosa que no ocurre en otros sistemas, como si se
implementase con cámaras normales para después calcular los valores de
profundidad y color (la escena); esto hace que el precio del desarrollo
disminuya enormemente, ya que los datos proporcionados por los
sensores no requieren ser calculados a partir de la diferencia de las
imágenes proporcionadas por las cámaras (que son más baratas) además
el hecho de incluir el sensor Kinect, implica un coste menor, ya que este
está orientado a mas campos que al de navegación autónoma, lo que le
proporciona mayor número de clientes y disminuye su precio.
109
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Estudio económico
Una cosa a tener en cuenta es el relativo poco mercado que existe, ya que
si hubiera más demanda, hacer un sistema de navegación con cámaras
normales, aunque poseyera un desarrollo del prototipo mucho más
costoso, el coste de construcción por unidad es más barato (los
componentes son más baratos), lo que rebajaría mucho su precio (cubriría
más fácilmente los costes de desarrollo).
110
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Estudio económico
111
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
112
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Mediciones
Capítulo 1 MEDICIONES
Ordenador Toshiba
1 300 1000
Satellite i3
113
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Mediciones
Microsoft Visual
1 300 380
Studio Ultimate 2013
Librería OpenGL 1 70 70
Actividad Horas
Programación 65
Documentación 85
Pruebas y testeo 70
Solución de errores 90
114
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Precios unitarios
Kinect 360 70
Elemento Precio[€/ud]
115
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Precios unitarios
Actividad Precio[€/ud]
Programación 25
Documentación 30
Pruebas y testeo 30
Solución de errores 40
116
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Sumas parciales
Horas Horas
Equipo y Amortización
Cantidad de de uso Precio[€/ud] Coste total(€)
hardware anual
proyecto al año
Ordenador
Toshiba 1 300 1000 800 25% 200
Satellite i3
Cable USB
1 280 280 15 10% 13.5
Kinect
Total 262.5
117
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Sumas parciales
Horas
Horas de Amortización
Elemento Cantidad de uso Precio[€/ud] Coste total
proyecto Anual
al año
Microsoft Visual
Studio Ultimate 1 300 500 3328 20% 2662.4
2013
Total 2686.2
Programación 65 25 1625
Documentación 85 30 2550
Total 9875
118
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Presupuesto general
Concepto Coste(€)
Total 12823.7
119
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Presupuesto general
120
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Presupuesto general
121
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
122
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
#include "resource.h"
#include <stdio.h>
#include "opencv2/flann/miniflann.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/photo/photo.hpp"
#include "opencv2/video/video.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/ml/ml.hpp"
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/core/core_c.h"
#include "opencv2/highgui/highgui_c.h"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/nonfree/nonfree.hpp"
#include <vector>
#include "stdafx.h"
#include <cmath>
#include "NuiImageBuffer.h"
#include "Utility.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <glut.h> ///dio problemas tiene que estar por debajo de stdlib
//////
123
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
int variableauxiliarDep = 0;
int variableauxiliarRGB = 0;
int LUT_depth_matrixPAR[640][480];
int LUT_depth_matrixIMPAR[640][480];
int LUT_depth_matrix2[640][480];
int LUT_R_matrixPAR[640][480];
int LUT_G_matrixPAR[640][480];
int LUT_B_matrixPAR[640][480];
int LUT_R_matrixIMPAR[640][480];
int LUT_G_matrixIMPAR[640][480];
int LUT_B_matrixIMPAR[640][480];
int LUT_R_matrix[640][480];
int LUT_G_matrix[640][480];
int LUT_B_matrix[640][480];
int LUT_R_matrix2[640][480];
int LUT_G_matrix2[640][480];
int LUT_B_matrix2[640][480];
//string Sto_bitmap;
int colors[921600];
int Height = 639;
int Width = 479;
int T_timer = 0;
int GO = 10;
int mezcla = 0;
int n_image = 0;
int n_image2 = 0;
int cuenta1,cuenta2,cuenta3 = 0;
int LUT_1RGB[640][480][3];
int LUT_2RGB[640][480][3];
float vecX_Base[] = { 0, 0, 0, 0 };
float vecY_Base[] = { 0, 0, 0, 0 };
float vecX_New[] = { 0, 0, 0, 0 };
124
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
float vecY_New[] = { 0, 0, 0, 0 };
float X_Base, Y_Base, X_New, Y_New = 0;
float vectorXY_desp[50][3];///50 por ejemplo, hay que cambiarlo 0 es X 1
es Y 2 es Z
float vec[3][10];
float centros[50][3]; ///0 es X, 1 es Y, 2 es Z
#define BYTES_PER_PIXEL_RGB 4
#define BYTES_PER_PIXEL_INFRARED 2
#define BYTES_PER_PIXEL_BAYER 1
#define BYTES_PER_PIXEL_DEPTH sizeof(NUI_DEPTH_IMAGE_PIXEL)
#define COLOR_INDEX_BLUE 0
#define COLOR_INDEX_GREEN 1
#define COLOR_INDEX_RED 2
#define COLOR_INDEX_ALPHA 3
/// <summary>
/// Constructor
/// </summary>
NuiImageBuffer::NuiImageBuffer()
: m_nearMode(false)
, m_depthTreatment(CLAMP_UNRELIABLE_DEPTHS)
, m_nSizeInBytes(0)
, m_width(0)
, m_height(0)
, m_srcWidth(0)
, m_srcHeight(0)
, m_pBuffer(nullptr)
{
////aqui inicializo la matriz en la que podre los vectores
Mat_Omega[numero_puntos][7]; /// numero,X,Y,Z, R,G,B
for (int p = 0; p < numero_puntos; p++) {
Mat_Omega[p][0]=p;
125
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
InitDepthColorTable();
}
/// <summary>
/// Destructor
/// </summary>
NuiImageBuffer::~NuiImageBuffer()
{
SafeDelete(m_pBuffer);
}
/// <summary>
/// Set image size according to image resolution
/// </summary>
/// <param name="resolution">Image resolution</param>
void NuiImageBuffer::SetImageSize(NUI_IMAGE_RESOLUTION resolution)
{
GetImageSize(resolution, m_srcWidth, m_srcHeight);
}
/// <summary>
/// Calculate image width and height according to image resolution
enumeration value.
/// If resolution enumeration is invalid, width and height will be set to
zero.
/// </summary>
/// <param name="resolution">Enumeration value which indicates the image
resolution format</param>
/// <param name="width">Calculated image width</param>
/// <param name="height">Calculated image height</param>
void NuiImageBuffer::GetImageSize(NUI_IMAGE_RESOLUTION resolution, DWORD&
width, DWORD& height)
{
NuiImageResolutionToSize(resolution, width, height);
}
/// <summary>
/// Get width of image.
/// </sumamry>
/// <returns>Width of image.</returns>
DWORD NuiImageBuffer::GetWidth() const
{
return m_width;
}
/// <summary>
/// Get height of image.
/// </sumamry>
/// <returns>Width of height.</returns>
DWORD NuiImageBuffer::GetHeight() const
{
return m_height;
}
126
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
/// <suumary>
/// Get size of buffer.
/// <summary>
/// <returns>Size of buffer.</returns>
DWORD NuiImageBuffer::GetBufferSize() const
{
return m_nSizeInBytes;
}
/// <summary>
/// Return allocated buffer.
/// </summary>
/// <returns>
/// The pointer to the allocated buffer
/// Return value could be nullptr if the buffer is not allocated
/// </returns>
BYTE* NuiImageBuffer::GetBuffer() const
{
return m_pBuffer;
}
/// <summary>
/// Allocate a buffer of size and return it
/// </summary>
/// <param name="size">Size of buffer to allocate</param>
/// <returns>The pointer to the allocated buffer. If size hasn't changed,
the previously allocated buffer is returned</returns>
BYTE* NuiImageBuffer::ResetBuffer(UINT size)
{
if (!m_pBuffer || m_nSizeInBytes != size)
{
SafeDeleteArray(m_pBuffer);
if (0 != size)
{
m_pBuffer = new BYTE[size];
}
m_nSizeInBytes = size;
}
printf("\n\nalphaBuffer \n\n");
return m_pBuffer;
}
/// <summary>
/// Clear buffer
/// </summary>
void NuiImageBuffer::Clear()
{
m_width = 0;
m_height = 0;
ResetBuffer(0);
}
/// <summary>
/// Initialize the depth-color mapping table.
/// </summary>
127
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
void NuiImageBuffer::InitDepthColorTable()
{
ZeroMemory(m_depthColorTable, sizeof(m_depthColorTable));
switch (m_depthTreatment)
{
case CLAMP_UNRELIABLE_DEPTHS:
// Fill in the "near" portion of the table with solid color
for (int depth = UNKNOWN_DEPTH + 1; depth < minReliableDepth;
depth++)
{
m_depthColorTable[0][depth] = TOO_NEAR_COLOR;
}
case TINT_UNRELIABLE_DEPTHS:
{
// Fill in the "near" portion of the table with a tinted
gradient
for (int depth = UNKNOWN_DEPTH + 1; depth < minReliableDepth;
depth++)
{
BYTE intensity = GetIntensity(depth);
BYTE r = intensity >> 3;
BYTE g = intensity >> 1;
BYTE b = intensity;
SetColor(&m_depthColorTable[0][depth], r, g, b);
128
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
SetColor(&m_depthColorTable[0][depth], r, g, b);
}
}
break;
case DISPLAY_ALL_DEPTHS:
minReliableDepth = MIN_DEPTH;
maxReliableDepth = MAX_DEPTH;
default:
break;
}
/// <summary>
/// Set color value
/// </summary>
/// <param name="pColor">The pointer to the variable to be set with
color</param>
/// <param name="red">Red component of the color</param>
/// <param name="green">Green component of the color</parma>
/// <param name="blue">Blue component of the color</param>
/// <param name="alpha">Alpha component of the color</param>
void NuiImageBuffer::SetColor(UINT* pColor, BYTE red, BYTE green, BYTE
blue, BYTE alpha)
{
if (!pColor)
return;
BYTE* c = (BYTE*)pColor;
c[COLOR_INDEX_RED] = red;
c[COLOR_INDEX_GREEN] = green;
c[COLOR_INDEX_BLUE] = blue;
c[COLOR_INDEX_ALPHA] = alpha;
}
129
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
/// <summary>
/// Calculate intensity of a certain depth
/// </summary>
/// <param name="depth">A certain depth</param>
/// <returns>Intensity calculated from a certain depth</returns>
BYTE NuiImageBuffer::GetIntensity(int depth)
{
// Validate arguments
if (depth < MIN_DEPTH || depth > MAX_DEPTH)
{
return UCHAR_MAX;
}
// Use a logarithmic scale that shows more detail for nearer depths.
// The constants in this formula were chosen such that values between
// MIN_DEPTH and MAX_DEPTH will map to the full range of possible
// byte values.
const float depthRangeScale = 500.0f;
const int intensityRangeScale = 74;
return (BYTE)(~(BYTE)min(
UCHAR_MAX,
log((double)(depth - MIN_DEPTH) / depthRangeScale + 1) *
intensityRangeScale));
}
/// <summary>
///Stacks an image in the Mat format
/// </summary>
void Mat_Image(Mat pImage,int unoo2)
{
for (int rw = 0; rw <479; rw++){
for (int cl = 0; cl < 639; cl++){
Mat paso_punto(1, 1, CV_8UC3, Scalar(LUT_B_matrix[639-
cl][rw], LUT_G_matrix[639-cl][rw], LUT_R_matrix[639-cl][rw]));
paso_punto.copyTo(pImage.row(rw).col(cl));//para que
funcione
if (unoo2==1){
LUT_1RGB[cl][rw][0] = LUT_R_matrix[cl][rw];
LUT_1RGB[cl][rw][1] = LUT_G_matrix[cl][rw];
LUT_1RGB[cl][rw][2] = LUT_B_matrix[cl][rw];
}
else{
LUT_2RGB[cl][rw][0] = LUT_R_matrix[cl][rw];
LUT_2RGB[cl][rw][1] = LUT_G_matrix[cl][rw];
LUT_2RGB[cl][rw][2] = LUT_B_matrix[cl][rw];
}
}
}
130
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
// OpenGL setup
glClearColor(0, 0, 0, 1);// Set background color to black and opaque
glClearDepth(1); // Set background depth to farthest
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// aparece en
display
/////////
// Global variables:
GLuint vboId; // Vertex buffer ID
GLuint cboId; // Color buffer ID
//int D = depth_M[314][239];
///std::cout << D;
///La primera coorodenada els la del eje de coordenadas (horizontal)
la 2 es ordenadas (altura) y la ultima es profundidad
int D = 800;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color
and depth buffers
glMatrixMode(GL_MODELVIEW); // To operate on model-view matrix
glLoadIdentity();
glRotatef(angleCube, 0, 1, 0);
glPointSize(1);// le he puesto mucho tamaño
131
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
glVertex3f(Mat_Omega[i][1] / 3 / reescalado,
Mat_Omega[i][2] / 3 / reescalado, Mat_Omega[i][3] / 3 / reescalado);
}
}
// II
glColor3f(1, 0, 0); // Red
glVertex3f(w / 2, h / 2, w);
*/
// III
glColor3f(0, 255, 255); // blue
glVertex3f(w / 2, -h / 2, -w);
// IV
glColor3f(0, 1, 0); // Green
glVertex3f(-w / 2, -h / 2, -w);
// V
glColor3f(255, 51, 0); // White
glVertex3f(0, 0, D - D);
glEnd();
glLineWidth(4);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);
for (int i = 0; i < cuenta2; i++){
132
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
glVertex3f(centros[cuenta2][0], centros[cuenta2][0],
centros[cuenta2][0]);
glVertex3f(30+5*i, 5*i, 30);
}
glEnd();
*/
glutSwapBuffers();
angleCube -= 0.2;
if (height == 0) height = 1;
GLfloat aspect = (GLfloat)width / (GLfloat)height;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); // reset
case 'o':
case 'O':
reescalado = 1;
break;
case 'i':
case 'I':
reescalado = reescalado/2;
break;
133
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
break;
}
}
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(1280, 960);
glutInitWindowPosition(50, 50);
glutCreateWindow(title);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
initGL();
}
/////
void fcn_Square(Mat queryImg_N, Mat trainImg_N, int BaseorNew){
SiftFeatureDetector detector(400);
vector<KeyPoint> queryKeypoints_N, trainKeypoints_N;
detector.detect(queryImg_N, queryKeypoints_N);
detector.detect(trainImg_N, trainKeypoints_N);
134
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
SiftDescriptorExtractor extractor;
size = trainDescriptors_N.size();
BFMatcher matcher(NORM_L2);
vector<DMatch> matches_N;
matcher.match(queryDescriptors_N, trainDescriptors_N, matches_N);
printf("Found %d matches.\n", matches_N.size());
//namedWindow("matches", 1);
Mat img_matches_N;
drawMatches(queryImg_N, queryKeypoints_N, trainImg_N,
trainKeypoints_N, matches_N, img_matches_N);
// imshow("matches", trainImg);
//////
vector< DMatch > good_matches;
double min_dist = 100;
for (int i = 0; i < queryDescriptors_N.rows; i++)
{
if (matches_N[i].distance < 3 * min_dist)
{
good_matches.push_back(matches_N[i]);
}
}
//Localiza
vector<Point2f> obj_N;
vector<Point2f> scene_N;
obj_N.push_back(queryKeypoints_N[good_matches[i].queryIdx].pt);
scene_N.push_back(trainKeypoints_N[good_matches[i].trainIdx].pt);
}
135
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
//obtiene esqunas
vector<Point2f> obj_corners(4);
obj_corners[0] = cvPoint(0, 0); obj_corners[1] =
cvPoint(queryImg_N.cols, 0);
obj_corners[2] = cvPoint(queryImg_N.cols, queryImg_N.rows);
obj_corners[3] = cvPoint(0, queryImg_N.rows);
vector<Point2f> scene_corners(4);
//dibujar lineas
line(img_matches_N, scene_corners[0] + Point2f(queryImg_N.cols, 0),
scene_corners[1] + Point2f(queryImg_N.cols, 0), Scalar(0, 255, 0), 4);
line(img_matches_N, scene_corners[1] + Point2f(queryImg_N.cols, 0),
scene_corners[2] + Point2f(queryImg_N.cols, 0), Scalar(0, 255, 0), 4);
line(img_matches_N, scene_corners[2] + Point2f(queryImg_N.cols, 0),
scene_corners[3] + Point2f(queryImg_N.cols, 0), Scalar(0, 255, 0), 4);
line(img_matches_N, scene_corners[3] + Point2f(queryImg_N.cols, 0),
scene_corners[0] + Point2f(queryImg_N.cols, 0), Scalar(0, 255, 0), 4);
if (BaseorNew==1){
vecX_New[0] = X_coordinate0;
vecY_New[0] = Y_coordinate0;
vecX_New[1] = X_coordinate1;
vecY_New[1] = Y_coordinate1;
vecX_New[2] = X_coordinate2;
vecY_New[2] = Y_coordinate2;
vecX_New[3] = X_coordinate3;
vecY_New[3] = Y_coordinate3;
//OutputDebugStringA("gammaaaAAAA \n\n\n\n");
}else{
vecX_Base[0] = X_coordinate0;
vecY_Base[0] = Y_coordinate0;
vecX_Base[1] = X_coordinate1;
vecY_Base[1] = Y_coordinate1;
vecX_Base[2] = X_coordinate2;
vecY_Base[2] = Y_coordinate2;
vecX_Base[3] = X_coordinate3;
vecY_Base[3] = Y_coordinate3;
}
136
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
if (select == 0){
///es base
X_Base = 0;
Y_Base = 0;
X_Base = x_central;
Y_Base = y_central;
}
else{
X_New = 0;
Y_New = 0;
X_New = x_central;
Y_New = y_central;
}
/// <summary>
/// Copy color frame image to image buffer
/// </summary>
/// <param name="pImage">The pointer to the frame image to copy</param>
/// <param name="size">Size in bytes to copy</param>
void NuiImageBuffer::CopyRGB(const BYTE* pImage, UINT size){
//OutputDebugStringA("\nprueba RGB\n");
// Check source buffer size
//OutputDebugStringA("\n alpha \n");
if (size != m_srcWidth * m_srcHeight * BYTES_PER_PIXEL_RGB){
137
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
return;
}
// Set image size to source image size
m_width = m_srcWidth;
m_height = m_srcHeight;
//////aatatata
int p = 0;
int dpt = 0;
int p2 = 0;
138
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
/*
char sz15[255];
sprintf_s(sz15, " R: %d ", LUT_R_matrix[300][240]); //
m_depthColorTable[300][240]);
OutputDebugStringA(sz15);
sprintf_s(sz15, " G: %d ", LUT_G_matrix[300][240]); //
m_depthColorTable[300][240]);
OutputDebugStringA(sz15);
sprintf_s(sz15, " B: %d ", LUT_B_matrix[300][240]); //
m_depthColorTable[300][240]);
OutputDebugStringA(sz15);
*/
///////
/////////////
char sz152[255];
variableauxiliarRGB = variableauxiliarRGB + 10;
sprintf_s(sz152, " RGB=VarAuxDepth: %d ", variableauxiliarDep); //
m_depthColorTable[300][240]);
OutputDebugStringA(sz152);
sprintf_s(sz152, " ((RGB: %d)) \n", variableauxiliarRGB); //
m_depthColorTable[300][240]);
OutputDebugStringA(sz152);
/// <summary>
/// Copy raw bayer data and convert to RGB image
/// </summary>
/// <param name="pImage">The pointer to the frame image to copy</param>
/// <param name="size">Size in bytes to copy</param>
void NuiImageBuffer::CopyBayer(const BYTE* pImage, UINT size)
{
// Check source buffer size
if (size != m_srcWidth * m_srcHeight * BYTES_PER_PIXEL_BAYER)
{
return;
}
139
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
{
for (DWORD x = 0; x < m_srcWidth; x += 2)
{
int firstRowOffset = (y * m_srcWidth) + x;
int secondRowOffset = firstRowOffset + m_srcWidth;
// _____
// Get bayer colors from source image // | | |
BYTE r = pImage[firstRowOffset + 1]; // |g1|r |
BYTE g1 = pImage[firstRowOffset]; // |--|--|
BYTE g2 = pImage[secondRowOffset + 1]; // |b |g2|
BYTE b = pImage[secondRowOffset]; // |__|__|
/// <summary>
/// Copy and convert infrared frame image to image buffer
/// </summary>
/// <param name="pImage">The pointer to the frame image to copy</param>
/// <param name="size">Size in bytes to copy</param>
void NuiImageBuffer::CopyInfrared(const BYTE* pImage, UINT size)
{
// Check source buffer size
if (size != m_srcWidth * m_srcHeight * BYTES_PER_PIXEL_INFRARED)
{
return;
}
//OutputDebugStringA("\nprueba Infarred\n");
// Converted image size is equal to source image size
m_width = m_srcWidth;
m_height = m_srcHeight;
140
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
if (vecX_Base[r1] != vecX_Base[r2]){
alpha1 = (vecY_Base[r1] - vecY_Base[r2]) /
(vecX_Base[r1] - vecX_Base[r2]);
}
char szb[255];
sprintf_s(szb, "\n alpha: %f ", alpha1);
//OutputDebugStringA(szb);
float Beta1 = vecY_Base[r1] - alpha1*vecX_Base[r1];
sprintf_s(szb, "\n betab: %f ", Beta1);
//OutputDebugStringA(szb);
if (alpha1!=0){
C_X = (w_Y - Beta1) / alpha1;
}
else{
C_X = vecX_Base[r1];
}
if (vecX_Base[r1] != vecX_Base[r2]){
141
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
if (vecX_New[r1] != vecX_New[r2]){
alpha1 = (vecY_New[r1] - vecY_New[r2]) /
(vecX_New[r1] - vecX_New[r2]);
}
if (alpha1 != 0){
C_X = (w_Y - Beta1) / alpha1;
}
else{
C_X = vecX_Base[r1];
}
142
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
if (vecX_New[r1] != vecX_New[r2]){
if (alpha1 != 0){
C_X = (w_Y - Beta1) / alpha1;
}
else{
C_X = vecX_New[r1];
}
//OutputDebugStringA("priemro escanado\n");
/// segunda 1-2
int segunda = inter_recta(1, 2, w_X1, w_Y1);
//OutputDebugStringA("segundo escanado\n");
///tercera 01
int tercera = inter_recta(0, 1, w_X1, w_Y1);
//OutputDebugStringA("tercero escanado\n");
// ///cuarta 32
int cuarta = inter_recta(3, 2, w_X1, w_Y1);
// char sza[255];
// sprintf_s(sza, "\n awi p1: %d ,p2: %d,p3: %d,p4: %d \n ",
primera,segunda, tercera,cuarta);
// OutputDebugStringA(sza);
if (primera+segunda+tercera+cuarta==1){
rr = 1;
}
return rr;
//// si dentro o si fuera
}
int intersec_PuntoDos(float w_X1, float w_Y1){
int rr = 0;
143
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
///tercera 01
int tercera = inter_rectaDos(0, 1, w_X1, w_Y1);
// ///cuarta 32
int cuarta = inter_rectaDos(3, 2, w_X1, w_Y1);
}
void Cuatro_Puntos(int x_1, int x_2, int x_3, int x_4 ){
///////////////// tengo las 4 aristas en vecX_Base, vecY_Base y
vecX_New , vecY_New
///esta el priemr punto dentro?
/////////////////
////se continua con los demas puntos
}
void Cuatro_PuntosDos(int x_1, int x_2, int x_3, int x_4){
///////////////// tengo las 4 aristas en vecX_Base, vecY_Base y
vecX_New , vecY_New
144
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
/////////////////
////se continua con los demas puntos
}
////obtener giro, rotacion y diferencia de profunidad
void Cambio_Imagenes(float giroY,float giroX, int Z){
145
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
if (CuatroDos[i] == 1){
punto_FotBase[0] = vecX_Base[i];
punto_FotBase[1] = vecY_Base[i];
}
if (CuatroDos[i]==1){
punto_FotNew[0] = vecX_New[i];
punto_FotNew[1] = vecY_New[i];
}
}
///localizacion punto
//punto base
if (n_image==1){
int x = punto_FotNew[0] - X_Base;///calculo las diferencias
int y = punto_FotNew[1] - Y_Base;
Prof_New_Base[0] = LUT_depth_matrixPAR[x][y];///tengo la
profundidad
int x2 = punto_FotBase[0] - X_New;///calculo las diferencias
int y2 = punto_FotBase[1] - Y_New;
Prof_New_Base[1] = LUT_depth_matrixPAR[x2][y2];///tengo la
profundidad
}
else{
int x = punto_FotNew[0] - X_Base;///calculo las diferencias
int y = punto_FotNew[1] - Y_Base;
Prof_New_Base[0] = LUT_depth_matrixIMPAR[x][y];
int x2 = punto_FotBase[0] - X_New;///calculo las diferencias
int y2 = punto_FotBase[1] - Y_New;
Prof_New_Base[1] = LUT_depth_matrixIMPAR[x2][y2];///tengo la
profundidad
}
giroY = atan((Prof_New_Base[0] - Prof_New_Base[0]) / (X_Base -
X_New));///dan muchos problemas
giroX = atan((Prof_New_Base[0] - Prof_New_Base[0]) / (Y_Base -
Y_New));///dan muchos problemas
Z = Prof_New_Base[1] - Prof_New_Base[0];
/// <summary>
/// Copy and convert depth frame image to image buffer
/// </summary>
/// <param name="pImage">The pointer to the frame image to copy</param>
/// <param name="size">Size in bytes to copy</param>
/// <param name="nearMode">Depth stream range mode</param>
/// <param name="treatment">Depth treatment mode</param>
void NuiImageBuffer::CopyDepth(const BYTE* pImage, UINT size, BOOL
nearMode, DEPTH_TREATMENT treatment)
{
frame_complete = 0;
// Check source buffer size
if (size != m_srcWidth * m_srcHeight * BYTES_PER_PIXEL_DEPTH)
{
return;
}
146
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
// Check if range mode and depth treatment have been changed. Re-
initlialize depth-color table with changed parameters
if (m_nearMode != (FALSE != nearMode) || m_depthTreatment != treatment)
{
m_nearMode = (FALSE != nearMode);
m_depthTreatment = treatment;
InitDepthColorTable();
}
////relleno la matriz
int p = 0;
int l;
int inv_d[640];
int inv_I[640];
for (int k = 0; k <= 479; k++){
l = 0;
for (l = 0; l <= 639; l++){
USHORT depth = pPixelRun->depth; /// este es el valor
USHORT index = pPixelRun->playerIndex;
//int depth = pBufferRun->depth; //saca la profundidad
del sitio
inv_d[l] = depth;
inv_I[l]=index;
pPixelRun++;
}
for (int h = 0; h <= 639; h++){
LUT_depth[frame_complete] = inv_d[639 - h];
LUT_index[frame_complete] = inv_I[639 - h];
++rgbrun;
*rgbrun =
m_depthColorTable[LUT_index[frame_complete]][LUT_depth[frame_complete]];
//LUT_depth_matrix[h][k] = LUT_depth[p];
if (n_image == 1){ ///porque se actualiza despues, va
cambiado
LUT_depth_matrixIMPAR[h][k] = LUT_depth[p] * 255
/ 1250;
}else{
147
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
p++;
frame_complete++;
}
}
variableauxiliarDep = variableauxiliarDep + 25;
///
////
char sz15[255];
sprintf_s(sz15, "(( Depth: %d ))", variableauxiliarDep); //
m_depthColorTable[300][240]);
//OutputDebugStringA(sz15);
/////////////////////////////////////////////////////////////////////
//////////////////////
////toca sacar imagenes
/////////////////////////////////////////////////////////////////////
//////////////////////
if (Inicio_SCAN == 0){
if (T_timer >= GO){ ///cuando el contador llega al momento
fijado de inicio (GO es el numero de bucles)
if (n_image == 1){
OutputDebugStringA("PAR \n");
148
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
////PAR
////Imagen Base
if (cuenta1 == 0){
OutputDebugStringA("\n Primer fotograma,
el BASE \n");
Mat_Image(LUT_1,1); /// va a la funcion
dada, que carga la imagen
cuenta1 = 1; /// para no volver a pasar
por aqui
namedWindow("L1 first",
CV_WINDOW_AUTOSIZE);
imshow("L1 first", LUT_1);
///////////
///copio la primera imagen al vector
requerido
int vueltas = 0;
Mat_Omega[numero][1] = -l +
640 / 2;///x
Mat_Omega[numero][2] = -k +
480 / 2;///y
Mat_Omega[numero][3] =
LUT_depth_matrixPAR[l][k];///z
Mat_Omega[numero][4] =
LUT_1RGB[640 - l][k][0];// LUT_R_matrixPAR[640 - l][k];///R
Mat_Omega[numero][5] =
LUT_1RGB[640 - l][k][1];//LUT_G_matrixPAR[640 - l][k];///G
Mat_Omega[numero][6] =
LUT_1RGB[640 - l][k][2];// LUT_B_matrixPAR[640 - l][k];///B No puedo
poner PAR, porque se escaneo antes de eso
}
vueltas++;
}
numero=numero - 480;///307200
centros[0][1] = 0;
centros[0][0] = 0;
centros[0][2] =
LUT_depth_matrixPAR[320][240];
//aqui se carga L1, pero no se autoriza
OpenGL_3D(0); ///para saltar, se quita
}else{
//////////
//cargo L1 y autorizo
Mat_Image(LUT_1,1);
mezcla = 1;
}
149
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
}
if (n_image == 2){
n_image = 0;
OutputDebugStringA("IMPAR \n");
////IMPAR
///Cargare L2
Mat_Image(LUT_2,2);
mezcla = 1;
}
///////////////////////////////////////////////
//////////////////////////////////////////////
if (mezcla == 1){
////juntar L1 y L2, en Pares, la Base es L2, en
impares, L1 (el inicial no salta), a Stitch
/*
vecX_Base[] = { 0, 0, 0, 0 };
vecY_Base[] = { 0, 0, 0, 0 };
vecX_New[] = { 0, 0, 0, 0 };
vecY_New[] = { 0, 0, 0, 0 };
*/
//// detectar si son la misma
/////////////////////////////////////////////////////////////////////
////////
////es necesario un evento que diga que si son
la misma o han avanzado
/////////////////////si no son la misma,
comeinzo el proceso normal,
StichMix(LUT_1, LUT_2);
if (cuenta2 == 0){
namedWindow("L2 first",
CV_WINDOW_AUTOSIZE); //create a window with the name "MyWindow"
imshow("L2 first", LUT_2); //display the
image which is stored in the 'img' in the "MyWindow" window
namedWindow("MyWindow1",
CV_WINDOW_AUTOSIZE); //create a window with the name "MyWindow"
imshow("MyWindow1", Stitch); //display the
image which is stored in the 'img' in the "MyWindow" window
}
if (cuenta2 == 1){
//namedWindow("MyWindow3",
CV_WINDOW_AUTOSIZE); //create a window with the name "MyWindow"
//imshow("MyWindow3", Stitch); //display
the image which is stored in the 'img' in the "MyWindow" window
//OpenGL_3D(0);
150
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
}
if (cuenta2 == 2){
//namedWindow("MyWindow2",
CV_WINDOW_AUTOSIZE); //create a window with the name "MyWindow"
//imshow("MyWindow2", Stitch); //display
the image which is stored in the 'img' in the "MyWindow" window
//namedWindow("L1 2", CV_WINDOW_AUTOSIZE);
//create a window with the name "MyWindow"
//imshow("L1 2", LUT_1); //display the
image which is stored in the 'img' in the "MyWindow" window
}
OutputDebugStringA("JUNTAR \n");
if (n_image == 1){ //BASE L2
//es PAR
////////
/// hago los recortes
Mat Centro_Origen(LUT_2, Rect(140, 40,
400, 400)); ////chequear si los recortes son apropiados
Mat Centro_Nueva(LUT_1, Rect(140, 40, 400,
400));
///////
//// los paso a escala de grises
//cvtColor(Centro_Nueva, LUT_1,
CV_RGB2GRAY);
//cvtColor(Centro_Origen, LUT_2,
CV_RGB2GRAY);
////////
}else{
///es IMPAR
////////
/// hago los recortes
Mat Centro_Origen(LUT_1, Rect(140, 40,
400, 400)); ////chequear si los recortes son apropiados
Mat Centro_Nueva(LUT_2, Rect(140, 40,
400, 400));
///////
//// los paso a escala de grises
//cvtColor(Centro_Nueva, LUT_2,
CV_RGB2GRAY);
151
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
//cvtColor(Centro_Origen, LUT_1,
CV_RGB2GRAY);
////////
///
/////
sprintf_s(sz152, "0_Found Base X: %f and Y: %f
/// \n", vecX_Base[0], vecY_Base[0]);
OutputDebugStringA(sz152);
sprintf_s(sz152, "1_Found Base X: %f and Y: %f
/// \n", vecX_Base[1], vecY_Base[1]);
OutputDebugStringA(sz152);
sprintf_s(sz152, "2_Found Base X: %f and Y: %f
/// \n", vecX_Base[2], vecY_Base[2]);
OutputDebugStringA(sz152);
sprintf_s(sz152, "3_Found Base X: %f and Y: %f
/// \n", vecX_Base[3], vecY_Base[3]);
OutputDebugStringA(sz152);
/////////////////////
///aqui saco los valores del punto central
152
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
Cambio_Imagenes(giro,giro2, Z_prof);////cuidado
con las operaciones trigonometricas, da muchos errores
///////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
///
if (n_image == 1){
////PAR, añado LUT_1
char sz152[255];
int vueltas = 0;
Mat_Omega[numero][0] =
numero;
Mat_Omega[numero][1] = -l +
640 / 2 + X_New - X_Base + centros[cuenta2][0] - (-l + 640 / 2)*(1 -
cos(giro));///x
Mat_Omega[numero][2] = -k +
480 / 2 + Y_New - Y_Base + centros[cuenta2][1] - (-k + 480 / 2)*(1-
cos(giro2));///y
Mat_Omega[numero][3] =
centros[cuenta2][2] + Z_prof - (-l + 640 / 2)*sin(giro) - (-k + 480 /
2)*sin(giro2)+ LUT_depth_matrixPAR[l][k];///z
if
(LUT_depth_matrixPAR[l][k]==0){
Mat_Omega[numero][3]
= 0;
}
153
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
Mat_Omega[numero][4] =
LUT_1RGB[640 - l][k][0];// LUT_R_matrixPAR[640 - l][k];///R
Mat_Omega[numero][5] =
LUT_1RGB[640 - l][k][1];//LUT_G_matrixPAR[640 - l][k];///G
Mat_Omega[numero][6] =
LUT_1RGB[640 - l][k][2];// LUT_B_matrixPAR[640 - l][k];///B No puedo
poner PAR, porque se escaneo antes de eso
}
vueltas++;
}
numero = numero - 480;///307200
OpenGL_3D(0);///poner como comentario para
saltar
}else{
///IMPAR, añado LUT_2
int vueltas = 0;
Mat_Omega[numero][0] =
numero;
Mat_Omega[numero][1] = -l +
640 / 2 + X_New - X_Base + centros[cuenta2][0] - (-l + 640 / 2)*(1 -
cos(giro));///x
Mat_Omega[numero][2] = -k +
480 / 2 + Y_New - Y_Base + centros[cuenta2][1] - (-k + 480 / 2)*(1 -
cos(giro2));///y
Mat_Omega[numero][3] =
centros[cuenta2][2] + Z_prof - (-l + 640 / 2)*sin(giro) - (-k + 480 /
2)*sin(giro2) +LUT_depth_matrixPAR[l][k];///z
if
(LUT_depth_matrixPAR[l][k] == 0){
Mat_Omega[numero][3]
= 0;
}
Mat_Omega[numero][4] =
LUT_2RGB[640 - l][k][0];// LUT_R_matrixPAR[640 - l][k];///R
Mat_Omega[numero][5] =
LUT_2RGB[640 - l][k][1];//LUT_G_matrixPAR[640 - l][k];///G
Mat_Omega[numero][6] =
LUT_2RGB[640 - l][k][2];// LUT_B_matrixPAR[640 - l][k];///B No puedo
poner PAR, porque se escaneo antes de eso
}
vueltas++;
}
numero = numero - 480;///307200
154
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
// destroyWindow("MyWindow");
}
T_timer++;
}
////////////////////////////////
//char sz15[255];
//sprintf_s(sz15, " pequeña: %d ", LUT_depth_matrix[320][240]); //
m_depthColorTable[300][240]);
//OutputDebugStringA(sz15);
}
155
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
156
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Código fuente
USUARIO
157
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
158
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Instalación de librerías
En este capítulo se explican los pasos a seguir para instalar las librerías
necesarias para que el programa funcione correctamente.
159
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Instalación de librerías
160
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Instalación de librerías
161
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Instalación de librerías
Figura 86 Propiedades
162
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Instalación de librerías
163
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Instalación de librerías
164
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
PROGRAMA
165
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
166
UNIVERSIDAD PONTIFICIA COMILLAS
ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)
INGENIERO INDUSTRIAL
Figura 93 Representación 3D
167