Código de Matlab - Detección de imágenes mediante el uso de Visión Artificial

Imágen de perfil
Val: 8
Ha disminuido su posición en 5 puestos en Matlab (en relación al último mes)
Gráfica de Matlab

Detección de imágenes mediante el uso de Visión Artificialgráfica de visualizaciones


Matlab

Actualizado el 22 de Octubre del 2015 por Jesus (Publicado el 12 de Noviembre del 2014)
21.683 visualizaciones desde el 12 de Noviembre del 2014
El siguiente código detecta imágenes tomadas con la cámara WEB y las compara con 2 imágenes que se le enseñan a una Red Neuronal Artificial y obtiene una salida que nos dice a que imagen se parece.

Interfaz

La estructura que implementamos fue la siguiente:

Prototipo

Se utiliza un algoritmo conocido como Regla de Hebb.

Desarrollado por:
Castañeda espinosa Jesus
Cesar Zetina Gaspar Antonio
Pedro Mendoza Erick Eduardo
Facultad de Ingeniería UNAM

Requerimientos

Componentes:
-Microcontroladro (Arduino)
-Madera de 2.5x2.5x30cm y de 2.5x2.5x15cm
-Triplay de ½” de 30x40cm
-Clavos 1”
-Cubos de 4.5x4.5x2 cm
-Figuras de Platanos, Manzanas y letras “M” “P” con un tamaño de 190x190 pixeles
-Motorreductor 2Kgcm a 70 rpm
-Webcam (Logitech)
-Circuito integrado L293D

Consideraciones
-La distancia entre la imagen y la lente de la cámara debe de ser constante.
-La cámara debe de estar fija y preferentemente perpendicular a la imagen para evitar deformaciones.
-La caja con la imagen debe quedar en la misma posición para que la cámara pueda capturar la imagen y hacer el procedimiento adecuadamente.

1.0
estrellaestrellaestrellaestrellaestrella(14)

Actualizado el 23 de Octubre del 2015 (Publicado el 12 de Noviembre del 2014)gráfica de visualizaciones de la versión: 1.0
21.684 visualizaciones desde el 12 de Noviembre del 2014
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

A esta versión le hace falta la poner una imagen de fondo y terminar correctamente la comunicación serial entre MATLAB y Arduino

Para utilizar la cámara WEB se requiere saber que cámara se va a utilizar y modificar la siguiente linea:
vid=videoinput('winvideo',1,'MJPG_640x360');

Cambiar el número de cámara y los formatos que soporta la cámara, para obtener esos datos ejecutar el siguiente comando (Windows)

-imaqhwinfo('winvideo')
-Doble clic en ans -> Workspace
-Doble clic sobre DeviceInfo <1x_ Struct>
-Seleccionar alguna de las cámaras que aparezcan y les mostrará información de que cámara esta haciendo referencia
-Doble clic sobre SupportedFormats <1x_ cell>
-Seleccionar alguno de los formatos que aparezcan, por lo regular las cámaras WEB integradas por default manejan el formato 'YUY2_160x1202'

Ya que sabemos el número de cámara y los formatos que soportan, se necesita cambiar la siguiente linea:

vid=videoinput('winvideo',2,'YUY2_160x1202');

