OpenCV4

From ESE205 Wiki
Jump to navigation Jump to search

Step 1: Install OpenCV on your Raspberry Pi and Import it to Python

Follow these instructions to install OpenCV onto your Raspberry Pi using the terminal.

Important note: don't do make-j4. It may freeze so it best to just do make or make-j1.


After you have successfully installed OpenCV, you will be able to use import cv2. If you do it on the command window, you want to put in these code source ~/.profile and then workon cv.

Step 2: Enabling the Camera Module

Following these step to set up your camera.

Note: Ignoring GoPiGo installation.


In order to capture image, follow these instruction

Taking picture code


Note: sleep (measured in seconds) to create a delay between the preview and the capture by typing in time.sleep(seconds)

Step 3: Capturing an Image

After setting up the OpenCV library and the camera module, we will finally be able to capture images. First, type in import picamera at the top of the Python file. After this, typing in camera = picamera.PiCamera() will create an instance of the camera which you will be able to modify and use to take pictures. You can adjust the resolution by typing in camera.resoultion = (resolution, resolution). 1024 by 1024 resolution was the parameter we used in our project. To get a preview of the image to be taken on the computer screen, type in camera.start_preview(). Add in a sleep (measured in seconds) to create a delay between the preview and the capture by typing in time.sleep(seconds). Finally, capture the image by typing in camera.capture('name of file') and filling in the name of the file that will be saved.

Step 4: Analyze your image

Now that we are able to set up the camera and take pictures, we can use the images that are captured for new uses. One thing we can do with captured images is analyzing the pixels in the image. Pixels are stored as lists of Blue, Green, and Red color values. Before we do this, we must first allow our code to read the image we are analyzing. To read an image, we can type img = cv2.imread('name of file', cv2.IMREAD_COLOR). The image we have just read is a list of lists of Blue, Green, and Red color values respectively. We can then use the instance of the image file to access a certain pixel in the image, for example img[125, 275]. We can also use ranges of pixels by typing img[100:500] . These pixels can also have their values changed, which would be reflected in the image used. For example, we can turn a set of pixels white by typing img[100:500] = [255,255,255]. We can also use a section of the image and replace another part of the image with that given section by typing in img[100:500] = img[300:500]