Raspberry Pi 4 OpenCV with Intro Code in Python



Raspberry Pi 4 OpenCV with Intro Code in Python – Part 1

Raspberry Pi enthusiasts, get ready to dive into the exciting world of computer vision! In this multi-part guide, we’ll explore how to harness the power of Raspberry Pi 4 and OpenCV to create impressive computer vision applications. Whether you’re a beginner or a seasoned Pi aficionado, this series will provide you with the knowledge and code snippets you need to get started with OpenCV on your Raspberry Pi 4.

Part 1: Introduction to Computer Vision

Before we jump into the technical details, let’s briefly introduce the concept of computer vision. Computer vision is a field of artificial intelligence (AI) that focuses on enabling machines, including the Raspberry Pi, to interpret and understand visual information from the world around them. This technology has numerous real-world applications, from object recognition to facial detection, autonomous navigation, and more.

Why Raspberry Pi 4?

The Raspberry Pi 4 is a versatile and powerful single-board computer that’s perfect for running computer vision projects. With its quad-core ARM Cortex-A72 CPU, multiple RAM options, and Hardware-accelerated graphics, the Raspberry Pi 4 is well-suited to handle the computational demands of computer vision tasks. Plus, it’s energy-efficient and cost-effective, making it an excellent choice for hobbyists and developers alike.

Raspberry pi 4

Getting Started

Before we dive into the coding part, let’s ensure you have the necessary hardware and software set up:

Hardware Requirements:

  • Raspberry Pi 4 (2GB, 4GB, or 8GB RAM model)
  • MicroSD card (16GB or larger recommended)
  • USB webcam or Raspberry Pi Camera Module
  • Power supply
  • HDMI cable and monitor (for initial setup)
Raspberry Pi 8GB

Software Requirements:

  • Raspbian OS (or Raspberry Pi OS) installed on the microSD card
  • Python 3.x
  • OpenCV library

If you haven’t set up your Raspberry Pi 4 yet, you can follow the steps outlined in our blog post “Getting Started with Raspberry Pi 4”, which provides a comprehensive guide for beginners.

Part 2: Installing OpenCV on Raspberry Pi 4

Now that we have introduced the basics let’s proceed to installing OpenCV, a crucial library for computer vision projects, on your Raspberry Pi 4.

Installation Steps:

  1. Update and Upgrade: Open a terminal on your Raspberry Pi 4 and run the following commands to ensure your system is up to date:
    sudo apt-get update
    sudo apt-get upgrade
  2. Install Dependencies: Install the required dependencies for building OpenCV: sudo apt-get install libjpeg-dev libpng-dev libtiff-dev
    sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev
    sudo apt-get install libv4l-dev libxvidcore-dev libx264-dev
    sudo apt-get install libfontconfig1-dev libcairo2-dev
    sudo apt-get install libgdk-pixbuf2.0-dev libpango1.0-dev
  3. Install OpenCV:You can install OpenCV using the following command. This might take a while, so be patient: pip install opencv-python
  4. Test the Installation:To ensure OpenCV is installed correctly, create a Python script and run the following code: import cv2
    print(cv2.version) If you see the OpenCV version printed without errors, you’re ready to move on.

Part 3: Your First OpenCV Code

With OpenCV installed, let’s write and run our first OpenCV code. In this example, we’ll load an image, convert it to grayscale, and display both the original and grayscale versions.

import cv2

# Load an image from file
image_path = 'your_image.jpg'
image = cv2.imread(image_path)

# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Display the original and grayscale images
cv2.imshow('Original Image', image)
cv2.imshow('Grayscale Image', gray_image)

# Wait for a key press and then close the windows

In the next part of our series, we’ll explore more advanced OpenCV functionalities and delve into real-world computer vision projects using Raspberry Pi 4. Stay tuned for Part 4, where we’ll take your skills to the next level!

Part 4: Advanced Image Processing with OpenCV

In this part, we’ll delve deeper into the capabilities of OpenCV and explore advanced image processing techniques. Here are some of the topics we’ll cover:

1. Image Filtering

Image filtering is a fundamental technique in computer vision. It involves applying a Kernel (a small matrix) to an image to perform operations like blurring, sharpening, edge detection, and more.

import cv2

# Load an image from file
image_path = 'your_image.jpg'
image = cv2.imread(image_path)

# Apply Gaussian blur
blurred_image = cv2.GaussianBlur(image, (5, 5), 0)

# Display the original and blurred images
cv2.imshow('Original Image', image)
cv2.imshow('Blurred Image', blurred_image)

# Wait for a key press and then close the windows

2. Edge Detection

Edge detection is crucial for object detection and recognition. The Canny edge detector is a popular choice in OpenCV.

import cv2

# Load an image from file
image_path = 'your_image.jpg'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# Apply Canny edge detection
edges = cv2.Canny(image, 100, 200)

# Display the original and edge-detected images
cv2.imshow('Original Image', image)
cv2.imshow('Edge Detection', edges)

