Skip to content

Instantly share code, notes, and snippets.

@sergeyprokudin
Created February 21, 2024 17:33
Show Gist options
  • Save sergeyprokudin/6f121ee4424224f0ac5efe800c8dbd57 to your computer and use it in GitHub Desktop.
Save sergeyprokudin/6f121ee4424224f0ac5efe800c8dbd57 to your computer and use it in GitHub Desktop.
Filter out blurry images based on the image Laplacian
"""
MIT License
Copyright (c) 2024 Sergey Prokudin sergey.prokudin@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This script processes a directory of images to identify and copy sharp images to a specified directory.
It uses the Laplacian operator to measure the variance (sharpness) of images and filters them based on a given threshold.
Supports command-line arguments for specifying source and target directories, and an optional sharpness threshold.
Usage:
python sharp_image_filter.py <source_directory> <target_directory> [-t --threshold <sharpness_threshold>]
- <source_directory>: The directory containing images to process.
- <target_directory>: The directory where sharp images will be stored.
- [-t --threshold <sharpness_threshold>]: Optional. The sharpness threshold for determining if an image is sharp.
Higher values increase sharpness requirement, potentially discarding more images. Default is 30.0.
Example:
python sharp_image_filter.py ./images ./sharp_images -t 25.0
"""
import cv2
import os
import argparse
import shutil
def is_sharp(image_path, threshold=30.0):
"""Check if the image is sharp based on the Laplacian variance.
Args:
image_path (str): Path to the image file.
threshold (float): Variance threshold for determining sharpness.
Returns:
bool: True if the image is considered sharp, False otherwise.
"""
print(image_path)
image = cv2.imread(image_path)
if image is None:
print(f"Warning: Unable to load {image_path}, skipping.")
return False
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
variance = cv2.Laplacian(gray, cv2.CV_64F).var()
return variance > threshold
def process_images(frames_directory, sharp_frames_directory, threshold):
"""Process images from a directory and copy sharp images to another directory.
Args:
frames_directory (str): Directory containing images to process.
sharp_frames_directory (str): Directory to store sharp images.
threshold (float): Sharpness threshold.
"""
if not os.path.exists(sharp_frames_directory):
os.makedirs(sharp_frames_directory)
supported_formats = ('.jpg', '.jpeg', '.png', '.bmp')
for frame in os.listdir(frames_directory):
if not frame.lower().endswith(supported_formats):
continue
frame_path = os.path.join(frames_directory, frame)
if is_sharp(frame_path, threshold):
sharp_frame_path = os.path.join(sharp_frames_directory, frame)
shutil.copy(frame_path, sharp_frame_path)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Process images to filter sharp ones. Use the -t (--threshold) option to set the sharpness threshold. A higher threshold means fewer images will be considered sharp, as it requires higher sharpness variance.")
parser.add_argument("source_directory", help="The directory containing images to process.")
parser.add_argument("target_directory", help="The directory where sharp images will be stored.")
parser.add_argument("-t", "--threshold", type=float, default=30.0, help="The sharpness threshold for determining if an image is sharp. Higher values increase sharpness requirement, potentially discarding more images.")
args = parser.parse_args()
process_images(args.source_directory, args.target_directory, args.threshold)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment