Building a Simple Spy Camera with Python
Tags: python, cybersecurity, security, hacking
Published: 2024-02-26 15:13:18


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](https://blog.learnhub.africa/wp-content/uploads/2024/02/Building-a-Mad-Libs-Word-Game-in-Python-1024x535.png)


Are you a beginner in python, learn how to [Build a Mad Libs Word Game in Python](https://blog.learnhub.africa/2024/02/16/building-a-mad-libs-word-game-in-python/)

First, create a folder. 


    mkdir python_spy_cam

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:

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

```
- `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.

```python
    output_dir = os.path.join(os.path.expanduser("~"), "spycam_output")
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
```
This will create the directory if it doesn't already exist.

## Initializing the Camera

Let's initialize the camera using OpenCV:
```python
    cap = cv2.VideoCapture(0)
```
We pass 0 to access the default webcam.


![Python Loops: A Comprehensive Guide for Beginners](https://blog.learnhub.africa/wp-content/uploads/2024/02/Python-Loops-A-Comprehensive-Guide-for-Beginners-1024x535.png)


Loops are quite hard to grasp, but find an easy way to learn [Python Loops: A Comprehensive Guide for Beginners](https://blog.learnhub.africa/2024/02/15/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:

```python
    root = tk.Tk() 
    root.title("My Spy Cam")
```
Then add buttons to take photo, record video, and quit the app:
```python

    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()
```
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.

```python
    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)
```
We generate a filename with a timestamp and save the image.

## Recording Video

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

```python
    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()
```
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:
```python

    btn_take_photo.config(command=take_photo)
    btn_record_video.config(command=start_recording)
```
## 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:

```python
    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()
```
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](https://www.buymeacoffee.com/scofields1s).

If you find this post exciting, find more exciting posts on [Learnhub Blog](https://blog.learnhub.africa/); we write everything tech from [Cloud computing](https://blog.learnhub.africa/category/cloud-computing/) to [Frontend Dev](https://blog.learnhub.africa/category/frontend/), [Cybersecurity](https://blog.learnhub.africa/category/security/), [AI](https://blog.learnhub.africa/category/data-science/), and [Blockchain](https://blog.learnhub.africa/category/blockchain/).

## **Resource**
- [Getting started with Folium](https://realpython.com/lessons/python-folium-get-started/)
- [20 Essential Python Extensions for Visual Studio Code](https://blog.learnhub.africa/2023/05/26/20-essential-python-extensions-for-visual-studio-code/)
- [Using Python for Web Scraping and Data Extraction](https://blog.learnhub.africa/2023/04/27/using-python-for-web-scraping-and-data-extraction/)
- [Getting Started with Python](https://www.python.org/about/gettingstarted/)
- [Creating Interactive Maps with Folium and Python](https://blog.learnhub.africa/2023/10/04/creating-interactive-maps-with-folium-and-python/)