Seguimiento de objetos con Raspberry . Visión Artificial

Español

En este proyecto vamos a presentar como usar la Raspberry Pi para conectar una webcam y poder realizar el seguimiento de un objeto a través de esa camara y un servomotor conectada a ella. 

1.- Instalación del SO en la SD de la Raspberry

Para realizar el proyecto probamos primeramente con Raspbian y con Pidora. El hecho de usar estos SO nos obliga posteriormente a instalar muchas librearias externas, y al final algunas nos dieron problemas de compatibilidad. Es por ello que nos decantamos por Occidentalis (sección HOW TO INSTALL) .Esta versión ya incluye la mayoria de librerias que necesitamos para el proyecto.

 

2.- Conexión del servomotor a la Raspberry Pi

 

Para realizar la conexión entre el portapilas (necesario para alimentar el servo) , Servo y Raspberry Pi procederemos de la manera siguiente:

- El servo lleva tres cables :

rojo = +5V

negro = GND

Amarillo/blanco/naranja = señal de control 

- Unimos el cable rojo del portapilas con el cable rojo del servomotor

- Unimos el cable negro del servo con el cable negro del portapilas

Ahora tenemos hechas las conexiones tal y como se muestra en la fotografia 

- Conectamos los 2 pins ( negativo y control ) a la raspberry Pi .

 

Para ello debemos conectar el negativo a alguno de los pins de masa de la Raspberry ( pin 6, pin 14 o pin 25) y conectar el cable de control al pin correspondiente donde enviaremos los pulsos, en nuestro caso el pin 4 (si queremos cambiar de pin , deberemos ajustar las lineas correspondientes de codigo ).

Programa : servo.py

# Servo Control
import time
# Definimos la variable de la función
def set(property, value):
try:
f = open("/sys/class/rpi-pwm/pwm0/" + property, 'w')
f.write(value)
f.close()
except:
print("Error writing to: " + property + " value: " + value)
# Definimos el angulo que tiene que realizar el servo
def setServo(angle):
set("servo", str(angle))
set("delayed", "0")
set("mode", "servo")
# Angulo máximo al cual debe llegar el servo
set("servo_max", "180")
set("active", "1")
# Funcíon para indicar la velocidad de giro del servo.
delay_period = 0.01
# Funció de repetición(bucle).
while True:
# Acción para empezar a 0º y llegar hasta 180º
for angle in range(0, 180):
setServo(angle)
time.sleep(delay_period)
# Acción para empezar en 180º y llegar hasta 0º
for angle in range(0, 180):
setServo(180 - angle)
time.sleep(delay_period)

(fuente : Adafruit )

Con este programa comprobaremos que el servomotor realiza giros de 180º en los dos sentidos. De esta manera sabemos que la comunicación con la raspberry es correcta.

3.- Conexión de la webcam a la Raspberry Pi

Ahora debemos conectar la webcam a la raspberry y comprobar también su comunicación en combinación con el servo. La unión entre la webcam y el servo puede ser simplemente un velcro de doble cara

El programa que usaremos para la comunicación es el siguiente : cam.py

 

# - * - Coding: utf-8 - * - 
# CamTracker.py - track a colourful object with a webcam mounted atop a servo
# Running on a Raspberry Pi, Raspbian Wheezy OS
# (c) Sakari Kapanen, 2013
import cv2
import numpy as np
from RPIO import PWM
# the HSV range we use to detect the colourful object
Hmin = 159
Hmax = 179
Smin = 108
Smax = 255
Vmin = 80
Vmax = 255
# minimum detected area
minArea = 50
# frame parameters
width = 160
height = 120
cx = int(0.5 * width)
cy = int(0.5 * height)
# servo PWM pulsewidths
dServo = 20
servoVal = 1500
servoMin = 500
servoMax = 2500
# the maximum delta (pixels) when the object is still considered centered
eps = 15
rangeMin = np.array([Hmin, Smin, Vmin], np.uint8)
rangeMax = np.array([Hmax, Smax, Vmax], np.uint8)
cv2.namedWindow("Adjustment")
cv2.namedWindow("Video")

