Skip to content

Instantly share code, notes, and snippets.

@maggiben
Last active July 30, 2024 21:57
Show Gist options
  • Save maggiben/007ee03594ed6999d07c0b1c11fcf1cf to your computer and use it in GitHub Desktop.
Save maggiben/007ee03594ed6999d07c0b1c11fcf1cf to your computer and use it in GitHub Desktop.
remove dark images systemd daemon

Dark image remover daemon

Intended to be used to clean timelapse pictures

Requirements

  1. Python 3
  2. OpenCV library (cv2)
  3. NumPy library (numpy)

Install python virtual env sudo apt install python3-venv

Setup Commands

You must first install motion using your package manager of choice, for debian sudo apt-get install motion make sure motion has the right permissions for the /var/log/motion & /var/log/motion/motion.log.

Edit /etc/motion/motion.conf and choose where to store the saved pictures, snapshots and movies with the target_dir variable, the default is /var/lib/motion.

  1. sudo mkdir /snapshots
  2. chown motion:adm /snapshots
  3. cd /snapshots
  4. python3 -m venv srvenv (create virtual environment)
  5. source srvenv/bin/activate (activate virtual environment)
  6. pip install opencv-python-headless numpy && pip list (Install dependencies)
  7. deactivate (deactivate virtual environment)

Source code for /snapshots/delete_dark_images.py

import cv2
import numpy as np
import os
import glob
import time
import argparse

def is_image_dark(image_path, darkness_threshold):
    """Check if the image is dark based on the darkness threshold."""
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    if image is None:
        return False
    mean_brightness = np.mean(image)
    return mean_brightness < darkness_threshold

def delete_dark_images(image_directory, darkness_threshold):
    """Delete dark images in the specified directory."""
    # Get the list of image files sorted by creation time
    image_files = sorted(glob.glob(os.path.join(image_directory, '*.jpg')), key=os.path.getctime)
    
    for image_file in image_files:
        print(f"checking image: {image_file}")
        if is_image_dark(image_file, darkness_threshold):
            os.remove(image_file)
            print(f"Deleted dark image: {image_file}")

def main():
    parser = argparse.ArgumentParser(description='Delete dark images from a directory.')
    parser.add_argument('-f', '--image_directory', type=str, default='/path/to/motion/images',
                        help='Directory where motion saves images')
    parser.add_argument('-t', '--darkness_threshold', type=int, default=50,
                        help='Threshold for darkness (0-255)')
    parser.add_argument('-s', '--sleep_time', type=int, default=60,
                        help='Time to sleep between checks in seconds')
    
    args = parser.parse_args()

    while True:
        delete_dark_images(args.image_directory, args.darkness_threshold)
        time.sleep(args.sleep_time)

if __name__ == '__main__':
    main()

Create Systemd service file

Create new service file: sudo nano /etc/systemd/system/delete-dark-images.service

[Unit]
Description=Delete Dark Images Service
After=network.target

[Service]
Type=simple
User=motion
Environment="PATH=/snapshots/srvenv/bin:$PATH"
WorkingDirectory=/snapshots
ExecStart=/snapshots/srvenv/bin/python /snapshots/delete_dark_images.py -f /snapshots -t 40 -s 120
Restart=always

[Install]
WantedBy=multi-user.target

Service options:

  1. -f or --image_directory: The directory where motion saves images.
  2. -t or --darkness_threshold: The threshold for darkness (0-255).
  3. -s or --sleep_time: The time to sleep between checks in seconds.

Starting/Stopping the service

  1. Start: sudo systemctl start delete-dark-images
  2. Stop: sudo systemctl stop delete-dark-images
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment