Intermediate Level • Lesson 8

📷 Camera and Vision Basics

⏱️ 50 minutes 📚 Intermediate 🎯 Computer Vision
📷

Camera and Vision Basics

Learn how to use the Raspberry Pi Camera to take pictures and detect motion - this is the first step toward human tracking!

Raspberry Pi Camera

The Raspberry Pi Camera is a small camera module that connects directly to your Raspberry Pi. It can take photos, record videos, and with the right software, detect objects and people!

💡 Real-World Example: Security cameras use computer vision to detect people, cars, and movement. Your Raspberry Pi can do similar things!

Setting Up the Camera

Hardware Setup:

  1. Enable Camera: Run sudo raspi-config → Interface Options → Camera → Enable
  2. Connect Camera: Insert camera ribbon cable into the camera port (between Ethernet and HDMI)
  3. Secure Connection: Make sure the ribbon cable is inserted correctly (metal contacts facing away from Ethernet port)
  4. Reboot: Restart Raspberry Pi after enabling camera

Taking Pictures

The simplest thing you can do with a camera is take pictures!

Basic Photo Capture:

from picamera import PiCamera import time # Create camera object camera = PiCamera() # Optional: Set resolution camera.resolution = (640, 480) # Take a picture camera.start_preview() # Show preview time.sleep(2) # Give camera time to adjust camera.capture('image.jpg') # Save photo camera.stop_preview() print("Photo saved as image.jpg!")

Understanding the Code:

  • PiCamera(): Creates a camera object
  • start_preview(): Shows what camera sees (like a live view)
  • capture(): Takes a photo and saves it
  • stop_preview(): Closes the preview

Recording Video

You can also record videos with the camera:

Video Recording:

from picamera import PiCamera import time camera = PiCamera() camera.resolution = (640, 480) # Start recording camera.start_recording('video.h264') camera.wait_recording(10) # Record for 10 seconds camera.stop_recording() print("Video saved as video.h264!")

Motion Detection

Motion detection compares consecutive frames to see if anything has moved. This is simpler than full object detection but very useful!

Simple Motion Detection:

from picamera import PiCamera import numpy as np import time camera = PiCamera() camera.resolution = (320, 240) # Lower resolution for faster processing def detect_motion(): # Capture first frame camera.capture('frame1.jpg') time.sleep(0.1) # Capture second frame camera.capture('frame2.jpg') # Compare frames (simplified - in real project, you'd compare pixel differences) # If difference is large, motion detected! return True # Simplified - always returns True for demo try: while True: if detect_motion(): print("Motion detected!") # Take a photo when motion detected camera.capture('motion_' + str(time.time()) + '.jpg') time.sleep(1) except KeyboardInterrupt: camera.close() print("Motion detection stopped!")

Note: This is a simplified example. Real motion detection compares pixel differences between frames.

Project: Motion Detection Camera

Let's build a system that takes a photo when it detects motion!

Materials Needed:

  • Raspberry Pi
  • Raspberry Pi Camera Module
  • Optional: LED to indicate when motion is detected

Complete Motion Detection Code:

from picamera import PiCamera import RPi.GPIO as GPIO import time from datetime import datetime # Set up camera camera = PiCamera() camera.resolution = (640, 480) # Set up LED indicator (optional) GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) def take_motion_photo(): """Take a photo when motion is detected""" timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"motion_{timestamp}.jpg" # Flash LED to indicate photo taken GPIO.output(18, GPIO.HIGH) camera.capture(filename) GPIO.output(18, GPIO.LOW) print(f"Motion detected! Photo saved: {filename}") return filename try: print("Motion detection camera started!") print("Press Ctrl+C to stop") last_capture_time = 0 while True: # Simulate motion detection (in real project, compare frames) # For now, take a photo every 5 seconds as demo current_time = time.time() if current_time - last_capture_time >= 5: take_motion_photo() last_capture_time = current_time time.sleep(0.5) except KeyboardInterrupt: camera.close() GPIO.cleanup() print("Motion detection stopped!")

Understanding the Code:

  • Camera continuously monitors for motion
  • When motion detected, takes a photo with timestamp
  • LED flashes to indicate photo was taken
  • Photos are saved with unique filenames

Introduction to Computer Vision

Computer vision is when computers "see" and understand images. It's what allows cameras to detect faces, objects, and people!

👁️

Image Capture

Camera takes pictures

🔍

Image Processing

Computer analyzes the image

🎯

Object Detection

Finds faces, people, objects

💡 Next Step: In the Advanced level, you'll learn to use OpenCV (a computer vision library) to detect faces and people - this is what you'll need for the human-tracking fan project!

Common Mistakes to Avoid

⚠️ Watch Out For:

  • Camera Not Enabled: Must enable camera in raspi-config first
  • Wrong Cable Orientation: Camera ribbon must be inserted correctly
  • Missing Library: Install picamera with pip3 install picamera
  • Too High Resolution: Higher resolution = slower processing - use lower for motion detection
  • Forgetting to Close: Always call camera.close() when done

Summary

You've learned:

  • ✅ Raspberry Pi Camera can take photos and record videos
  • ✅ Camera must be enabled in raspi-config before use
  • ✅ Use PiCamera() to create camera object
  • capture() takes photos, start_recording() records video
  • ✅ Motion detection compares frames to detect movement
  • ✅ Computer vision lets computers "see" and understand images
  • ✅ Lower resolution = faster processing for motion detection
🎉 Congratulations! You've completed the Intermediate Level! You can now read sensors, display information, control motors, and use cameras. In the Advanced level, you'll combine all these skills to build the human-tracking fan!

🎮 Try It: Practice with Camera!

Practice writing code for the camera. Try these challenges:

📝 Challenge 1: Take a Photo

Write code that takes a single photo and saves it:

📝 Challenge 2: Timelapse

Write code that takes 10 photos, one every 2 seconds:

💡 Tip: Remember to enable the camera in raspi-config first! And always call camera.close() when you're done.

🎯 Activity: Motion Detection Camera

What You'll Build:

Create a motion detection system that takes photos when movement is detected!

Step-by-Step Instructions:

  1. Enable Camera: Run sudo raspi-config and enable camera interface
  2. Connect Camera: Insert camera ribbon cable into camera port
  3. Install Library: Install picamera library if needed
  4. Write Code: Create motion detection code
  5. Test: Run code and wave in front of camera
  6. Enhance: Add LED indicator when motion detected

Testing Checklist:

  • ✅ Camera takes photos successfully
  • ✅ Photos are saved with unique filenames
  • ✅ System detects motion (or simulates detection)
  • ✅ LED flashes when photo is taken
🏆 Bonus Challenge: Can you create a system that takes a photo every time a button is pressed? Combine camera with button input!

💪 Practice Challenges

Challenge 1: Photo with Timestamp

Take a photo and save it with the current date and time in the filename:

# Example filename: "photo_20241215_143022.jpg" # (year, month, day, hour, minute, second)

Challenge 2: Continuous Photos

Take 5 photos, one every 3 seconds, and print a message each time:

Challenge 3: Button-Triggered Photo

Combine camera with button - take a photo when button is pressed:

# When button pressed → take photo # Show LED indicator when photo taken

Challenge 4: Low-Resolution Motion Detection

Set camera to low resolution (160x120) for faster motion detection processing:

# Lower resolution = faster processing # Better for real-time motion detection