Home

trealu_a2014_lo _manipulador_codi_font

image

Contents

1. CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 37 UVIC h firpm 16 0 1 3 1 0 0 1 1 C lculo de un filtro equiripple paso alto h ftrans2 h Convierte en filtro 2D imf filter2 h img b Filtrar la se al o subplot 3 3 4 imshow img b imf figure imshow img b imf title Resalte bordes pause Espera a pulsar tecla 6 Binarizar imagen umb graythresh img _b imf img bw im2bw img_b imf umb umbral ssubplot 3 3 5 imshow img_ bw figure imshow img_ bw title Binarizada pause Espera a pulsar tecla Eliminar ruido img bn bwareaopen img 700 6 figure imshow img bn ssubplot 3 3 6 imshow img_ bn title Sin ruido pause SEspera a pulsar tecla Rellenar huecos vacios se strel square 5 img br imclose img bn se se strel disk 5 img brl imclose img br se subplot 3 3 7 imshow img br figure imshow img_brl1 title Rellenada pause SEspera a pulsar tecla Etiquetar elementos L N bwlabel img brl figure imshow label2rgb L subplot 3 3 8 imshow label2rgb L jet title Etiquetada figure imshow label2rgb L title Etiquetada pause SEspera a pulsar tecla Si no existe ning n elemento forma retorna al programa principal if N centro N 0 opc questdlg No hay piezas rojas Desea continuar CONTINUE SI NO SI if strcmp opc SI close figure 3 close figure 2
2. Como complemento al documento de MEMORIA se ha redactado el presente documento con el fin de explicar de forma m s detallada el funcionamiento del c digo fuente tanto del software de control CableBot V1 0 como el firmware implementado en el microcontrolador elegido para realizar el control del manipulador rob tico 1 2 Alcance El documento se centra en explicar el proceso seguido en cada una de las implementaciones inform ticas de una forma visual con el fin de comprender el funcionamiento del mismo Este documento tambi n muestra el c digo fuente de ambas implementaciones con el fin de tener recopilada toda la informaci n en un solo documento Para saber el funcionamiento del software de visi n artificial con m s detalle es necesario ver el documento Manual de usuario en el cual se puede apreciar todos los pasos a seguir para poner en marcha el software as como la forma de proceder para la identificaci n de las formas elegidas CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 2 UVIC 2 Codigos fuente Este apartado intenta describir de una forma visual los c digos fuente implementados en ambos dispositivos ya sea el PC para el software de visi n artificial como el microcontrolador encargado de la gesti n del software 2 1 C digo fuente software de visi n artificial Como ya se ha comentado anteriormente el software de control de visi n artificial se ha implementado bajo el programa MATLAB el cual c
3. close figure 1 return end end oe oe oo oe o o o AP ye oe oe oe oo oe a oo oe oo o oe LE oe oe Encontrar propiedades de los elementos prop regionprops L all Contar el n mero de objetos np length prop o Matriz vac a para ir concatenando los centros de las figuras CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 38 UVIC centro figure imshow img o title Deteccion de centros 5 Delimitar formas hold on for n 1 np rectangle Position prop n BoundingBox EdgeColor r LineWidth 2 x prop n Centroid 1 y prop n Centroid 2 centro centro prop n Centroid Guardar el centro del objeto plot x y end hold off pause SEspera a pulsar tecla E 6 Mensaje de aviso para continuar en la GUID opc questdlg Deteccion Finalizada CONTINUAR SI NO SI if strcmp opc SI close figure 4 close figure 3 close figure 2 close figure 1 else return end end 3 1 9 Shape m function prop shape imagen tratada imagen original umbral oo Esta funci n se encarga de detectar la forma de cada pieza para cargarla en la tabla de visualizacion Nos dice si se trata de un cuadrado circulo triangulo Separa cada forma de la imagen de entrada delimitando su perimetro para luego compararlas con
4. gui mainfcn gui State varargin else gui_mainfcn gui State varargin end k kkkkkk k W nd initialization code DO NOT EDIT KKK KKKKK KK KKK KK KKK Executes just before CableBOT is made visible function CableBOT OpeningFcn hObject eventdata handles varargin oe En esta funcion se colocan las instrucciones que queremos que se ejecuten antes de realizar ninguna accion es decir se ejecutan nada mas abrir la aplicacion GUIDE oe oe Inicio de variables global threshold global panoramica CAM global azimutal CAM azimutal CAM panoramica CAM I l 2 CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 7 UVIC cle warning off threshold 0 Ruido de encendido cargamos el archivo wav y Fs NBITS wavread Sonidos Entrada de Windows XP wav carga los datos del archivo wav a MATLAB sound y Fs SReproduce el sonido cargado oe Insertar Logo de la UVic Con estas instrucciones leo la imagen del logo y la represento en el axes correspondiente logo imread C Documents and Settings LOPEZ Escritorio GRADO PFG CableBOT GUI MatLabNLogosNlogoHome jpg logo imread Logos logoHome jpg image logo axis off oe oe Personalizar boton SALIR SInsertar imagen en el boton cerrar de forma que vemos el simbolo salir en sel boton a map imread Logos cerrar jpg r c d size a x
5. o original de la webcam sibilidad de la tabla o el texto CODIGO FUENTE GRADO EN ELECTRO NICA INDUSTRIAL Y AUTOMATICA 18 UVIC x Executes on slider movement function slider8 Callback hObject eventdata handles hObject handle to slider8 see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA Hints get hObject Value returns position of slider oe get hObject Min and get hObject Max to determine range of slider Cargar el valor del Slider en la zona de visualizacion handles slider8 get hObject Value Carga en handles sliderl el valor delSlider handles slider8 round handles slider8 set handles text5 String handles slider8 SEscribe el valor de Slider en statictext Modificar el brillo en la imagen original y mostrala zona de captura val 0 5 get hObject Value 0 5 global original imagen cam global new imagen cam bright brt original imagen cam new imagen cam bright brightness brt val axes handles Zona de Captura imshow new imagen cam bright Executes on button press in imagen negativo function imagen negativo Callback hObject eventdata handles hObject handle to imagen negativo see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA
6. Abrir y configurar puerto Serie COMI Secuencia de instrucciones para la configuracion del serial port Serial PORT serial COM1 fclose Serial PORT set Serial PORT Baudrate 9600 set Serial_PORT Terminator CR LF set Serial PORT DataBits 8 set Serial PORT Parity none set Serial PORT StopBits 1 set Serial PORT FlowControl none fopen Serial PORT 5 Bucle central while buttons 10 1 axes buttons povs read JOY 6 Flancos de subida Ejemplo oe SFlanco boton 1 actual l buttons 1 if actual 1l 1 amp anterior l disp Boton ll end anterior 1 actual 1 o o oe oe oe oe oe Combinacion de 2 botones hacia adelante Con esta combinacion movemos los motores de forma individual adelante Flanco boton 1 6 Motor 1 adelante actual 1 6 buttons 1 amp buttons 6 oe CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 32 UVIC if actual 1 6 1 amp amp anterior 1 6 fprintf Serial PORT sWn 1 disp Motor 1 adelante end anterior 1 6 actual 1 6 oe Envio 1 por el serial Flanco boton 2 6 Motor 2 adelante actual 2 6 buttons 2 amp buttons 6 if actual 2 6 1 amp amp anterior 2 6 fprintf Serial PORT s Mn 3 disp Motor 2 adelante end anterior 2 6 actual 2 6 oe Envio 3 por el serial Flanco boton 3 6 Motor 3 adelante actual 3 6 buttons 3
7. Brillo satihahdiss ideri elem 0 handles slider8 get handles slider8 oe oe oe pe o o Colocamos el Value Q O ESTA o scribe el ta see GUIDATA nueva imagen que hemos eta del proyecto enCam jpg jpg eBOT EO tdata handles O re version of MATLAB ta see GUIDATA valor a 0 Lo cargamos en Value valor de Slider en set handles text5 statictext String handles slider8 2 5 Control del slider10 Contraste set handles sliderl0 Value 1 Colocamos el handles sliderl0 get handles sliderl0 Value set handles text7 String handles sliderl0 statictext 9 s 2 O 2 5 Control del slider15 Umbral set handles slider15 Value 0 Colocamos el handles sliderl5 get handles slider15 Value set handles text10 String handles sliderl15 statictext 9 oe Imagen de la zona de SNAPSHOT SVualve a poner en la zona de captura la imagen global original imagen cam global imagen cam global new imagen cam imagen cam original imagen cam new imagen cam original imagen cam axes handles Zona de Captura imshow imagen cam set hand set hand Visible SNAPSHOT off Oculto vi Cambi les uitablel les textl String 6 valor a 1 SLo cargamos en Value Escribe el valor de Slider en valor a 1 SLo cargamos en Value Escribe el valor de Slider en
8. L all Delimitar formas for n 1 length prop rectangle Position prop n Bo x prop n Centroid 1 y prop n Centroid 2 centro X n x centro Y n y end hold off imagen tratada label2rgb L end lementos undingBox EdgeColor r LineWidth 2 3 1 4 Motor Control m ut function varargo oe See also GUIDE GUIDATA GUIHANDL oe Motor Control varargin El Edit the above text to modify th x oe Last Modified by GUIDE V22o 25 ADE 9 Begin initialization code DO NOT gui Singleton 1 gui State struct gui Name qui Singleton gui OpeningFocn qui OutputFen gui LayoutFen gui Callback if nargin amp amp ischar varargin 1 gui State gui Callback end if nargout varargout l nargout response to help Motor Control 2014 00 30 12 EDIT mfilename gui Singleton Motor Control OpeningFcn GMotor Control OutputFon str2func varargin 1 gui mainfcn gui State varargin CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 27 UVIC else gui mainfcn gui State varargin end End initialization code DO NOT EDIT oe Executes just before Motor Control is made visible function Motor Control OpeningFcn hObject eventdata handles varargin Centrar ventana del GUIDE Con estas instrucciones realizamos un centrado de la
9. VidSrc getselectedsource vid Configuracion de las propiedades del objeto VidSrc getselectedsource vid set vid FocusMode auto set vid FramesPerTrigger Inf set vid ReturnedColorspace rgb vid FrameGrabInterval 1 flushdata vid x 1 while x for n 1 3 Comienzo de la adquisicion oe oe CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 29 UVIC start vid SBucle de toma de imagenes while vid FramesAcquired lt 200 Tomamos una foto de la camara data getsnapshot vid Para el tracking sacamos la componente azul de cada imagen y la tratamos de forma que identificamos solamente las formas de color azul diff im imsubtract data 3 rgb2gray data Usamos filtro de media para reducir el ruido diff im medfilt2 diff im 3 3 SBinarizamos imagen diff im im2bw diff im 0 18 Fuera ruido menor a 500 pixels diff im bwareaopen diff im 500 Etiquetamos todos los componentes de la imagen bw bwlabel diff im 8 Tomamos la informacion de los objetos detectados stats regionprops bw BoundingBox Centroid Zona de visualizacion de la imagen capturada Creamos la zona en la cual se mostrar la imagen capturada axes handles video 1 zona de captura background data cargamos la imagen capturada axis off quitamos los ejes de la zona de captura axes imshow background mostramos la imagen en
10. amp buttons 6 if actual 3 6 1 amp amp anterior 3 6 fprintf Serial PORT s n 5 disp Motor 3 adelante end anterior 3 6 actual 3 6 oe Envio 5 por el serial SFlanco boton 4 6 Motor 4 adelante actual 4 6 buttons 4 amp buttons 6 if actual 4 6 1 amp amp anterior 4 6 fprintf Serial PORT s n 7 disp Motor 4 adelante end anterior 4 6 actual 4 6 oe Envio 7 por el serial oe Combinacion de 2 botones hacia atras Con esta combinacion movemos los motores de forma individual hacia atras oe SFlanco boton 1 8 Motor 1 atras actual 1 8 buttons 1 amp buttons 8 if actual 1 8 1 amp amp anterior 1 8 fprintf Serial PORT s n 2 disp Motor 1 atras end anterior 1 8 actual 1 8 oe Envio 2 por el serial SFlanco boton 2 8 Motor 2 atras actual 2 8 buttons 2 amp buttons 8 if actual 2 8 1 amp amp anterior 2 8 fprintf Serial PORT Ss1n 4 disp Motor 2 atras end anterior 2 8 actual 2 8 oe Envio 4 por el serial SFlanco boton 3 8 Motor 3 atras actual 3 8 buttons 3 amp buttons 8 if actual 3 8 1 amp amp anterior 3 8 fprintf Serial PORT s n 6 disp Motor 3 atras end anterior 3 8 actual 3 8 oe Envio 6 por el serial CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 33 UVIC SFlanco boton 4 8 Motor 4 atras actual 4 8 buttons 4 amp buttons 8 if ac
11. and user data see GUIDATA set handles uipanel7 Visible off Visibilidad OFF del panel de herramientas de imagen set handles tools on Enable on Habilitamos el boton ON para volver a activar el panel set handles tools off Enable off Deshabilitamos el boton de OFF porque ya no es visible el panel Executes on button press in aceptar valores function aceptar valores Callback hObject eventdata handles hObject handle to aceptar valores see GCBO eventdata reserved to be defined in a future version of MATLAB CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 17 UVIC oe handles structure with handles and user da oe Con esta funcion lo que hacemos es asignar la creado para usarla en la deteccion de formas sglobal imagen cam global new imagen cam global new imagen cam contrast oe new imagen cam new imagen cam contrast Guardamos la nueva imagen capturada en la carp imwrite new imagen cam lImagenes CAM new imag Mensaje de confirmacion de seleccion de imagen helpdlg La imagen ha sido seleccionada Cabl oo o Visibilidad del boton COLOR set handles deteccion color enable on S Executes on button press in valores defec function valores defecto _Callback hObject even hObject handle to valores defecto see GCB eventdata reserved to be defined in a futu handles structure with handles and user da Control del slider8
12. ceil r 50 y ceil c 50 g a 1 x end 1 y end g g 255 5 1 255 set handles Salir CData g 5 Ocultar boton de lamparas off al inicio En el inicio del programa oculto el boton de apagar lamparas para que aparezca por encima el boton de encender lamparas set handles Lamparas OFF visible off oe Ocultar panel de herramientas de imagen set handles uipanel7 Visible off Visibilidad OFF del panel de herramientas de imagen 5 Ocultar tabla de resultados set handles uitablel Visible off Visibilidad OFF de la tabla oo Ocultar botones de deteccion de COLOR PLACE y SHAP sset handles deteccion color enable off set handles deteccion lugar enable off set handles deteccion forma enable off E EJ oe ET Centrar ventana del GUIDE Con estas instrucciones realizamos un centrado de la pantalla de la GUIDE de forma que tenga una mejor vision de cara al usuario scrsz get 0 ScreenSize pos act get gcf Position xr scrsz 3 pos act 3 xp round xr 2 yr scrsz 4 pos act 4 yp round yr 2 set gcf Position xp yp pos_act 3 pos_act 4 oo CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 8 UVIC Deshabilitar botones de TOOLS Hasta que no carguemos una imagen en la zona de SbapShot no podemos actuar sobre la paleta de herramientas oe set handles tools on Enable off Habilita
13. control del motor Motor Control 3 1 3 Calibration m unction imagen tratada centro X centro Y calibration imagen oe oe oe Esta funcion se encarga de la calibracion de la camara convirtiendo la distancia de pixeles en mm Se le ha dotado de un boton para realizar el centrado de la zona de trabajo respecto a la posicion de sla camara PAR METROS DE ENTRADA Simagen Ultima imagen arreglada para la deteccion PAR METROS DE SALIDA scentro X centro de masa de cada forma del patron Scentro Y centro de masa de cada forma del patron Simagen tratada Imagen arreglada para la deteccion del escalado o img imagen Cargo la imagen traida desde la GUIDE Pasar a escala de grises img_g rgb2gray img oo Realzar los bordes img _b double img g 255 Convierte a double h firpm 16 0 1 3 1 0 0 1 1 C lculo de un filtro equiripple paso alto h ftrans2 h Convierte en filtro 2D imf filter2 h img b Filtrar la sefial CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 26 UVIC 6 Binarizar imagen umb graythresh img _b imf 0 2 img bw im2bw img b imf umb oe oe Eliminar ruido img bn bwareaopen img bw 500 oe oe Rellenar huecos vacios se strel disk 15 img br imclose img bn se Etiquetar elementos Ne bwlabel img br Encontrar propiedades de los prop regionprops
14. global new imagen cam contrast black new imagen cam contrast black 255 black axes handles Zona de Captura imshow black oe Funcion para ajuste del brillo Con esta funcion modificamos el brillo de la imagen original y creamos una nueva imagen para proceder a la deteccion de las figuras Lo que se quiere conseguir es una imagen mejoradas para no tener problemas a la hora de la deteccion oe oe oo oe function brt brightness im val a b c size im for i 1 a for j 1 b for k 1 3 im i j k im i j k val if im 1 j k 2255 im i j k 255 elseif im i j k lt 0 im i j k 0 CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 19 UVIC end end end end brt im Executes on slider movement function sliderl0 Callback hObject eventdata handles hObject handle to sliderl0 see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA Hints get hObject Value returns position of slider get hObject Min and get hObject Max to determine range of slider Cargar el valor del Slider contraste en la zona de visualizacion handles sliderl0 get hObject Value Carga en handles sliderl10 el valor del Slider set handles text7 String sprintf 1 2f handles slider10 valor de Slider en statictext oo Escribe el global new imagen cam bright g
15. handles hObject handle to Lamparas ON see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA Abrir y configurar puerto Serie COMI Secuencia de instrucciones para la configuracion del serial port Serial PORT serial COM1 fclose Serial PORT set Serial PORT Baudrate 9600 set Serial_PORT Terminator CR LF set Serial PORT DataBits 8 set Serial PORT Parity none set Serial PORT StopBits 1 set Serial PORT FlowControl none fopen Serial PORT oe Envio de datos a traves del puerto seri Segun el checkbox activado se manda un caracter u otro para activar un circuito o dos circuitos de iluminacion circuit l get handles circuito _1 Value circuit 2 get handles circuito 2 Value oo oe if circuit 1 amp amp circuit 2 Si los dos checkbox estan habilitados fprintf Serial PORT ss n A Envio A por el serial set handles circuito 1 Enable off set handles circuito 2 Enable off Deshabilito los checkbox Cerramos y borramos el puerto serie para poder usarlo de nuevo fclose Serial PORT delete Serial PORT clear Serial PORT elseif circuit 1 amp amp circuit 2 sel esta un circuito circuito 1 activado fprintf Serial PORT SsIn B SEnvio B por el serial set handles circuito 1 Enable off Deshabil
16. la zona capturada hold on Marcamos los objetos azules con un cuadro for object 1 length stats bb stats object BoundingBox bc stats object Centroid rectangle Position bb EdgeColor r LineWidth 2 plot bc 1 bc 2 m a text bc 1 15 bc 2 strcat X num2str round bc 1 qu num2str round bc 2 set a FontName Arial FontWeight bold FontSize 12 Color magenta end hold off end Stop de la adquisicion de video stop vid SLimpiamos el buffer de la memoria de las instantaneas tomadas para volver a iniciar el ciclo flushdata vid Sprintf s i El numero de ciclo es n Mensaje de continuar o no if n 2 opc questdlg Desea continuar CONTINUAR SI NO SI if stremp opc SI CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 30 UVIC x 1 Sprintf s i valor de x end if strcmp opc NO x 0 sprintf ss i valor de x end end end end o SLimpiamos el buffer de la memoria de las instantaneas tomadas para salir flushdata vid disp Final del proceso Cerrar videos closepreview vid 1 cerramos la ventana de preview delete vid 1 borramos el canal de Video helpdlg Fin de video CableBOT o Executes on button press in cerrar video function cerrar video Callback hObject eventdata handles Carta de ajuste en axes Como el proceso ha f
17. puerto Serie COM1 Serial PORT serial COM1 fclose Serial PORT set Serial PORT Baudrate 9600 set Serial PORT Terminator CR LF set Serial PORT DataBits 8 set Serial PORT Parity none set Serial PORT StopBits 1 set Serial PORT FlowControl none fopen Serial PORT Envio de datos a traves del puerto serie en este caso el caracter B fprintf Serial PORT SsIn D cerramos y borramos el puerto serie para poder usarlo de nuevo fclose Serial PORT delete Serial PORT clear Serial PORT Instrucciones para mostrar u ocultar los botones de ON OFF de iluminacion set handles Lamparas OFF visible off set handles Lamparas ON visible on 5 Borrado de los checkbox set handles circuito 1 Value 0 set handles circuito 2 Value 0 Habilitado de los checkbox Usando la propiedad Enable habilito los checkbox para poder seleccionar una opcion de nuevo set handles circuito 1 Enable on set handles circuito 2 Enable on Executes on button press in Salir function Salir Callback hObject eventdata handles hObject handle to Salir see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA Mensaje que se muestra al presionar el boton inferior de SALIR opc questdlg Desea salir del programa
18. sdisp El numero de formas AMARILLAS es num2str numero amarillas disp Eje X Eje Y disp centroide amarillas Deteccion de lugar de piezas rojas 0 ro centroide rojas numero rojas place imagen formas rojas original imagen cam ro sdisp El numero de formas ROJAS es num2str numero rojas disp Eje X Eje Y disp centroide rojas Configuramos el numero de filas columnas de la tabla filas numero rojJas numero amarillas CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 13 UVIC columnas 6 num element cell filas columnas Cargamos el numero d lementos que tenemos for n 1 filas num element n 1 n end Cargamos coordenada X coordenada Y de AMARILLAS for n 1 numero amarillas num element n 2 round centroide amarillas n 1 relacion num element n 3 round centroide amarillas n 2 relacion num element n 5 Amarilla end Cargamos coordenada X coordenada Y de ROJAS x 1 for n numero amarillas 1 filas num element n 2 round centroide rojas x 1 relacion num element n 3 round centroide rojas x 2 relacion num element n 5 Roja x x 1 end Visibilidad boton SHAPE set handles deteccion forma enable on Executes on button press in deteccion forma function deteccion forma Callback hObject eventdata handles hObject handle to deteccion forma
19. see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA global original imagen cam global new imagen cam global threshold global num element global imagen formas amarillas global imagen formas rojas global n amarillas global n rojas shape new imagen cam original imagen cam threshold Deteccion de formas amarillas imagen formas amarillas not imagen formas amarillas imagen formas amarillasl bwareaopen imagen formas amarillas 100 L N bwlabel imagen formas amarillasl Sfigure imshow imagen formas amarillasl prop regionprops L all n amarillas length prop figure imshow original imagen cam hold on for k 1 n amarillas CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 14 UVIC if prop k Area gt 3900 amp amp prop k Area lt 5000 num element k 4 Circulo end end Deteccion de formas rojas imagen formas rojasl bwareaopen imagen formas rojas 100 L N bwlabel imagen formas rojasl sfigure imshow imagen formas rojasl prop regionprops L all n rojas length prop x 1 for k n _amarillas 1 n amarillas n rojas if prop x Area gt 4000 amp amp prop x Area lt 5000 num element k 4 Circulo text prop x Centroid 1 40 prop x Centroid 2 11 Color c FontWeight bold disp prop x Area elseif prop x Area gt 5000 amp amp prop
20. try y catch para evaluar si hay o no webcam conectada y de este modo mostrar un mensaje d rror en pantalla global original imagen cam global azimutal CAM 5 Ocultar tabla de resultados set handles uitablel Visible off Visibilidad OFF de la tabla try canalVideo videoinput winvideo azimutal CAM RGB24 800x600 esto crea el canal de video a la camara web preview canalVideo abrimos una ventana de preview para ver a donde apuntamos con la camara Catch CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 9 VI errordlg NO HAY CAMARA CONECTADA Mensaje de error end start canalVideo inicializamos el canal de Video pause 5 espera 5 segundos para que estabilice la imagen de la webcam imgAdq getsnapshot canalVideo tomamos una instantanea con la camara que se guarda en imgAdq Guardamos la imagen capturada en el PC imwrite imgAdq Imagenes CAM imagenCam jpg jpg Guardamos la imagen en la variable global para usarla donde nosotros queramos dentro de la GUIDE original imagen cam imread Imagenes CAM imagenCam jpg Ruido de camara cargamos el archivo wav y Fs NBITS wavread NVSonidosNCAMERA wav carga los datos del archivo wav a MATLAB sound y Fs SReproduce el sonido cargado 5 Cerrar video closepreview canalVideo cerramos la ventana de preview delete canalVideo borramos el canal de Video set handles text1 Str
21. x Area lt 6500 num element k 4 Cuadrado text prop x Centroid 1 40 prop x Centroid 2 11 Color c FontWeight bold disp prop x Area elseif prop x Area gt 2000 amp amp prop x Area lt 3000 num_element k 4 Triangulo text prop x Centroid 1 40 prop x Centroid 2 11 GColor c FontWeight baeld disp prop x Area end xX x 1 end Cargamos en tabla t handles uitablel Data num element Visualizar tabla de resultados t handles uitablel Visible on Visibilidad ON de la t handles uitablel RowName set handles uitablel ColumnWidth set handles uitablel ColumnFormat short bank RI RI Ri text prop k Centroid 1 50 prop k Centroid 2 YELLOW CIR FontSize l1 Color c PontWerghr bold disp prop k Area elseif prop k Area gt 5000 amp amp prop k Area lt 6500 num element k 4 Cuadrado text prop k Centroid 1 50 prop k Centroid 2 YELLOW SO Fontsize l11 Color c FontWeight bald disp prop k Area elseif prop k Area gt 2000 amp amp prop k Area lt 3000 num element k 4 Triangulo text prop k Centroid 1 50 prop k Centroid 2 YELLOW TRI FontSize lI1 Qolor c FontwWeright bold disp prop k Area ED CIR FontSize ED SQ FontSize ED TRI FontSize tabla 60 115 115 85 865 774
22. y borramos el puerto serie para poder usarlo de nuevo close Serial PORT delete Serial PORT clear Serial PORT Hh Executes on button press in transferir datos function transferir datos Callback hObject eventdata handles hObject handle to transferir datos see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA oe oo oo Abrir y configurar puerto Serie COMI Secuencia de instrucciones para la configuracion del serial port Serial PORT serial COM1 set Serial PORT Terminator CR fopen Serial PORT oe oo Envio de datos a traves del puerto seri fprintf Serial PORT sMn T SEnvio T por el serial oe oe Recepcion por el puerto seri Se mantiene leyendo el puerto durante un determinado tiempo A fgets Serial PORT B int32 str2num A if B set handles comienzo transferencia enable on helpdlg Continuar con START CableBOT else errordlg NO HAY COMUNICAION SERIE Mensaje de error disp A end Cerramos y borramos el puerto serie para poder usarlo de nuevo fclose Serial PORT delete Serial PORT clear Serial PORT o Executes on slider movement function slider15 Callback hObject eventdata handles hObject handle to slider15 see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure wi
23. 3 7 set handles textl String TABLE Cambio el texto de la imagen de IMAGEN CAPTURADA a TABLA CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 15 UVIC o Executes on button press in deteccion color function deteccion color Callback hObject eventdata handles hObject handle to deteccion color see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA oe oe global new imagen cam sRescatamos la imagen a utilizar oe Creamos matriz del color a buscar Es una prueba practica ya anteriormente se han buscado estos valores para que sean lo mas parecido posibles a los que buscamos oe RGB red 0 0 0 SREVISAR VALORES RGB yellow 255 0 0 SREVISAR VALORES oe oo OBTENER IMAGENES DEL MISMO COLOR El valor de los pixeles de cada figura pueden variar levemente de uno a otro asi que creamos un valor de umbral o histeresis De esta forma tenemos el valor del pixel este umbral para discriminar entre los dos colores Es una prueba practica de forma que puede variar dependiento de la imagen usada color umbral red 70 Valor emp rico 70 color umbral yellow 70 Valor emp rico 70 oe oe oe oe oe oe oe Llamadas a funcion color En esta parte de codigo se realizan las llamadas correspondientes para realizar la discrimi
24. Eliminar ruido img bn bwareaopen img bw 500 figure imshow img bn subplot 3 3 6 imshow img bn title in ruido pause Espera a pulsar tecla 5 Rellenar huecos vacios se strel square 5 img br imclose img bn se ssubplot 3 3 7 imshow img br figure imshow img br title Rellenada pause SEspera a pulsar tecla oo Etiquetar elementos NJ bwlabel img br oe E Si no existe ning n elemento forma retorna al programa principal N errordlg NO EXISTE NINGUNA FIGURA Mensaje de error close figure 3 close figure 2 close figure 1 oe oo H Hh oe oe oe 11 C lculo de un filtro equiripple paso CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 40 UVIC return oe oo Encontrar propiedades de los elementos prop regionprops L all Contar el n mero de objetos np length prop Marcar perimetro S figure imshow img br figure imshow img o title Perimetrada hold on B bwboundaries img br for k l np boundary B k plot boundary 2 boundary 1 c LineWidth 2 sdisp prop k Area end hold off pause Espera a pulsar tecla El Mensaje de aviso para continuar en la GUID opc questdlg Deteccion Finalizada CONTINUAR SI NO SI if stremp opc SI close figure 7 close figure close figure close figure close figure close figure
25. SALIR SI NO NO if strcmp opc NO CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 12 UVIC return end Ruido de apagado cargamos el depone wav y Fs NBITS wavread Sonidos Apagado de Windows XP wav carga los datos del archivo wav a MATLAB sound y Fs SReproduce el sonido cargado delete handles figurel o Executes when user attempts to close figurel function figurel CloseRequestFcn hObject eventdata handles hObject handle to figurel see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA oe oe oe Hint delete hObject closes the figure delete hObject gt Executes on button press in deteccion lugar function deteccion lugar Callback hObject eventdata handles hObject handle to deteccion lugar see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA obal original imagen cam lobal imagen formas amarillas lobal imagen formas rojas obal numero rojas numero amarillas obal centroide rojas obal centroide amarillas lobal num element obal relacion oe ee E O o w jes global threshold Deteccion de lugar de piezas amarillas am 1 centroide amarillas numero amarillas place imagen formas amarillas original imagen cam am
26. Universitat de Vic UV Escola Polit cnica Superior CODIGO FUENTE Manipulador rob tico con visi n artificial CableBot Alberto L pez Germ n Grado en Ingenier a Electr nica Industrial y Autom tica Tutor Pere Mart Puig Vic Septiembre de 2014 UVIC INDICE 1 Introduccion 1 1 Objeto N 1 2 Alcance N 2 C digos fuente 2 1 C digo fuente software de visi n artificial 2 1 1 2 2 C digo fuente firmware 2 2 1 3 Anexos 3 1 C digo software MATLAB 3 1 1 3 1 2 3 1 3 3 1 4 3 1 5 3 1 6 3 1 7 3 1 8 3 1 9 3 2 C digo firmware de control Diagrama de bloques Diagrama de bloques aon FW Q Presentaci n m CableBOT m Calibration m Motor_Control m Gamepad_Control m Scale m Color m Place m Shape m CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 1 UVIC 1 Introduccion Una de las partes mas importantes en un controlador rob tico junto con el propio sistema es la parte destinada al control ya sea implementado en un PC o en un sistema embebido En el caso que a este proyecto ata e se han realizado dos implementaciones de car cter inform tico Por un lado se ha desarrollado una aplicaci n software de visi n artificial sobre el programa MATLAB y otra implementaci n sobre un microcontrolador en ANSI C para realizar el control del hardware del manipulador rob tico 1 1 Objeto
27. alized CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 6 UVIC Position 82 15 15 07 String COMENZAR PFontsise l4 BackgroundColor 0 1 0 1 Osllback eles all close allele CablebBors 3 1 2 CableBOT m function varargout CableBOT varargin ZRAKKKKKKK KK Ck Ck Sk SKK kk Ck KK KKK SKK KKK KK KKK KKK KKK KKK KKK KK KK KK KK KK KK KK KK KK KKK KKK SAutor Alberto Lopez German Centro Universidad Politecnica de Vic Fecha 08 07 2014 Descripcion Programa principal de configuracion de una GUIDE en MatLab Se trata de la pantalla principal de la aplicacion en la cual tenemos todos los controles encargados de la deteccion de piezas de nuestro proyecto Wkckk kc ko ck ko kck kc ck kock k kck Kk k ck k k k k kk kk kk kk kk ck ko kk k Kok kc ck ko k ko k kock ck k ko k k k kk RARE k ko k ko k k ok Ak Ak RR oe oe oe oe oe Last Modified by GUIDE v2 5 25 Apr 2014 22 17 53 oe RAL EERE AAR RUE C ESSET a T initialization code DO NOT EDIT x x x x x x gui Singleton 1 gui State struct gui Name mfilename gui Singleton gui Singleton gui OpeningFcn CableBOT OpeningFcn gui OutputFcn G8CableBOT OutputFcn gui_LayoutFen gui Callback Je if nargin amp amp ischar varargin 1 gui State gui Callback str2func varargin 1 end if nargout varargout l nargout
28. close figure d se se RN W BOOD se else return end CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 41 UVIC 3 2 Codigo firmware de control Este capitulo queda pendiente al no conseguir llegar a tiempo a realizar una programaci n digna de ser comentada Al tratarse de un proyecto con car cter personal es decir que debido al tema tratado es de alto inter s para m esta parte se va realizar con posterioridad a la defensa del trabajo dando al robot las funcionalidades esperadas Ya se han realizado pruebas de programaci n en la placa de desarrollo elegida para ello por lo tanto solo es cuesti n de tiempo conseguir un firmware de control CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 42
29. data handles hObject handle to pushbutton3 see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA centered 3 1 7 Color m function imagen discriminada color imagen RGB valor umbral oe oe Esta funci n se encarga de evaluar el color de cada pieza para discriminar de qu color se trata Con esto conseguimos diferenciar el n mero de piezas de cada color que existen en la base de trabajo oe oe PAR METROS DE ENTRADA imagen Ultima imagen arreglada con el panel de herramientas de imagen oe oe PAR METROS DE SALIDA Simagen discriminada imagen en la cual solo estan presentes las formas del color buscado oe I imagen Separar la matriz RGB en R rojo B azul y G verde R RGB 1 G RGB 2 B RGB 3 CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 36 UVIC oe C lculo de la referenica Realizar una comparaci n de cada pixel de la imagen de entrada con los valores de la matriz RGB esta diferencia debe estar dentro del umbral para encontrar el color oe imagen discriminada abs I 1 R valor umbral amp abs I 2 G lt valor umbral amp abs I 3 B valor umbral En otras palabras si el color que se busca por ejemplo es de tendencia azul 0 0 255 1a matriz imagen discriminada ser uno 1 pixel blanco solo en aque
30. dth 2 cateto adyacente line x 1 x 2 y 1 y 2 color r LineWidth 2 Shipotenusa global scale global hipot cat_op y 2 y 1 cat_ad x 2 x 1 hipot sqrt cat_op cat_op cat_ad cat_ad Llamada a la GUIDE de calibracion Scale uiwait relacion hipot scale cat op num2str cat op cat ad num2str cat ad hipot num2str hipot relacion text num2str relacion CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 25 UVIC Svisualiza linea cat op visualiza linea cat ad Svisualiza linea hipot text 20 70 A cat op Color k text 20 120 B cat_ad Color g text 20 170 C hipot Color r rectangle Position 10 50 150 150 EdgeColor k LineWidth 2 line 20 500 30 30 color k LineWidth 1 hipotenusa text 20 20 La relacion pixel mm es relacion text pixeles es 1mm 1 visualiza el punto C x Executes on button press in control gamepad function control gamepad_Callback hObject eventdata handles hObject handle to control gamepad see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA gamepad control warndlg Has salido del control GAMEPAD CableBOT Executes on button press in motor control function motor control Callback hObject eventdata handles 5 Llamada a la GUIDE de
31. e 1 El else return end Visibilidad boton PLACE set handles deteccion lugar enable on Executes on button press in tools on function tools on Callback hObject eventdata handles hObject handle to tools on see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA set handles uipanel7 Visible on Visibilidad ON del panel de herramientas de imagen set handles tools on Enable off SDeshabilitamos el boton ON ya que no tiene ninguna funcion set handles tools off Enable on Habilitamos el boton de OFF oe Control del Slider10 Contraste et handles sliderl0 Value 1 Colocamos el valor a 1 andles sliderl0 get handles sliderl0 Value Lo cargamos en Value set handles text7 String handles sliderl10 SEscribe el valor de Slider en statictext 2 uU Control del Slider10 Contraste set handles sliderl15 Value 0 Colocamos el valor a 1 handles sliderl5 get handles slider15 Value SLo cargamos en Value set handles text10 String handles sliderl1l5 SEscribe el valor de Slider en statictext Executes on button press in tools off function tools off Callback hObject eventdata handles hObject handle to tools off see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles
32. eo helpdlg Fin de video CableBOT uiwait end 5 Parte de la calibracion LEM canalVideo videoinput winvideo azimutal CAM RGB24 800x600 esto crea el canal de video a la camara web preview canalVideo abrimos una ventana de preview para ver a donde apuntamos con la camara catch errordlg NO HAY CAMARA CONECTADA Mensaje de error end Q start canalVideo inicializamos el canal de Video pause 5 espera 5 segundos para que estabilice la imagen de la webcam img_calibracion getsnapshot canalVideo tomamos una instantanea con la camara que se guarda en img calibracion Guardamos la imagen capturada en el PC imwrite img _calibracion Imagenes CAM Calibration img jpg jpg o closepreview canalVideo cerramos la ventana de preview o delete canalVideo borramos el canal de Video imagen calibrada x y calibration img calibracion 9 set handles textl String CALIBRATION Cambio el texto de la imagen de ZONA DE CAPTURA axes handles Zona de Captura zona de captura background imagen calibrada cargamos la imagen capturada axis off quitamos los ejes de la zona de captura axes 9 imshow background mostramos la imagen en la zona capturada hold on line xini xend yini yend ayuda para comando line line x 1 x 1 y 1 y 2 color k LineWidth 2 cateto opuesto line x 1 x 2 y 2 y 2 color g LineWi
33. inalizado colocamos una carta de ajuste en pantalla oo Zona de visualizacion de la imagen capturada SCreamos la zona en la cual se mostrar la imagen capturada axes handles video 1 zona de captura background imread Logos cartadeajuste jpg cargamos la imagen axis off quitamos los ejes de la zona de captura axes imshow background mostramos la imagen en la zona capturada axes handles video 2 zona de captura axis off quitamos los ejes de la zona de captura axes imshow background mostramos la imagen en la zona capturada o Executes on button press in Salir function Salir Callback hObject eventdata handles Mensaje que se muestra al presionar el boton inferior de SALIR opc questdlg Desea salir del programa SALIR SI T NO NO if strcmp opc NO return end delete handles figurel CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 31 UVIC 3 1 5 Gamepad_Control m function gamepad control ole Control mediante GamePad oe oo Esta funcion toma el control del robot mediant l GamePad asociado al PC Para salir basta con pulsar el boton 10 oe oe alos tr JOY VRJOYSTICK 1 catch errordlg NO HAY JOYSTICK CONECTADO Mensaje de error uiwait end stop button 10 buttons stop button 0 disp CONTROL GAMEPAD warndlg Has tomado el control GAMEPAD CableBOT uiwait
34. ing SNAPSHOT Cambio el texto de la imagen de ZONA DE tl E CAPTURA a IMAGEN CAPTURADA Zona de visualizacion de la imagen capturada SCreamos la zona en la cual se mostrar la imagen capturada oe 2 O axes handles Zona_de_Captura zona de captura background imread Imagenes CAM imagenCam jpg cargamos la imagen capturada axis off quitamos los ejes de la zona de captura axes 9 imshow background mostramos la imagen en la zona capturada Habilitamos la paleta de herramientas de imagen Tools Imagen set handles tools on Enable on Habilitamos el boton ON para volver a activar el panel Guarmos la variable canalVideo para usarla en otra funcion handles canalVideo canalVideo guidata hObject handles Executes on button press in Abrir Video function Abrir Video Callback hObject eventdata handles global azimutal CAM Abrir Video para visualizacion del proceso canalVideo videoinput winvideo azimutal CAM RGB24 800x600 esto crea el canal de video a la camara web preview canalVideo abrimos una ventana de preview para ver a donde apuntamos con la camara start canalVideo inicializamos el canal de Video handles canalVideo canalVideo guidata hObject handles CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 10 UVIC Executes on button press in Lamparas ON function Lamparas ON Callback hObject eventdata
35. is off quitamos los ejes de la zona de captura axes 9 imshow background mostramos la imagen en la zona capturada hold on Marcamos los objetos azules con un cuadro for object 1 length stats bb stats object BoundingBox bc stats object Centroid rectangle Position bb EdgeColor r LineWidth 2 plot bc 1 bc 2 m a text bc 1 35 bc 2 20 strcat X num2str round bc 1 Y num2str round bc 2 set a FontName Arial FontWeight bold FontSize 12 Color e Lineas de centrado en la imagen line 0 8001 300 300 color c LineWidth 2 Linea longitudinal line 400 400 0 600 color c LineWidth 2 Linea transversal end hold off end oe Stop de la adquisicion de video cop vid Limpiamos el buffer de la memoria de las instantaneas tomadas para volver a iniciar el ciclo lushdata vid oe UY oe Hh Mensaje de continuar o no if n 2 opc questdlg Desea continuar CONTINUAR SI NO SI if stremp opc SI x 1 end if strcmp opc NO x 0 end end end end ae Limpiamos el buffer de la memoria de las instantaneas tomadas para salir flushdata vid disp Final del proceso CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 24 UVIC 5 Cerrar videos closepreview vid cerramos la ventana de preview delete vid borramos el canal de Vid
36. ito los checkbox set handles circuito 2 Enable off Cerramos y borramos el puerto serie para poder usarlo de nuevo fclose Serial PORT delete Serial PORT clear Serial PORT elseif circuit_1 amp amp circuit_2 01 esta un circuito circuito 2 activado fprintf Serial PORT SsIn C SEnvio C por el serial set handles circuito 1 Enable off Deshabilito los checkbox set handles circuito 2 Enable off Cerramos y borramos el puerto serie para poder usarlo de nuevo fclose Serial PORT delete Serial PORT clear Serial PORT else Si no hay ningun checkbox habilitado envio msg de error errordlg Selecciona un circuito de encendido ERROR o Cerramos y borramos el puerto serie para poder usarlo de nuevo CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 11 UVIC fclose Serial PORT delete Serial PORT clear Serial PORT return end se se Instrucciones para mostrar u ocultar los botones de ON OFF de iluminacion set handles Lamparas ON visible off set handles Lamparas OFF visible on Executes on button press 1n Lamparas OFF function Lamparas OFF Callback hObject eventdata handles hObject handle to Lamparas OFF see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA oo Abrir y configurar
37. k Ck Ck Sk Ck kk Sk ck kk Sk kk Sk Sk kk Ck kk kk kk Sk kx ko ke kx ko k kx ko kv ko ko kx ko ko oe oo oe oe Inicializacion del programa clear clc cla close all SBorramos todo lo que pueda haber abierto warning off all Suprimir avisos oo Creamos figura figdiag figure Units Pixels Position 1 1 1024 768 STama o de la presentaci n Number t off Name CableBOT Menubar none color 0 0 0 oo Ubicamos ejes en figura axes Units Normalized Position O 0 1 11 Incluir imagen de fondo SImportamos imagen jpg junto con su mapa de colores x map imread fondo presentacion jpg jpg SRepresentamos imagen en figura con su mapa de colores image x colormap map axis off hold on ae T tulos sobre imagen tulo text 220 50 CableBOT Fontname Arial Fontsize 60 Fontweight Bold color b SNombre del autor text 30 590 Autor Alberto Lopez German Fontname Arial Fontweight Bold Fontsize 14 color r Nombre del curso text 30 620 Curso Electronica industrial y Automatica Fontname Arial Pontweight Bold Pontsize l14 golor r SNombre del centro text 30 650 Centro UNIVERSIDAD DE VIC Fontname Arial Fontweight Bold Pontsize 14 color r oe oe oe oe oo Bot n Comenzar Continue uicontrol Style pushbutton Units norm
38. llos sectores de la imagen donde la diferencia est dentro del umbral o sea donde est el color m s cercano al azul oe end 3 1 8 Place m function centro N place imagen tratada imagen original color Esta funci n separa cada forma de la imagen de entrada Asimismo obtiene el centro de masa de cada objeto Devuelve tambi n en n mero d lementos que hay en la imagen ox oe oe PAR METROS DE ENTRADA Simagen Ultima imagen arreglada para la deteccion de las formas scolor Tag que nos indica que imagen vamos a tratar amarillas o rojas oe PAR METROS DE SALIDA centro centro de masa de cada forma objeto N numero de formas dentro de la imagen oe oe Inicio img o imagen original imagen imagen tratada if color img not imagen imagen amarillas bwareaopen img 100 figure imshow imagen amarillas InitialMagnification 200 title Piezas color AMARILLO helpdlg Seguir proceso pulsando tecla CableBOT else img imagen figure imshow img InitialMagnification 200 title Piezas color ROJO helpdlg Seguir proceso pulsando tecla CableBOT end pause SEspera a pulsar tecla Pasar a escala de grises img g rgb2gray img subplot 3 3 3 imshow img g figure imshow img g title Grises pause Espera a pulsar tecla Realzar los bordes img b double img g 255 Convierte a double
39. lobal new imagen cam contrast val contrast get hObject Value J imadjust new imagen cam bright 0 val contrast 0 1 axes handles Zona de Captura imshow J new imagen cam contrast J Executes on button press in imagen gris function imagen gris Callback hObject eventdata handles hObject handle to imagen gris see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA Convertir imagen en escala de grises global new imagen cam contrast global img g img new imagen cam contrast img g rgb2gray img axes handles Zona de Captura imshow img g set handles imagen blanco negro Enable on SHabilito el boton B amp W para poder binarizar Executes on button press in imagen blanco negro function imagen blanco negro Callback hObject eventdata handles hObject handle to imagen blanco negro see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA 22 Convertir imagen en blanco y negro Binarizada global img g CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 20 UVIC global threshold Realzar los bordes img b double img g 255 Convierte a double h firpm 16 0 1 3 1 0 0 1 1 C lculo de un filtro equiripple paso alto h ftrans2 h Convierte en filtro 2D i
40. mf filter2 h img b Filtrar la sefial Binarizar imagen try umb graythresh img b imf img bw im2bw img b imf umb threshold catch errordlg AJUSTAR VALOR UMBRAL Mensaje de error end oe oe Eliminar ruido Formas menores a 500pixel img bn bwareaopen img bw 500 Mostrar imagen en zona SNAPSHOT axes handles Zona de Captura imshow img bn Executes on button press in comienzo transferencia function comienzo transferencia Callback hObject eventdata handles hObject handle to comienzo transferencia see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA oe oe oe global num element global n amarillas global n rojas Serial PORT serial COM1 set Serial PORT Terminator CR LF fopen Serial PORT oe oo Envio de datos de la TABLA a traves del puerto seri numero formas n_amarillastn rojas for n 1 numero formas j pce cr cell2mat num element n cell2mat num element n cell2mat num element cell2mat num element cell2mat num element a4 n5 n 6 1 2 n 3 n 6 disp 3 fprintf Serial PORT Ss j fprintf Serial PORT An pause 0 1 end CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 21 UVIC helpdlg TRANSFERENCIA TERMINADA CableBOT oe Cerramos
41. mos el boton ON para volver a activar el panel set handles tools off Enable off Deshabilitamos el boton de OFF porque ya no es visible el panel 5 Deshabilitar boton START Comienzo de transferencia de datos set handles comienzo transferencia Enable off sDeshabilitamos el boton de OFF porque ya no es visible el panel 5 Guardamos los handles handles output hObject guidata hObject handles Deshabilita el boton de filtro B amp W hasta que no est n escala de grises Comienza la GUI con el boton deshabilitado Sigue en boton imagen gris set handles imagen blanco negro Enable off UIWAIT makes CableBOT wait for user response s UIRESUME uiwait handles figurel o Outputs from this function are returned to the command line function varargout CableBOT OutputFcn hObject eventdata handles varargout cell array for returning output args see VARARGOUT oo hObject handle to figure eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA o Get default command line output from handles structure varargout 1l handles output o Executes on button press in Captura Imagen function Captura Imagen Callback hObject eventdata handles oe Captura de imagen mediante WebCam SParte del programa encargada de la captura de la imagen de la webcam Usamos las sentencias
42. nacion de color Deteccion de piezas amarillas obal imagen formas amarillas obal imagen formas rojas oe oe oe Qu oe Deteccion de piezas amarillas imagen formas amarillas color new imagen cam RGB yellow color umbral yellow amarillas l not imagen formas amarillas SInvertir imagen amarillas 2 bwareaopen amarillas 1 700 SEliminar ruido se strel square 5 Rellenar huecos vacios amarillas 3 imclose amarillas 2 se figure subplot 1 2 1 imshow new imagen cam title Imagen ORIGINAL subplot 1 2 2 imshow amarillas 3 title Piezas AMARILLAS helpdlg Seguir proceso pulsando tecla CableBOT o pause Deteccion de piezas rojas imagen formas rojas 1l color new imagen cam RGB red color umbral red imagen formas rojas 2 xor imagen formas rojas 1 imagen formas amarillas imagen formas rojas 3 bwareaopen imagen formas rojas 2 100 se strel square 10 Rellenar huecos vacios imagen formas rojas imclose imagen formas rojas 3 se figure subplot 1 2 1 imshow new imagen cam title Imagen ORIGINAL subplot 1 2 2 imshow imagen formas rojas title Piezas ROJAS pause CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 16 UVIC Mensaje de aviso para continuar en la GUID opc questdlg CONTINUAR CON BOTON PLACE Deteccion Finalizada SI NO SI if strcmp opc SI close figure 2 close figur
43. on varargout SCALE M file for Scale See also GUIDE fig o oe oe Edit the above text to modify th Last Modified by GUIDE qui Callback if nargin amp amp ischar varargin 1 gui State gui Callback end if nargout varargout l nargout e function Scale OpeningFcn hObject oe Jo 5 Choose default handles output hObject structure handles Update handles guidata hObject global hipot set handles edit2 String hipot GUIDATA GUIHANDLI Scale varargin ti ca qui Singleton gui OpeningFocn gui OutputFon gui_LayoutFcn gui mainfcn gui State This function has no output args response to help Scale v2 5 18 Aug 2014 10 48 31 Begin initialization code DO NOT EDIT gui Singleton 1 gui State struct gui Name mfilename gui Singleton Scale OpeningFcn Scale OutputFocn ll 2 str2func varargin 1 varargin else gui_mainfcn gui State varargin end End initialization code DO NOT EDIT Executes just before Scale is made visible eventdata handles see OutputFcn varargin 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 Scale see VARARGIN command line output for Scale oe varargout hObject eventdata handle
44. onsta de diferentes subrutinas o procedimientos con la extensi n propia del programa m Cada uno de los procedimientos es el encargado de una funci n concreta de forma que si se requiere la modificaci n de una de las partes solamente se accede a dicho procedimiento a realizar la modificaci n pertinente quedando el resto del programa intacto para evitar posibles conflictos Los archivos que forman dicho software son los citados a continuaci n RELACION DE ARCHIVOS NOMBRE DESCRIPCION Presentaci n m Archivo inicial en el cual aparece el bot n de inicio del sistema CableBOT m Archivo que nos ofrece la visualizaci n de la pantalla principal del programa en la cual se realiza la adquisici n y tratamiento de la imagen Calibration m Procedimiento encargado de la calibraci n de la c mara respecto a la zona de trabajo Motor_Control m Archivo que muestra en pantalla la ventana de control del motor para comenzar el ciclo de almacenamiento de las fichas Gamepad_Control m Toma de control del actuador desde una joystick inal mbrico z de juegos para PC para dar m s amplitud al proyecto Scale m Procedimiento que escala la imagen de forma que pasa de trabajar en pixeles a trabajar en mil metros Color m Detecci n del color de las fichas usadas en la maqueta bien amarillo o rojo Place m Detecci n del centroide de cada una de las figuras Discriminaci n de las figuras seg n su forma Cuadrada triangular o circ
45. or Motor Control handles output hObject o Update handles structure CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 28 UVIC guidata hObject handles UIWAIT makes Motor Control wait for user response s UIRESUME uiwait handles figurel o Outputs from this function are returned to the command line function varargout Motor Control OutputFcn hObject eventdata handles Get default command line output from handles structure varargout 1 handles output Recuperacion de variables global panoramica CAM global azimutal CAM Camara panoramica try vid videoinput winvideo panoramica CAM RGB24 640x480 esto crea el canal de video a la camara web cateh errordlg CAMARA PANORAMICA NO CONECTADA Mensaje de error end 5 Camara azimutal try vid l videoinput winvideo azimutal CAM RGB24 800x600 esto crea el canal de video a la camara web caton errordlg CAMARA AZIMUTAL NO CONECTADA Mensaje de error end vid_1 TriggerFrameDelay 25 vid_1 FramesPerTrigger 1 vidRes get vid 1 VideoResolution imWidth vidRes 1 imHeight vidRes 2 nBands get vid 1 NumberOfBands hImage image zeros imHeight imWidth nBands Parent handles video 2 preview vid_1 hImage start vid 1 oe Camara panoramica con seguimiento del efector Tomo las caracteristicas que la camara tiene por defecto
46. pantalla de la GUID de forma que tenga una mejor vision de cara al usuario scrsz get 0 ScreenSize pos act get gcf Position xr scrsz 3 pos act 3 xp round xr 2 yr scrsz 4 pos_act 4 yp round yr 2 set gcf Position xp yp pos_act 3 pos _act 4 El ole Insertar Logo de la UVic Con estas instrucciones leo la imagen del logo y la represento en el axes correspondiente logo imread C Documents and Settings LOPEZ Escritorio GRADO PFG CableBOT GUI MatLab Logos logoHome jpg logo imread Logos logoHome jpg image logo axis off oe Personalizar boton SALIR SInsertar imagen en el boton cerrar de forma que vemos el simbolo salir en el boton a map imread Logos cerrar jpg r c d size a x ceil r 50 y ceil c 50 g a 1 x end 1 y end g g 255 5 1 255 set handles Salir CData g oe Carta de ajuste en axes Comienzo de lops axes con carta de ajuste en pantalla axes handles video 1 zona de captura background imread Logos cartadeajuste jpg cargamos la imagen axis off quitamos los ejes de la zona de captura axes 9 imshow background mostramos la imagen en la zona capturada 9 axes handles video 2 zona de captura o axis off quitamos los ejes de la zona de captura axes 9 imshow background mostramos la imagen en la zona capturada o Choose default command line output f
47. que la camara tiene por defecto Configuracion de las propiedades del objeto VidSrc getselectedsource vid set vid FocusMode auto set vid FramesPerTrigger Inf set vid ReturnedColorspace rgb vid FrameGrabInterval 1 flushdata vid x 1 while x for n 1 3 Comienzo de la adquisicion start vid Bucle de toma de imagenes while vid FramesAcquired lt 200 oe oe o Tomamos una foto de la camara data getsnapshot vid SPara el tracking sacamos la componente azul de cada imagen y la tratamos de forma que identificamos solamente las formas de color azul diff im imsubtract data 3 rgb2gray data Usamos filtro de media para reducir el ruido diff im medfilt2 diff im 3 3 SBinarizamos imagen diff im im2bw diff im 0 18 Fuera ruido menor a 500 pixels diff im bwareaopen diff im 500 CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 23 UVIC oe Etiquetamos todos los componentes de la imagen bw bwlabel diff im 8 Tomamos la informacion de los objetos detectados stats regionprops bw BoundingBox Centroid Zona de visualizacion de la imagen capturada set handles text1 String CENTERED Cambio el texto de la zona de visualizaci n Creamos la zona en la cual se mostrar la imagen capturada 9 axes handles Zona de Captura zona de captura background data cargamos la imagen capturada ax
48. s oe handle to figure oo oe cell array for returning output args UIWAIT makes Scale wait for user response s UIRESUME uiwait handles figurel Outputs from this function are returned to the command line function varargout Scale OutputFcn hObject eventdata handles see VARARGOUT reserved to be defined in a future version of MATLAB structure with handles and user data see GUIDATA CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 35 UVIC Get default command line output from handles structure varargout 1 handles output Executes on button press in aceptar function aceptar Callback hObject eventdata handles hObject handle to aceptar see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA global scale Val get handles editl String Almacenar valor ingresado scale str2double Val Transformar a formato double delete handles figurel Executes on button press in cancelar function cancelar Callback hObject eventdata handles hObject handle to cancelar see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA delete handles figurel oe oe Executes on button press in pushbutton3 function pushbutton3 Callback hObject event
49. th handles and user data see GUIDATA oe oe oe oe Hints get hObject Value returns position of slider get hObject Min and get hObject Max to determine range of oe slider Cargar el valor del Slider umbral en la zona de visualizacion handles sliderl5 get hObject Value Carga en handles sliderl5 el valor del Slider set handles text10 String sprintf 1 2f handles sliderl15 valor de Slider en statictext oo Escribe el CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 22 UVIC global threshold threshold get hObject Value Carga en threshold el valor del Slider Executes on button press in calibracion distancia function calibracion distancia Callback hObject eventdata handles hObject handle to calibracion distancia see GCBO eventdata reserved to be defined in a future version of MATLAB handles structure with handles and user data see GUIDATA global relacion global azimutal CAM opc questdlg Que deseas hacer Escalado o Centrado CALIBRATION Scale Centered Centered if strcmp opc Centered Camara azimutal try vid videoinput winvideo 1 RGB24 800x600 esto crea el canal de video a la camara web catch errordlg CAMARA AZIMUTAL NO CONECTADA Mensaje de error end 5 Parte del centrado oe Camara panoramica con seguimiento del efector Tomo las caracteristicas
50. tual 4 8 1 amp amp anterior 4 8 fprintf Serial PORT s n 8 disp Motor 4 atras end anterior 4 8 actual 4 8 oe Envio 8 por el serial oe Control mediante los botones en cruz Con estos botones movemos el robot en la direccion seleccionada oe SFlanco robot adelante Flechas actual povs O povs if actual povs 0 0 amp amp anterior povs 0 0 fprintf Serial PORT sWMn E Envio E por el serial disp ROBOT ADELANTE end anterior povs O actual povs 0 SFlanco robot derecha Flechas actual povs 90 povs if actual povs 90 90 amp amp anterior povs 90 90 fprintf Serial PORT ss n H SEnvio H por el serial disp ROBOT DERECHA end anterior povs 90 actual povs 90 S Flanco robot atras Flechas actual povs 180 povs if actual povs 180 180 amp amp anterior povs 180 180 fprintf Serial PORT sMn F SEnvio F por el serial disp ROBOT ATRAS end anterior povs 180 actual povs 180 Flanco robot izquierda Flechas actual povs 270 povs if actual povs 270 270 amp amp anterior povs 270 270 fprintf Serial PORT ss n G SEnvio G por el serial disp ROBOT IZQUIERDA end anterior povs 270 actual povs 270 end fclose Serial PORT delete Serial PORT clear Serial PORT end se se CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 34 UVIC 3 1 6 Scale m functi
51. ular CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 3 UVIC 2 1 1 Diagrama de bloques Diagrama de bloques en el cual se puede observar el proceso que sigue el software de vision artificial para llevar a cabo su cometido el de discriminar las figuras situadas en la zona de trabajo Presentacion m Figura 2 1 Diagrama de bloques del software de visi n artificial CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 4 UVIC 2 2 Codigo fuente firmware De igual forma que el punto anterior en este se quiere representar de forma grafica la secuencia que sigue el firmware para llevar a cabo el almacenaje de las piezas ya sea de forma manual como automatica 2 2 1 Diagrama de bloques CONTROL MANUAL MOVIMIENTO X Y Z CONTROL AUTOM TICO Figura 2 2 Diagrama de bloques del firmware de control CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 5 UVIC 3 Anexos 3 1 Codigo software MATLAB 3 1 1 Presentaci n m function presentacion ZK KKK KK KK KK KK KKK kk KK KK KK KK KK KK KK KK RK KK KK KK KK KKK RK KK kck ck ckck kck ck ckckckck KK KKK SAutor Alberto Lopez German Centro Universidad Politecnica de Vic Fecha 08 09 2013 Descripcion Funci n que inicia el programa con una ventana de presentaci n antes de lanzar el programa principal con el motivo de mostrar informaci n relativa al programa Ck CC ck ck kk Ck kk Ck Ck kk Ck Ck Ck Sk Ck kk Sk kk Ck k
52. unas plantillas creadas previamente o Ae oe oe PAR METROS DE ENTRADA Simagen Ultima imagen arreglada para la deteccion de las formas sumbral Valor del threshold hayyado en el panel de herramientas para binarizar sin tener problemas oe T PAR METROS DE SALIDA o sforma Vector con la forma de cada figura img o imagen original Muestra la imagen inicial img imagen tratada CODIGO FUENTE GRADO EN ELECTRONICA INDUSTRIAL Y AUTOMATICA 39 UVIC figure imshow img_o InitialMagnification 200 title Original helpdlg Seguir proceso pulsando tecla CableBOT 9 pause Espera a pulsar tecla Pasar a escala de grises img g rgb2gray img subplot 3 3 3 imshow img g figure imshow img g title Grises pause SEspera a pulsar tecla 5 Realzar los bordes img b double img g 255 Convierte a double h firpm 80 0 1 3 1 11 1 alto h ftrans2 h Convierte en filtro 2D imf filter2 h img b Filtrar la sefial subplot 3 3 4 imshow img b imf figure imshow img b imf title Resalte bordes pause Espera a pulsar tecla 6 Binarizar imagen try umb graythresh img b imf img bw im2bw img b imf umb umbral catch errordlg AJUSTAR VALOR UMBRAL Mensaje de error end subplot 3 3 5 imshow img bw figure imshow img bw title Binarizada pause Espera a pulsar tecla oe oo

Download Pdf Manuals

image

Related Search

Related Contents

DS-850 取扱説明書  www.caleffi.com  MNL Powador XP100-HV IT 121128  TLZ11  Artema Desk  TSC693E Memory Controller / User`s Manual    2x4 DuoFit™ In Wall Tank System Drain Kit 2x4 DuoFit  Hama uRage Illuminated Essential    

Copyright © All rights reserved.
Failed to retrieve file