cv2.namedWindow("Binary")
def nothing(*args):
pass
def updateRanges():
Hmin = cv2.getTrackbarPos("Hmin", "Adjustment")
Hmax = cv2.getTrackbarPos("Hmax", "Adjustment")
Smin = cv2.getTrackbarPos("Smin", "Adjustment")
Smax = cv2.getTrackbarPos("Smax", "Adjustment")
Vmin = cv2.getTrackbarPos("Vmin", "Adjustment")
Vmax = cv2.getTrackbarPos("Vmax", "Adjustment")
minArea = cv2.getTrackbarPos("minArea", "Adjustment")
rangeMin = np.array([Hmin, Smin, Vmin], np.uint8)
rangeMax = np.array([Hmax, Smax, Vmax], np.uint8)
return rangeMin, rangeMax, minArea
# create controls for adjusting the detection range
cv2.createTrackbar("Hmin", "Adjustment", Hmin, 179, nothing)
cv2.createTrackbar("Hmax", "Adjustment", Hmax, 179, nothing)
cv2.createTrackbar("Smin", "Adjustment", Smin, 255, nothing)
cv2.createTrackbar("Smax", "Adjustment", Smax, 255, nothing)
cv2.createTrackbar("Vmin", "Adjustment", Vmin, 255, nothing)
cv2.createTrackbar("Vmax", "Adjustment", Vmax, 255, nothing)
cv2.createTrackbar("minArea", "Adjustment", minArea, 1000, nothing)
# capture from the first webcam found
cap = cv2.VideoCapture(0)
if cap.isOpened():
cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height)
servo = PWM.Servo()
servo.set_servo(4, servoVal)
while True:
servo.set_servo(4, servoVal)
# read a frame
ret, image = cap.read()
# blur the frame
image = cv2.blur(image, (3, 3))
# convert to HSV
imgHSV = cv2.cvtColor(image, cv2.cv.CV_BGR2HSV)
rangeMin, rangeMax, minArea = updateRanges()
# pixels within range are set to 1, others to 0
imgThresh = cv2.inRange(imgHSV, rangeMin, rangeMax)
#imgThresh = cv2.blur(imgThresh, (2, 2))
# calculate image moments
moments = cv2.moments(imgThresh, True)
if moments['m00'] >= minArea:
# calculate the centroid of the object using the moments
x = moments['m10'] / moments['m00']
y = moments['m01'] / moments['m00']
cv2.circle(image, (int(x), int(y)), 5, (0, 255, 0), -1)
# move the servo if necessary, check limits
dx = x - cx
step = abs(int(dx / 20) * dServo)
if (x - cx) > eps:
servoVal += step
elif (cx - x) > eps:
servoVal -= step
if servoVal < servoMin:
servoVal = servoMin
if servoVal > servoMax:
servoVal = servoMax
cv2.imshow("Video", image)
cv2.imshow("Binary", imgThresh)
key = cv2.waitKey(10)
if key == 27:
break
cv2.destroyAllWindows()

(fuente : Flanelhead)

Para probar la comunicación ejecutaremos el programa cam.py desde el terminal (LXTerminal en la Raspberry):

>sudo python cam.py

Con ello deberiamos tener 4 ventanas en el escritorio:

  • LXterminal con datos de la cam
  • Pantalla de Video de la webcam
  • Pantalla de la zona detectada por la webcam
  • Pantalla de ajustes de valores 

Si por alguna razón no es correcto el funcionamiento o no se ejecuta el programa cam.py procederemos a instalar 3 librerias (Open CV, Numpy y RPIO) de la siguiente manera desde el terminal :

  • Biblioteca "Open CV" 

> sudo apt-get install libopencv-dev python-opencv

(enlace web)

  • Biblioteca "Numpy"

sudo apt-get install python-numpy

> sudo apt-get install python-scipy

> sudo apt-get install python-sympy

(enlace web)

  • Biblioteca "RPIO"

> sudo apt-get install python-setuptools

> sudo easy_install -U RPIO

(enlace web)


En este video podeis ver el seguimiento de la webcam a un objeto en este caso de color rosa (determinado por el ajuste de valores) y también lo que aparece en pantalla : Selector de color, Visión de la webcam y detección del objeto.

 

 

Comentarios

Spot on with this write-up, I seriously believe this amazing site needs far more attention.
I'll probably be returning to see more, thanks for the info!

Here is my weblog: migliori soundbar classifica - http://bsdadvocacy.org

This page truly has all of the information I needed about this subject and didn't know who to ask.

my webpage Sewa Mobil Padang - http://sewamobilpadangsl.com/

Just wish to say your article is as amazing.
The clarity in your post is simply cool and i could assume you are an expert on this subject.
Well with your permission allow me to grab your RSS feed to
keep updated with forthcoming post. Thanks a million and please continue the enjoyable work.

Here is my web page ... cea mai buna oala sub presiune - http://gammadosporcorrida.com