# Wait for a key press and then close the windows

3. Object Detection

Detecting objects within an image is a complex but exciting task. OpenCV provides pre-trained models for object detection. Here’s a simple example using the Haar Cascade Classifier for face detection:

import cv2

# Load a pre-trained face detection model
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Load an image from file
image_path = 'your_image.jpg'
image = cv2.imread(image_path)

# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)

# Draw rectangles around detected faces
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y),

 (x + w, y + h), (255, 0, 0), 2)

# Display the image with detected faces
cv2.imshow('Face Detection', image)

# Wait for a key press and then close the window

4. Real-World Projects

As we progress in this series, we’ll delve into real-world computer vision projects, such as facial recognition, object tracking, and even creating your own smart security system with your Raspberry Pi 4 and OpenCV.

Part 5: Building a Raspberry Pi Smart Security System

In this final part, we’ll embark on a practical and fun computer vision project: creating your own smart security system using your Raspberry Pi 4 and OpenCV.

Project Overview

Imagine having a smart security system that can detect and notify you of any intruders or unusual activity around your home. In this project, we’ll create just that using your Raspberry Pi 4 and a USB webcam. Here are the key components of our security system:

  1. Motion Detection: We’ll use OpenCV to detect motion within the camera’s field of view.
  2. Image Capture: When motion is detected, we’ll capture images and store them for later review.
  3. Alert Notification: You’ll receive notifications (e.g., emails or text messages) when motion is detected.


Let’s break down the implementation into steps:

Step 1: Set Up Your Raspberry Pi

Ensure your Raspberry Pi 4 is set up and connected to the internet. You can refer to Part 1 for detailed instructions if needed.

Step 2: Connect the Webcam

Attach your USB webcam to one of the Raspberry Pi’s USB ports. Make sure it’s properly recognized by the system.

Step 3: Install Required Libraries

Install the necessary libraries, including OpenCV and any libraries for email or messaging notifications. You can refer to previous parts for OpenCV installation instructions.

Step 4: Write the Code

Here’s a basic outline of the code you’ll need:

import cv2
import smtplib  # For sending email notifications
from datetime import datetime

# Initialize the webcam
cap = cv2.VideoCapture(0)

# Initialize variables for motion detection
motion_detected = False
motion_start_time = None

# Loop to continuously capture frames
while True:
    ret, frame = cap.read()  # Read a frame from the webcam

    # Convert the frame to grayscale for motion detection
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray_frame = cv2.GaussianBlur(gray_frame, (21, 21), 0)

    if motion_detected:
        cv2.putText(frame, "Motion Detected", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

    # Display the frame
    cv2.imshow('Security Camera', frame)

    # Check for motion detection
    if not motion_detected:
        if motion_start_time is None:
            motion_start_time = datetime.now()
            delta_time = datetime.now() - motion_start_time
            if delta_time.total_seconds() >= 5:  # Adjust the time threshold as needed
                motion_detected = True
        # Save the image when motion is detected
        timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        image_filename = f'motion_{timestamp}.jpg'
        cv2.imwrite(image_filename, frame)
        # Send an alert notification (you can use your email service)
        sender_email = 'your_email@gmail.com'
        receiver_email = 'receiver_email@gmail.com'
        password = 'your_email_password'

        subject = 'Motion Detected!'
        message = 'Motion was detected by your smart security system.'

            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, f'Subject: {subject}\n\n{message}')
            print('Notification sent successfully!')
        except Exception as e:
            print(f'Error sending notification: {str(e)}')

        # Reset motion detection variables
        motion_detected = False
        motion_start_time = None

    if cv2.waitKey(1) & 0xFF == ord('q'):

# Release the webcam and close all windows

Step 5: Motion Detection and Notifications

Implement motion detection logic within the loop. When motion is detected, capture images and send email. You can use OpenCV to perform motion detection by comparing consecutive frames.

Step 6: Testing and Enhancements

Test your security system and make enhancements as needed. You can save captured images, implement a notification system (e.g., sending emails with detected images), and fine-tune the motion detection parameters.


Congratulations! You’ve created your own Raspberry Pi-based smart security system using OpenCV. This project is just the beginning of what you can achieve with computer vision and Raspberry Pi 4.

Feel free to explore more advanced Features, such as object recognition, Cloud integration, or integrating with smart home systems.

Thank you for joining us on this journey. We hope you’ve gained valuable insights into the world of computer vision and Raspberry Pi. For more tutorials and projects, visit CircuitMonster.

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore our other blogs.

  • 8-bit vs. 32-bit Microcontrollers in Today’s Projects

  • Nintendo Sues Creators of Popular Switch Emulator Yuzu, Citing Piracy Concerns

  • Raspberry Pi CPU Temperature Range – Everything You Need to Know

  • image of tunnel

    Reverse Tunneling with Raspberry Pi: A Comprehensive Guide