El numero 1 o 2 depende del número de cámaras conectadas al PC.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
function varargout = Reconocimiento(varargin)
% RECONOCIMIENTO MATLAB code for Reconocimiento.fig
%      RECONOCIMIENTO, by itself, creates a new RECONOCIMIENTO or raises the existing
%      singleton*.
%
%      H = RECONOCIMIENTO returns the handle to a new RECONOCIMIENTO or the handle to
%      the existing singleton*.
%
%      RECONOCIMIENTO('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RECONOCIMIENTO.M with the given input arguments.
%
%      RECONOCIMIENTO('Property','Value',...) creates a new RECONOCIMIENTO or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Reconocimiento_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Reconocimiento_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Reconocimiento

% Last Modified by GUIDE v2.5 11-Nov-2014 20:47:25

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Reconocimiento_OpeningFcn, ...
                   'gui_OutputFcn',  @Reconocimiento_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Reconocimiento is made visible.
function Reconocimiento_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Reconocimiento (see VARARGIN)

%Colocar Imagen de fondo
;


% Choose default command line output for Reconocimiento
handles.output = hObject;
imshow('190x190.png','Parent',handles.axCamara)
imshow('190x190.png','Parent',handles.axPrueba)
imshow('190x190.png','Parent',handles.axP1)
imshow('190x190.png','Parent',handles.axP2)
imshow('190x190.png','Parent',handles.axResultado)
set(handles.textSERIAL,'String','')
warning('off')

 
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Reconocimiento wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Reconocimiento_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in buttonPreview.
function buttonPreview_Callback(hObject, eventdata, handles)
% hObject    handle to buttonPreview (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global vid
vid=videoinput('winvideo',1,'MJPG_640x360');
vid.FramesPerTrigger = 1;
vid.ReturnedColorspace = 'rgb';
triggerconfig(vid, 'manual');
vidRes = get(vid, 'VideoResolution');
imWidth = vidRes(1);
imHeight = vidRes(2);
nBands = get(vid, 'NumberOfBands');
hImage = image(zeros(imHeight, imWidth, nBands), 'parent', handles.axCamara);
preview(vid, hImage);


% --- Executes on button press in buttonCapture.
function buttonCapture_Callback(hObject, eventdata, handles)
% hObject    handle to buttonCapture (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global vid PTf x y

prueba=getsnapshot(vid);
pru=im2bw(prueba,0.6);
%imshow(pru,'Parent',handles.axPrueba)
A = imcrop(pru, [120 70 189 189]); %imcrop(f,[xmin ymin ancho alto ])
a=imresize(A, 0.25);
prt=im2bw(a);
pt=double(prt);

[x,y]=size(pt);
for i=1:1:x
    for j=1:1:y
        PT(i,j)=pt(i,j);
        if(PT(i,j)==0)
            PT(i,j)=-1;
        end 
    end
end

cont = 1;
[f,g]=size(PT);
for r=1:1:g
    for c=1:1:f
        PTf(cont,1)=PT(c,r);
        cont=cont+1;
    end
end

imshow(PT,'Parent',handles.axPrueba)


% --- Executes on button press in buttonFiguras.
function buttonFiguras_Callback(hObject, eventdata, handles)
% hObject    handle to buttonFiguras (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global P1 P2 P1f P2f x y

%ENSEÑAR MANZANA
MA=imread('manzana.png');
m=imresize(MA,0.25);
pr1=im2bw(m);
p1=double(pr1);

[x,y]=size(p1);
for i=1:1:x
    for j=1:1:y
        P1(i,j)=p1(i,j);
        if(P1(i,j)==0)
            P1(i,j)=-1;
        end 
    end
end

cont = 1;
[f,g]=size(P1);
for r=1:1:g
    for c=1:1:f
        P1f(cont,1)=P1(c,r);
        cont=cont+1;
    end
end

%ENSEÑAR PLATANO
PL=imread('platano.png');
p=imresize(PL,0.25);
pr2=im2bw(p);
p2=double(pr2);

[x,y]=size(p2);
for i=1:1:x
    for j=1:1:y
        P2(i,j)=p2(i,j);
        if(P2(i,j)==0)
            P2(i,j)=-1;
        end 
    end
end

cont = 1;
[f,g]=size(P2);
for r=1:1:g
    for c=1:1:f
        P2f(cont,1)=P2(c,r);
        cont=cont+1;
    end
end

%MOSTRAR IMAGENES EN LA GUI
imshow(MA,'Parent',handles.axP1)
imshow(PL,'Parent',handles.axP2)


% --- Executes on button press in buttonResultado.
function buttonResultado_Callback(hObject, eventdata, handles)
% hObject    handle to buttonResultado (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global P1f P2f PTf x y A2

T=[P1f P2f];
P=[P1f P2f]';
W=T*P;
A=hardlims(W*PTf);
 
cont = 1;
for c=1:1:y
    for r=1:1:x
        A2(r,c)=A(cont,1);
        cont=cont+1;
    end
end
 
imshow(A2,'Parent',handles.axResultado)
 
 
% --- Executes on button press in buttonLetras.
function buttonLetras_Callback(hObject, eventdata, handles)
% hObject    handle to buttonLetras (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
global P1 P2 P1f P2f x y
 
%ENSEÑAR M
MA=imread('M.png');
m=imresize(MA,0.25);
pr1=im2bw(m);
p1=double(pr1);
 
[x,y]=size(p1);
for i=1:1:x
    for j=1:1:y
        P1(i,j)=p1(i,j);
        if(P1(i,j)==0)
            P1(i,j)=-1;
        end
    end
end
 
cont = 1;
[f,g]=size(P1);
for r=1:1:g
    for c=1:1:f
        P1f(cont,1)=P1(c,r);
        cont=cont+1;
    end
end
 
%ENSEÑAR P
PL=imread('P.png');
p=imresize(PL,0.25);
pr2=im2bw(p);
p2=double(pr2);
 
[x,y]=size(p2);
for i=1:1:x
    for j=1:1:y
        P2(i,j)=p2(i,j);
        if(P2(i,j)==0)
            P2(i,j)=-1;
        end
    end
end
 
cont = 1;
[f,g]=size(P2);
for r=1:1:g
    for c=1:1:f
        P2f(cont,1)=P2(c,r);
        cont=cont+1;
    end
end
 
%MOSTRAR IMAGENES EN LA GUI
imshow(PL,'Parent',handles.axP1)
imshow(MA,'Parent',handles.axP2)
 
 
% --- Executes on button press in buttonEnviar.
function buttonEnviar_Callback(hObject, eventdata, handles)
% hObject    handle to buttonEnviar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.textSERIAL,'String','')
 
global A2 P1 P2
 
if(A2==P1)
    set(handles.textSERIAL,'String','M')
end
if(A2==P2)
    set(handles.textSERIAL,'String','P')
end
 
% delete(instrfind({'Port'},{'COM4'}));
% pserial = serial ('COM4');
% pserial.Baudrate = 9600;
% warning('off','MATLAB:serial:fscanf:unsuccessfulRead');
% fopen(pserial);
% 
% if(A2==P1)
%     set(handles.textSERIAL,'String','M')
%     fprintf(pserial,'1');    
% end
% 
% if(A2==P2)
%     set(handles.textSERIAL,'String','P')
%     fprintf(pserial,'1');
% end
% 
% fclose(pserial);
% delete(pserial);



Comentarios sobre la versión: 1.0 (14)

juan
12 de Noviembre del 2014
estrellaestrellaestrellaestrellaestrella
Excelente!!!! mis mas sinceras felicitaciones por el trabajo realizado
Responder
Imágen de perfil
22 de Octubre del 2015
estrellaestrellaestrellaestrellaestrella
Muchas gracias Juan

Saludos
Responder
Imágen de perfil
19 de Marzo del 2015
estrellaestrellaestrellaestrellaestrella
hola amigo buenas noches podrias ayudarme en algunas cosas referente a tu codigo por favor.. gracias de antemano..!
Responder
Imágen de perfil
22 de Octubre del 2015
estrellaestrellaestrellaestrellaestrella
Con mucho gusto podría ayudarte, dime en que te puedo ayudar.

Disculpa la tardanza en responder pero por cuestiones de la escuela se me había complicado.

Espero tu pregunta.

Saludos.
Responder
David
21 de Octubre del 2015
estrellaestrellaestrellaestrellaestrella
Excelente codigo! profesor, queria hacer una consulta si quiero procesar una foto nueva siempre y que esta foto el objeto que esta en ella contornearlo en otras palabra con el contorno de la figura hacer que un servomotor regule su movimiento al compas del contorno como puedo hacer? tiene algun correo o wpp me pueda facilitar saludos
Responder
Imágen de perfil
22 de Octubre del 2015
estrellaestrellaestrellaestrellaestrella
Buenas tardes Juan.

No comprendí muy bien tu pregunta, en la parte de hasta arriba abajo del titulo viene que este código fue publicado por Jesús, le das clic en esa parte y te manda a mi perfil en lawebdelprogramador, y ahí viene un poco mas de información para contactarme.

Saludos
Responder
Imágen de perfil
22 de Octubre del 2015
estrellaestrellaestrellaestrellaestrella
Buenas tardes Juan.

No comprendí muy bien tu pregunta, en la parte de hasta arriba abajo del titulo viene que este código fue publicado por Jesús, le das clic en esa parte y te manda a mi perfil en lawebdelprogramador, y ahí viene un poco mas de información para contactarme.

Espero poder ayudarte y poder seguir subiendo más códigos de alguno proyectos que he realizado.

Saludos
Responder
David
23 de Octubre del 2015
estrellaestrellaestrellaestrellaestrella
Me podrías dar tu whatsapp o tu correo para comunicarnos por fa me encanto tu trabajo
Saludos cordiales
Responder
Imágen de perfil
28 de Octubre del 2015
estrellaestrellaestrellaestrellaestrella
Hola David.

Una forma de comunicarte conmigo la puedes lograr viendo mi perfil, el cual lo puedes observar dando clic en mi nombre al principio del este código.

"Detección de imágenes mediante el uso de Visión Artificial
Matlab
Actualizado el 22 de Octubre del 2015 por Jesus (Creado el 12 de Noviembre del 2014)
1.517 visualizaciones desde el 12 de Noviembre del 2014. Una media de 35 por semana"

En esa parte onde dice por Jesus le puede dar clic y te mandara a una descripción de mi perfil y enconraras algunas redes sociales en las cuales puedes contactarme.
Responder
Imágen de perfil
28 de Octubre del 2015
estrellaestrellaestrellaestrellaestrella
Ademas puedes contactarme por mi correo electrónico ([email protected]).

Saludos.
Responder
decareaga
2 de Febrero del 2016
estrellaestrellaestrellaestrellaestrella
Hola Jesus al querer ejecutar tu codigo me sale el siguiente error
Trial>> ReconocimientoPorWebCam
Error: File: ReconocimientoPorWebCam.m Line: 58 Column: 1
Expression or statement is incorrect--possibly unbalanced (, {, or [.

podrías darme una mano?
saludos
Responder
Imágen de perfil
4 de Febrero del 2016
estrellaestrellaestrellaestrellaestrella
Buenas tardes decareaga.

Intenta quitarle el punto y coma que esta más arriba en la línea 56 debajo de donde dice quitar imagen de fondo.

Saludos.
Responder
edgar
2 de Noviembre del 2016
estrellaestrellaestrellaestrellaestrella
primeramente agraderte por los conocimientos lo compartes.
Buenos días Jesús no se si lo tendras el codigo en c# te lo agradeceria bastante
o me podrias recomendar alguna otra pagina.
bueno gracias
Responder
jose niño
18 de Septiembre del 2017
estrellaestrellaestrellaestrellaestrella
hola Jesus , tengo una inquietud con el codigo
me podrias ayudar a hacerlo correr en mi matlab . la verdad es que me es util darle uso a tu valioso codigo por favor amigo.
Responder

Comentar la versión: 1.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s2847