An outstanding share! I have just forwarded this onto
a co-worker who has been conducting a little homework on this.
And he actually ordered me breakfast simply because I found it Best bean bags for kids - http://childrensbeanbag.blogspot.com/ - http://childrensbeanbag.blogspot.com/2017/02/best-baby-bean-bags.html - him...
lol. So let me reword this.... Thank YOU for the meal!!
But yeah, thanks for spending time to discuss this
topic here on your web page.

Hello! I've been reading your web site for some time now and finally got the bravery to go ahead
and give you a shout out from Austin Tx! Just wanted to tell
you keep up the fantastic work!

Take a look at my page ... xbox live gold gratuit ( ultragenerators.com
- http://ultragenerators.com/xbox-live-gratuit/ )

You made some good points there. I looked on the net to learn more about the issue and found
most individuals will go along with your views on this
web site.

My web site - xbox live gratuit ( Ian - http://ultragenerators.com/xbox-live-gratuit/ )

It's a shame you don't have a donate button! I'd most certainly donate
to this brilliant blog! I guess for now i'll settle for bookmarking and adding your RSS feed to my Google account.
I look forward to fresh updates and will share this
blog with my Facebook group. Chat soon!

Also visit my blog :: mil prestamos - https://credito-urgentes.es/

My partner and I absolutely love your blog and find almost all of your
post's to be what precisely I'm looking for. can you offer guest writers to write content for you personally?
I wouldn't mind publishing a post or elaborating on many of the subjects you write
regarding here. Again, awesome blog!

my weblog machine expresso ( costaviola-magazine.com - http://costaviola-magazine.com )

Genuinely when someone doesn't be aware of after that its
up to other people that they will help, so here it happens.

Feel free to visit my web page xbox live gratuit ( http://ultragenerators.com/xbox-live-gratuit/ -
http://ultragenerators.com/xbox-live-gratuit/ )

I'm not sure why but this site is loading very slow for me.
Is anyone else having this problem or is it a problem on my end?
I'll check back later and see if the problem still exists.

Feel free to surf to my webpage: code starpass gratuit [ ultragenerators.com - http://ultragenerators.com/generateur-de-code-starpass-gratuit/ ]

You should be a part of a contest for one of the finest blogs
on the web. I most certainly will highly recommend this website!

Here is my homepage xbox live gratuit 2015 - http://ultragenerators.com/xbox-live-gratuit/

Good post however , I was wondering if you could write a litte more on this topic?
I'd be very grateful if you could elaborate a little bit more.
Cheers!

my web page microcredito personales - https://prestamoscondni.credito-urgentes.es/

I really like your blog.. very nice colors & theme.
Did you design this website yourself or did you hire someone to do it for you?
Plz reply as I'm looking to design my own blog and would like to find out where u got this from.
many thanks

Also visit my web site; migliori bidoni aspiratutti
- http://oklahoma-city-life.com

I was recommended this website by my cousin. I'm not sure whether his post is writte by him as no one else know suchh detailedd about mmy trouble.
You are wonderful! Thanks!

my page ... services - http://format.anadolu.edu.tr/forum/member.php?action=profile&uid=146787

Wow, wonderful blog layout! How lengthy have you ever been running a blog for?
you make blogging glance easy. The entire glance of your web site is wonderful, as neatly as the content!

Also visit my blog post :: Credito Urgentes - https://Prestamosprivados.credito-urgentes.es/

Appreciation to my father who shared with
me on the topic of this weblog, this blog is
genuinely amazing.

Feel free to surf to my web blog ... Credito seguro - https://comparadordeprestamos.credito-urgentes.es/

I like the valuable info you provide in your articles.
I'll bookmark your blog and check again here regularly.
I am quite sure I'll learn many new stuff right here! Good luck for the next!

my webpage; Passport Status - http://passportapplicationstatus.kinja.com/documents-required-for-passpo...

Wow, awesome blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your website is magnificent, let alone the content!

My blog post: xbox live gratuit - http://ultragenerators.com/xbox-live-gratuit/

I am in fact pleased to glance at this web site posts
which consists of tons of useful facts, thanks for providing such data.

my webpage :: dinero express - https://prestamosrapidos.credito-urgentes.es/

Do you have a spam problem on this site; I also am a
blogger, and I was wondering your situation; many of
us have created some nice methods and we are looking to exchange techniques with others, be sure to shoot me an email if interested.

Feel free to surf to my blog post: code starpass gratuit ( ultragenerators.com - http://ultragenerators.com/generateur-de-code-starpass-gratuit/ )

I do not know whether it's just me or if perhaps
everyone else experiencing problems with your blog.
It appears like some of the text in your posts are running off the screen. Can somebody else please provide feedback and let me
know if this is happening to them too? This could be a issue with my web browser because I've had
this happen before. Many thanks

My web page: generateur de code starpass - http://ultragenerators.com/ - http://ultragenerators.com/generateur-de-code-starpass-gratuit/ ,

If you desire to grow your know-how only keep visiting this web page and
be updated with the hottest information posted here.

my web page: xbox live gratuit ( http://ultragenerators.com/ - http://ultragenerators.com/xbox-live-gratuit/ )

Heya i am for the first time here. I came across
this board and I find It really useful & it helped me out
much. I hope to give something back and help others like
you helped me.

my homepage ... Obtenir un abonnement xbox live gold
gratuit - http://ultragenerators.com/xbox-live-gratuit/

What's up to every one, because I am in fact eager of reading this weblog's post to be updated
daily. It contains pleasant data.

Have a look at my website - xbox live Gratuit ( Ultragenerators.com - http://ultragenerators.com/xbox-live-gratuit/ )

I'm really inspired with your writing skills and also with the structure
in your weblog. Is this a paid subject or did you modify
it your self? Anyway stay up the excellent quality writing, it's rare to see a great blog like
this one nowadays..

Here is my web page; Xbox live gold gratuit [ Ultragenerators.com - http://ultragenerators.com/xbox-live-gratuit/ ]

I do not even understand how I finished up right here,
however I thought this post was good. I don't know who you might be
however certainly you are going to a well-known blogger
in case you aren't already ;) Cheers!

Take a look at my weblog - telecharger generateur de
code starpass - http://ultragenerators.com/generateur-de-code-starpass-gratuit/

Appreciating the time and energy you put into your website and detailed information you provide.
It's great to come across a blog every once in a while that isn't the same out
of date rehashed material. Excellent read! I've bookmarked your site and I'm adding your RSS feeds to my Google account.

my blog :: dinero express - https://prestamosdelgobierno.credito-urgentes.es/

Can I just say what a comfort to find a person that
actually understands what they are talking about
on the internet. You definitely know how to bring
a problem to light and make it important. More people should read
this and understand this side of your story. I was surprised you aren't more popular since you surely have the gift.

Also visit my blog code starpass gratuit ( ultragenerators.com - http://ultragenerators.com/generateur-de-code-starpass-gratuit/ )

This blog was... how do you say it? Relevant!!
Finally I have found something that helped me.

Many thanks!

Here is my page xbox live gold gratuit ( http://ultragenerators.com/xbox-live-gratuit/ - http://ultragenerators.com/xbox-live-gratuit/ )

I every time spent my half an hour to read this weblog's articles all the time along with a mug of coffee.

Feel free to surf to my page solicitar credito - https://comparadordeprestamos.credito-urgentes.es/

At this time it sounds like Drupal is the preferred blogging platform available right now.

(from what I've read) Is that what you're using on your blog?

Feel free to surf to my web page :: xbox live gratuit ( Ultragenerators.Com - http://ultragenerators.com/xbox-live-gratuit/ )

Good day I am so happy I found your blog page, I really
found you by error, while I was looking on Askjeeve for something else, Anyhow I
am here now and would just like to say thank you for a marvelous
post and a all round thrilling blog (I also love the theme/design), I don’t have time to read it all at the minute
but I have saved it and also included your RSS feeds, so when I have time I will be back
to read much more, Please do keep up the great b.

Feel free to surf to my web blog: xbox live gratuit ( ultragenerators.com - http://ultragenerators.com/xbox-live-gratuit/ )

Hello, There's no doubt that your web site might be having browser compatibility issues.
Whenever I look at your web site in Safari, it looks fine however when opening
in Internet Explorer, it has some overlapping issues. I
merely wanted to give you a quick heads up! Other than that, wonderful blog!

My website xbox live gratuit - Veola - http://ultragenerators.com/xbox-live-gratuit/ ,

I'm not sure exactly why but this blog is loading extremely slow for me.
Is anyone else having this issue or is it a problem
on my end? I'll check back later on and see if the problem still exists.

my webpage :: code starpass gratuit ( ultragenerators.com - http://ultragenerators.com/generateur-de-code-starpass-gratuit/ )

is cialis daily the best
[url=http://cialisoverthecounteratwalmartshop.com]cialis over the counter at walmart
[/url] buy cialis .u.k.
<a href="http://cialisoverthecounteratwalmartshop.com">cialis over counter
</a> - levitra cialis cialis comparison clip.cgi
can i take cialis if i have not got erectil problems

I'm extremely pleased to uncover this website.
I want to to thank you for ones time for this fantastic read!!
I definitely appreciated every little bit of it and I have
you book-marked to check out new stuff in your site.

Also visit my weblog; xbox live gratuit ( ultragenerators.com -
http://ultragenerators.com/xbox-live-gratuit/ )

Touche. Sound arguments. Keep up the good spirit.

Feel free to visit my page - xbox live gold gratuit - http://ultragenerators.com/xbox-live-gratuit/

My spouse and I absolutely love your blog and find the majority of your
post's to be what precisely I'm looking for.
Does one offer guest writers to write content for yourself?
I wouldn't mind writing a post or elaborating
on a number of the subjects you write related to here.

Again, awesome site!

Feel free to surf to my web page :: xbox live gold gratuit
- http://ultragenerators.com/xbox-live-gratuit/

Hi there to every body, it's my first go to see of this website; this weblog consists of amazing and really excellent data designed for
visitors.

Look at my site: xbox live gratuit ( ultragenerators.com - http://ultragenerators.com/xbox-live-gratuit/ )

you're truly a excellent webmaster. The web site loading
velocity is incredible. It kind of feels that you're doing
any unique trick. Furthermore, The contents are masterpiece.
you've done a magnificent process on this matter!

my homepage xbox live gold gratuit ( ultragenerators.com - http://ultragenerators.com/xbox-live-gratuit/ )

Attractive section of content. I just stumbled upon your
web site and in accession capital to assert that I acquire in fact
enjoyed account your blog posts. Anyway I will be subscribing to your augment and
even I achievement you access consistently rapidly.

my web site xbox live gold gratuit ( http://ultragenerators.com/xbox-live-gratuit - http://ultragenerators.com/xbox-live-gratuit/ )

If you desire to obtain a good deal from this article then you
have to apply these techniques to your won blog.

Review my website: xbox live gratuit - http://ultragenerators.com/xbox-live-gratuit/

Hi there, after reading this awesome paragraph i am too delighted to share my know-how here with mates.

Here is my weblog; Xbox Live Gratuit 2015 - http://ultragenerators.com/xbox-live-gratuit/

Howdy! Would you mind if I share your blog with
my myspace group? There's a lot of folks that I think would really
appreciate your content. Please let me know. Thanks

Take a look at my web blog xbox live gold gratuit [ http://ultragenerators.com - http://ultragenerators.com/xbox-live-gratuit/ ]

You made some good points there. I checked on the net for more information about the issue and found most people will go along with
your views on this web site.

Here is my blog post :: comment avoir abonnement xbox
live Gold Gratuit - http://ultragenerators.com/xbox-live-gratuit/

I was able to find good information from your blog articles.

Visit my webpage - xbox live gratuit ( ultragenerators.com -
http://ultragenerators.com/xbox-live-gratuit/ )

It's perfect time to make a few plans for the future and it is time to be happy.
I've learn this publish and if I may just I want to
recommend you some attention-grabbing issues or suggestions.

Perhaps you could write subsequent articles referring to this article.
I wish to learn even more things about it!

my web site :: xbox live gold gratuit - http://ultragenerators.com/xbox-live-gratuit/

My spouse and I stumbled over here from a different website and thought I might as well
check things out. I like what I see so now i'm
following you. Look forward to going over your web
page repeatedly.

My blog: Xbox live gold gratuit ( ultragenerators.com - http://ultragenerators.com/xbox-live-gratuit/ )

Howdy, i read your blog occasionally and i own a similar one
and i was just curious if you get a lot of spam responses?
If so how do you protect against it, any plugin or anything you can suggest?
I get so much lately it's driving me insane
so any assistance is very much appreciated.

Feel free to visit my website: Xbox Live Gold Gratuit
[ Ultragenerators.Com - http://ultragenerators.com/xbox-live-gratuit/ ]

Aw, this was an extremely good post. Taking the time and actual
effort to produce a really good article… but what can I say… I put things
off a lot and never seem to get anything done.

Feel free to surf to my page Xbox Live Gratuit ( Ultragenerators.Com - http://ultragenerators.com/xbox-live-gratuit/ )

Páginas

Añadir nuevo comentario

Plain text

  • No se permiten etiquetas HTML.
  • Las direcciones de las páginas web y las de correo se convierten en enlaces automáticamente.
  • Saltos automáticos de líneas y de párrafos.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.