DEV Community

Cover image for Building a Simple Spy Camera with Python
Scofield Idehen
Scofield Idehen

Posted on • Originally published at blog.learnhub.africa

Building a Simple Spy Camera with Python

A spy camera lets you secretly record videos or take images without noticing. Python is a great language for building such an application thanks to its extensive libraries for computer vision and graphical interface development.

This comprehensive guide will teach you how to build a simple spy cam using Python and OpenCV.

Building a Mad Libs Word Game in Python

Are you a beginner in python, learn how to Build a Mad Libs Word Game in Python

First, create a folder.

mkdir python_spy_cam
Enter fullscreen mode Exit fullscreen mode

Next, we would cd into the python_spy_cam directory and create a virtual environment python -m venv myenv to avoid having issues with dependencies.

Activate the Virtual environment source myenv/bin/activate, and then we can install dependencies.

Run pip install opencv-python to install the OpenCV library and run the pip install Pillow to install the PIL library.

Importing the Required Libraries

Start by importing the libraries we need:

    import cv2
    import tkinter as tk
    from PIL import Image, ImageTk
    import datetime
    import os

Enter fullscreen mode Exit fullscreen mode
  • cv2 - OpenCV library for computer vision
  • tkinter - For building GUI
  • PIL - For image processing
  • datetime - For generating timestamps
  • os - For handling files and directories ## Creating the Output Directory

We need a directory to store the photos and videos captured by our spy cam.

    output_dir = os.path.join(os.path.expanduser("~"), "spycam_output")
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
Enter fullscreen mode Exit fullscreen mode

This will create the directory if it doesn't already exist.

Initializing the Camera

Let's initialize the camera using OpenCV:

    cap = cv2.VideoCapture(0)
Enter fullscreen mode Exit fullscreen mode

We pass 0 to access the default webcam.

Python Loops: A Comprehensive Guide for Beginners

Loops are quite hard to grasp, but find an easy way to learn Python Loops: A Comprehensive Guide for Beginners

Building the GUI

We will use tkinter to build a simple GUI for our spy cam app.
First, create the main window:

    root = tk.Tk() 
    root.title("My Spy Cam")
Enter fullscreen mode Exit fullscreen mode

Then add buttons to take photo, record video, and quit the app:


    btn_photo = tk.Button(root, text="Take Photo") 
    btn_video = tk.Button(root, text="Record Video")
    btn_quit = tk.Button(root, text="Quit")

    btn_photo.pack()
    btn_video.pack() 
    btn_quit.pack()
Enter fullscreen mode Exit fullscreen mode

We use .pack() to organize the widgets.

Capturing Photos

When the user clicks the Take Photo button, we will capture a frame from the camera and save it as an image file.

    def take_photo():

        print("Taking photo...")
        ret, frame = cap.read()

        if ret:

            timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")  
            filename = f"spycam_photo_{timestamp}.jpg"

            output_file = os.path.join(output_dir, filename)
            print(f"Saving photo to {output_file}")

            cv2.imwrite(output_file, frame)
Enter fullscreen mode Exit fullscreen mode

We generate a filename with a timestamp and save the image.

Recording Video

We need to create a VideoWriter object to record a video.

    output_path = ""
    output_video = None

    def start_recording():
        global output_path, output_video
        now = datetime.datetime.now()
        filename = now.strftime("%Y-%m-%d_%H-%M-%S") + ".avi"    
        output_path = os.path.join(output_dir, filename)

        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        output_video = cv2.VideoWriter(output_path, fourcc, 20.0, (640,480))

    def stop_recording():
        output_video.release()
Enter fullscreen mode Exit fullscreen mode

We can call these functions when the user clicks the Record Video button to start/stop recording.

In the main loop, check if we are recording and write frames to video file:


    btn_take_photo.config(command=take_photo)
    btn_record_video.config(command=start_recording)
Enter fullscreen mode Exit fullscreen mode

Running the Spy Camera

Finally, we call root.mainloop() to start the GUI event loop and show the live camera feed.
Here is the complete code:

    import tkinter as tk
    import cv2
    from PIL import Image, ImageTk  
    import datetime
    import os
    # Get home directory and create output dir
    output_dir = os.path.join(os.path.expanduser("~"), "spycam_output")
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    print(f"Saving photos and videos to: {output_dir}")  
    # Initialize Camera 
    cap = cv2.VideoCapture(0)
    # GUI Window 
    root = tk.Tk()
    root.title("My Spy Camera")
    # Buttons
    btn_take_photo = tk.Button(root, text="Take Photo") 
    btn_record_video = tk.Button(root, text="Record Video")
    btn_quit = tk.Button(root, text="Quit")
    btn_take_photo.pack()
    btn_record_video.pack()  
    btn_quit.pack()
    # Variables
    output_video_path = ""  
    output_video_writer = None
    # Functions  
    def take_photo():

        print("Taking photo...")
        ret, frame = cap.read()

        if ret:

            timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")  
            filename = f"spycam_photo_{timestamp}.jpg"

            output_file = os.path.join(output_dir, filename)
            print(f"Saving photo to {output_file}")

            cv2.imwrite(output_file, frame)
    # Video Recording Functions  

    output_path = ""
    output_video = None
    def start_recording():
        global output_path, output_video
        now = datetime.datetime.now()
        filename = now.strftime("%Y-%m-%d_%H-%M-%S") + ".avi"    
        output_path = os.path.join(output_dir, filename)
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        output_video = cv2.VideoWriter(output_path, fourcc, 20.0, (640,480))
    def stop_recording():
        output_video.release()

    # Bind Buttons
    btn_take_photo.config(command=take_photo)
    btn_record_video.config(command=start_recording)
    root.mainloop()
Enter fullscreen mode Exit fullscreen mode

And that's it! We have built a simple spy camera app in Python that can secretly capture photos and videos.

Some ways you can extend this project further:

  • Add the option to select different cameras
  • Build a motion detection system to start recording when movement is detected
  • Add timestamp overlay on captured media
  • Implement email/FTP upload option
  • Package it as a Linux application that launches on system startup

I hope you enjoyed this step-by-step guide for building a spy camera in Python! Let me know if you have any other questions.

If you like my work and want to help me continue dropping content like this, buy me a cup of coffee.

If you find this post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.

Resource

Top comments (6)

Collapse
 
luxandcloud profile image
Luxand.cloud

You can also add the facial recognition technology to this project. Here is a guide How to Build Facial Recognition Application with Python

Collapse
 
scofieldidehen profile image
Scofield Idehen

sweet, i would go through this, thanks a lot.

Collapse
 
shawn2208 profile image
Shawn2208

And this is why i dont have a webcam haha, Cool project though

Collapse
 
scofieldidehen profile image
Scofield Idehen

Don't be scared of one, you can deactivate it only use it when necessary

Collapse
 
devdoesit17 profile image
Devontae Reid

This is a great project! Iā€™m going to have to implement this into one of my projects.

Collapse
 
scofieldidehen profile image
Scofield Idehen

Cool, I think I would update it and implement hidden factors to avoid detection.

Let me know when you do.