banner



How To View Camera On Raspberry Pi

raspi_still_example_1

Over the by year the PyImageSearch blog has had a lot of pop blog posts. Using k-means clustering to find the dominant colors in an prototype was (and still is) hugely popular. One of my personal favorites, building a kick-ass mobile document scanner has been the most popular PyImageSearch commodity for months. And the first (big) tutorial I ever wrote, Hobbits and Histograms, an commodity on building a simple image search engine, still gets a lot of hits today.

But by far , the most popular post on the PyImageSearch blog is my tutorial on installing OpenCV and Python on your Raspberry Pi ii and B+. Information technology's actually, really awesome to come across the love you and the PyImageSearch readers have for the Raspberry Pi community — and I program to continue writing more than articles nearly OpenCV + the Raspberry Pi in the future.

Anyway, after I published the Raspberry Pi + OpenCV installation tutorial, many of the comments asked that I go on on and discuss how to admission the Raspberry Pi photographic camera using Python and OpenCV.

In this tutorial nosotros'll be using picamera, which provides a pure Python interface to the camera module. And best of all, I'll be showing you how to use picamera to capture images in OpenCV format.

Read on to find out how…

Important: Be sure to follow 1 of my Raspberry Pi OpenCV installation guides prior to following the steps in this tutorial.

Looking for the source code to this post?

Jump Right To The Downloads Department

OpenCV and Python versions:
This example volition run on Python 2.7/Python 3.iv+ and OpenCV 2.4.X/OpenCV three.0+.

Step ane: What do I need?

To get started, you'll demand a Raspberry Pi camera board module.

I got my 5MP Raspberry Pi camera board module from Amazon for under $xxx, with shipping. Information technology'due south hard to believe that the camera board module is almost equally expensive as the Raspberry Pi itself — but it just goes to evidence how much hardware has progressed over the past 5 years. I likewise picked upwardly a camera housing to keep the camera rubber, because why non?

Assuming yous already have your photographic camera module, you lot'll need to install it. Installation is very simple and instead of creating my own tutorial on installing the camera board, I'll simply refer you lot to the official Raspberry Pi photographic camera installation guide:

Bold your camera lath and properly installed and setup, information technology should expect something like this:

Figure 1: Installing the Raspberry Pi camera board.
Figure 1: Installing the Raspberry Pi camera board.

Footstep two: Enable your camera module.

Now that you have your Raspberry Pi camera module installed, you lot demand to enable it. Open up a terminal and execute the following control:

$ sudo raspi-config          

This will bring up a screen that looks like this:

Figure 2: Enabling the Raspberry Pi camera module using the raspi-config command.
Figure 2: Enabling the Raspberry Pi camera module using the raspi-config command.

Employ your arrow keys to gyre down to Option five: Enable camera, hit your enter primal to enable the camera, so arrow down to the End push and hit enter again. Lastly, you'll need to reboot your Raspberry Pi for the configuration to take affect.

Stride 3: Exam out the camera module.

Before we dive into the code, permit's run a quick sanity bank check to ensure that our Raspberry Pi photographic camera is working properly.

Annotation: Trust me, you'll want to run this sanity check before you start working with the code. It's always good to ensure that your camera is working prior to diving into OpenCV code, otherwise you could easily waste time wondering when your code isn't working correctly when it's simply the camera module itself that is causing you problems.

Anyhow, to run my sanity check I connected my Raspberry Pi to my TV and positioned it such that information technology was pointing at my couch:

Figure 3: Example setup of my Raspberry Pi 2 and camera.
Figure 3: Example setup of my Raspberry Pi 2 and photographic camera.

And from at that place, I opened upwardly a final and executed the post-obit command:

$ raspistill -o output.jpg          

This command activates your Raspberry Pi camera module, displays a preview of the paradigm, then afterwards a few seconds, snaps a picture, and saves it to your current working directory as output.jpg .

Here'due south an instance of me taking a photo of my TV monitor (so I could document the process for this tutorial) as the Raspberry Pi snaps a photo of me:

Figure 4: Sweet, the Raspberry Pi camera module is working!
Effigy iv: Sweet, the Raspberry Pi camera module is working!

And here'south what output.jpg looks like:

Figure 5: The image captured using the raspi-still command.
Figure 5: The image captured using the raspi-still command.

Clearly my Raspberry Pi camera module is working correctly! Now we can move on to the some more exciting stuff.

Step 4: Installing picamera.

Then at this point we know that our Raspberry Pi camera is working properly. But how do we interface with the Raspberry Pi camera module using Python?

