Python 01: OpenCV + Webcam

RasPythonUsual when one starts learning any programming language, Hello World program should always be first contact.
In python that is just not educative… too simple.

Because of that, I started with something a little more interesting, display webcam’s output.

The source code that I will provide is quite self explanatory and well commented, so it should not be a problem following it.
Here is the source code:

# Load webcamera, show LiveFeed and save an imagem when exiting
#

#import opencv module 
import cv
 
# video capture constructor
capture = cv.CaptureFromCAM(0)
 
# creates the window that will display the image
cv.NamedWindow("webcam")
 
while True:
    # frame grab and display
    frame = cv.QueryFrame(capture)
    cv.ShowImage("webcam", frame)

    # wait for any key to be pressed
    k = cv.WaitKey(5)
    if k % 256 == 10:
        # enter
        cv.SaveImage("imagem.png", frame)
    if k % 256 == 27:
        # quit
        break

# closes window
cv.DestroyWindow("webcam")

Copy/Paste this code to any text editor and save it as .py extension (e.g. program_opencv_webcam.py) and using the terminal run it like:

$ python program_opencv_webcam.py

You should see something like this:

pic_opencv_webcam

Output from program_opencv_webcam.py


Bonus: Hello, world!

print("Hello, world!")
Advertisements
This entry was posted in Python, Raspberry Pi and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s