The answer is the picamera module.

Retrieve from the previous tutorial how nosotros utilized virtualenv and virtualenvwrapper to cleanly install and segment our Python packages from the the arrangement Python and packages?

Well, we're going to exercise the aforementioned affair here.

Before installing picamera , be sure to activate our cv virtual environment:

$ workon cv          

Note: If you are installing the the picamera module system wide, you can skip the previous commands. However, if you lot are following forth from the previous tutorial, you lot'll want to brand sure yous are in the cv virtual environment before continuing to the next command.

And from there, we can install picamera by utilizing pip:

$ pip install "picamera[array]"          

Important: Notice how I specified picamera[assortment] and not just picamera .

Why is this and so important?

While the standard picamera module provides methods to interface with the photographic camera, we demand the (optional) array sub-module so that we can utilize OpenCV. Remember, when using Python bindings, OpenCV represents images as NumPy arrays — and the array sub-module allows us to obtain NumPy arrays from the Raspberry Pi camera module.

Bold that your install finished without mistake, y'all now have the picamera module (with NumPy assortment support) installed.

Pace v: Accessing a single image of your Raspberry Pi using Python and OpenCV.

Alright, now we can finally showtime writing some code!

Open a new file, proper noun information technology test_image.py , and insert the following lawmaking:

# import the necessary packages from picamera.array import PiRGBArray from picamera import PiCamera import time import cv2  # initialize the photographic camera and grab a reference to the raw camera capture camera = PiCamera() rawCapture = PiRGBArray(camera)  # allow the camera to warmup time.sleep(0.i)  # grab an image from the camera camera.capture(rawCapture, format="bgr") image = rawCapture.assortment  # display the image on screen and wait for a keypress cv2.imshow("Prototype", image) cv2.waitKey(0)          

Nosotros'll start by importing our necessary packages on Lines 2-5.

From there, we initialize our PiCamera object on Line 8 and grab a reference to the raw capture component on Line 9. This rawCapture object is specially useful since information technology (one) gives usa direct access to the photographic camera stream and (2) avoids the expensive compression to JPEG format, which we would so have to take and decode to OpenCV format anyway. I highly recommend that you use PiRGBArray whenever you demand to admission the Raspberry Pi camera — the functioning gains are well worth it.

From there, nosotros sleep for a tenth of a 2nd on Line 12 — this allows the photographic camera sensor to warm up.

Finally, we catch the actual photo from the rawCapture object on Line xv where we accept special intendance to ensure our image is in BGR format rather than RGB. OpenCV represents images as NumPy arrays in BGR order rather than RGB — this little nuisance is subtle, but very important to call up every bit it can lead to some confusing bugs in your lawmaking downwards the line.

Finally, nosotros display our image to screen on Lines nineteen and 20.

To execute this instance, open up a concluding, navigate to your test_image.py file, and consequence the following control:

$ python test_image.py          

If all goes equally expected you lot should have an paradigm displayed on your screen:

Figure 6: Grabbing a single image from the Raspberry Pi camera and displaying it on screen.
Effigy 6: Grabbing a single image from the Raspberry Pi camera and displaying it on screen.

Annotation: I decided to add this section of the blog post later on I had finished up the rest of the article, so I did not have my camera setup facing the couch (I was actually playing with some custom home surveillance software I was working on). Sorry for any defoliation, simply rest assured, everything will work every bit advertised provided y'all have followed the instructions in the commodity!

Step vi: Accessing the video stream of your Raspberry Pi using Python and OpenCV.

Alright, so nosotros've learned how to grab a single image from the Raspberry Pi camera. Merely what virtually a video stream?

Yous might guess that nosotros are going to utilize the cv2.VideoCapture role here — simply I actually recommend against this. Getting cv2.VideoCapture to play nice with your Raspberry Pi is not a nice experience (you'll demand to install extra drivers) and something yous should mostly avert.

And as well, why would we use the cv2.VideoCapture part when we tin easily access the raw video stream using the picamera module?

Permit'southward go ahead and have a look on how we can access the video stream. Open up a new file, name it test_video.py , and insert the following code:

# import the necessary packages from picamera.array import PiRGBArray from picamera import PiCamera import time import cv2  # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (640, 480) camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(640, 480))  # permit the photographic camera to warmup time.sleep(0.i)  # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): 	# catch the raw NumPy array representing the image, so initialize the timestamp 	# and occupied/unoccupied text 	paradigm = frame.array  	# prove the frame 	cv2.imshow("Frame", image) 	primal = cv2.waitKey(1) & 0xFF  	# clear the stream in preparation for the next frame 	rawCapture.truncate(0)  	# if the `q` key was pressed, interruption from the loop 	if primal == ord("q"): 		break          

This example starts off similarly to the previous one. We start off by importing our necessary packages on Lines 2-5.

And from in that location nosotros construct our photographic camera object on Line 8 which allows the states to interface with the Raspberry Pi camera. Notwithstanding, nosotros also take the time to set the resolution of our photographic camera (640 x 480 pixels) on Line 9 and the frame rate (i.east. frames per second, or simply FPS) on Line x. We also initialize our PiRGBArray object on Line 11, but we also take intendance to specify the aforementioned resolution every bit on Line 9.

Accessing the actual video stream is handled on Line 17 by making a call to the capture_continuous method of our camera object.

This method returns a frame from the video stream. The frame then has an array holding, which corresponds to the frame in NumPy array format — all the difficult work is done for us on Lines 17 and 20!

We then accept the frame of the video and display on screen on Lines 23 and 24.

An important line to pay attention to is Line 27: You must clear the electric current frame before yous motion on to the next one!

If you neglect to clear the frame, your Python script volition throw an error — so exist sure to pay shut attention to this when implementing your own applications!

Finally, if the user presses the q key, we intermission form the loop and go out the plan.

To execute our script, just open up a last (making certain you are in the cv virtual environment, of course) and issue the following control:

$ python test_video.py          

Beneath follows an example of me executing the above command:

Every bit you tin see, the Raspberry Pi camera'due south video stream is beingness read by OpenCV and then displayed on screen! Furthermore, the Raspberry Pi photographic camera shows no lag when accessing frames at 32 FPS. Granted, we are not doing any processing on the individual frames, but as I'll bear witness in hereafter blog posts, the Pi 2 can easily keep up 24-32 FPS even when processing each frame.

What's adjacent? I recommend PyImageSearch Academy.

Course information:
35+ total classes • 39h 44m video • Last updated: Apr 2022
★★★★★ 4.84 (128 Ratings) • 13,800+ Students Enrolled

I strongly believe that if you had the right teacher you could master estimator vision and deep learning.

Exercise you think learning estimator vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve circuitous mathematics and equations? Or requires a degree in information science?

That's not the case.

All you need to master calculator vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that'southward exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you lot're serious about learning figurer vision, your next stop should exist PyImageSearch Academy, the most comprehensive computer vision, deep learning, and OpenCV form online today. Here you lot'll acquire how to successfully and confidently apply calculator vision to your work, research, and projects. Join me in computer vision mastery.

Inside PyImageSearch University y'all'll find:

  • 35+ courses on essential computer vision, deep learning, and OpenCV topics
  • 35+ Certificates of Completion
  • 39+ hours of on-demand video
  • Make new courses released regularly , ensuring you lot can go on up with country-of-the-art techniques
  • Pre-configured Jupyter Notebooks in Google Colab
  • ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev surroundings configuration required!)
  • ✓ Access to centralized code repos for all 450+ tutorials on PyImageSearch
  • Easy i-click downloads for code, datasets, pre-trained models, etc.
  • Access on mobile, laptop, desktop, etc.

Click here to join PyImageSearch Academy

Summary

This article extended our previous tutorial on installing OpenCV and Python on your Raspberry Pi 2 and B+ and covered how to admission the Raspberry Pi camera module using Python and OpenCV.

Nosotros reviewed two methods to access the camera. The first method immune us to admission a single photo. And the 2nd method immune us to access the raw video stream from the Raspberry Pi camera module.

In reality, there are many ways to access the Raspberry Pi photographic camera module, equally the picamera documentation details. However, the methods detailed in this blog post are used because (1) they are easily compatible with OpenCV and (2) they are quite speedy. There are certainly more i fashion to skin this true cat, only if you intend on using OpenCV + Python, I would suggest using the code in this commodity as "boilerplate" for your own applications.

In future blog posts we'll accept these examples and use information technology to build computer vision systems tofind motility in videos and recognize faces in images.

Be sure to sign upwardly for the PyImageSearch Newsletter to receive updates when new Raspberry Pi and computer vision posts get live, y'all definitely don't want to miss them!

Download the Source Code and Complimentary 17-page Resources Guide

Enter your email address below to become a .zip of the lawmaking and a FREE 17-page Resources Guide on Estimator Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to assist you master CV and DL!

Source: https://pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/

Posted by: ballardloortambel1953.blogspot.com

0 Response to "How To View Camera On Raspberry Pi"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel