Your script is well-structured for processing images in a directory to remove small connected components. Let's briefly discuss the main parts to ensure it's clear:
Functionality Understanding:
The script loads each image in grayscale and ensures it is a binary image.
Connected components in the image are identified, and their areas are computed.
The script retains only those components with an area greater than the average area of all components.
Processed images are saved to a specified output directory.
Key Functions:
remove_small_components: This processes a single image and writes the filtered image.
process_image: This is a wrapper that calls remove_small_components and handles exceptions.
remove_small_components_in_directory: This manages directory-level operations, splits files into batches, and uses multiprocessing to speed up the processing.
Multiprocessing and TQDM:
Pool from multiprocessing is used to parallelize the image processing, leveraging all available cores.
tqdm provides a progress bar to track the processing status of each batch, which is useful for monitoring long-running tasks.
Usage:
Directories for input (input_directory) and output (output_directory) are set, and images are processed in batches with configurable size and process count.
Potential Enhancements:
Check if the script correctly processes images to binary form: Ensure that the threshold method produces a binary output as required (0 or 255).
Consider logging messages instead of print statements for error handling if this script will be used in production environments.
Verify permissions: Ensure that your script has the necessary read and write permissions for the specified directories.
Extend file handling to include other file formats if needed.
If you have large images or a huge number of images, the mentioned script design already addresses this efficiency by utilizing batches and parallel processing. If you encounter memory issues or need further optimizations, consider processing smaller batches or optimizing memory usage further.
To incorporate the functionality of skipping image processing if the processed file already exists in the output directory, you can modify the remove_small_components_in_directory function. This will ensure the script checks for the existence of each output file before proceeding with processing. Here's how you can do it:
python
def remove_small_components_in_directory(input_dir, output_dir, batch_size=2000, num_processes=16):
# 确保输出目录存在
os.makedirs(output_dir, exist_ok=True)
# 获取目录中的所有图像文件
image_files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))
and f.lower().endswith(('_opened.png'))]
# 按 batch_size 分组处理
num_batches = (len(image_files) + batch_size - 1) // batch_size
for batch_num in range(num_batches):
start_idx = batch_num * batch_size
end_idx = min(start_idx + batch_size, len(image_files))
batch_files = image_files[start_idx:end_idx]
print(f"Processing batch {batch_num+1}/{num_batches}: files {start_idx+1} to {end_idx}")
# 准备参数列表给每个进程,并且跳过已存在的输出文件
args = []
for filename in batch_files:
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
if not os.path.exists(output_path):
args.append((input_path, output_path))
else:
print(f"Skipping {filename}, output already exists.")
# 使用多进程处理图像
if args: # 仅当有需要处理的文件时才执行多进程
with Pool(processes=num_processes) as pool:
list(tqdm(pool.imap(process_image, args), total=len(args), desc=f"Batch {batch_num+1}/{num_batches}", leave=False))
# 使用示例
input_directory = '/home/notebook/data/group/Ruby/depthrefine/mask_results'
output_directory = '/home/notebook/data/group/Ruby/depthrefine/mask_select'
remove_small_components_in_directory(input_directory, output_directory, batch_size=2000, num_processes=16)
User
import os
import cv2
import numpy as np
from multiprocessing import Pool
from tqdm import tqdm
def compute_connected_component_area(image_path):
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
raise ValueError(f"Cannot read image: {image_path}")
def process_images_in_directory(input_dir, num_processes=16):
# 获取目录中所有图像文件的路径
image_files = [os.path.join(input_dir, f) for f in os.listdir(input_dir)
if os.path.isfile(os.path.join(input_dir, f)) and
f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff'))]
code
# 使用多进程处理图像以计算连通域总面积
with Pool(processes=num_processes) as pool:
results = list(tqdm(pool.imap(compute_connected_component_area, image_files),
total=len(image_files), desc="Processing Images"))
# 根据连通域总面积对结果进行排序(降序)
results.sort(key=lambda x: x[1], reverse=True)
# 计算需要保留的图像数量 (60%)
cutoff_index = int(len(results) * 0.6)
images_to_keep = results[:cutoff_index]
# 删除剩余的40%的图像
images_to_delete = results[cutoff_index:]
for image_path, area in images_to_delete:
os.remove(image_path)
return images_to_keep
def save_results_to_txt(results, output_txt_path):
with open(output_txt_path, 'w') as f:
for image_path, area in results:
f.write(f"{image_path},{area}\n")
print(f"Results saved to {output_txt_path}")
if name == "main":
input_directory = './mask_select'
results_txt_path = './usefulmask.txt'
Your script processes a directory of images, computes the total area of connected components for each image, and retains a sorted list of the top 60% of images based on this area. It then deletes the remaining images and saves the paths and component areas of the retained images to a text file. Here's a brief breakdown of what each part of your script does:
Key Functions and Logic
compute_connected_component_area:
Loads an image in grayscale.
Converts the image to a binary format.
Identifies connected components and calculates their areas.
Returns the total area (ignoring the background) of the connected components for the given image.
process_images_in_directory:
Gathers all image files from the specified directory with supported formats.
Uses multiprocessing to efficiently process images concurrently for calculating connected component areas.
Sorts the images by the total area of connected components in descending order.
Identifies the top 60% of images to keep and deletes the remaining 40%.
Returns a list of the retained images with their areas.
save_results_to_txt:
Writes the retained image paths and their computed areas to a text file in a specified format.
Prints a confirmation message.
Main Execution:
Defines the input directory and output path for the results.
Calls process_images_in_directory to process and filter images.
Calls save_results_to_txt to save the results.
Potential Enhancements
Error Handling: Extend error handling to manage potential issues with file read/write operations. This might include adding try-except blocks around critical parts like file deletion or writing to a text file.
Configurable Parameters: Allow the percentage of images to keep to be configurable, for more flexibility in different scenarios.
Logging: Replace print statements with a logging framework for better control over logging levels and outputs, especially important if the script is used in larger applications.
Input Validation: Ensure input directory paths and file formats are validated to avoid runtime errors.
Overall, your script is efficient for processing large batches of images due to the use of parallelism, and the structure is clear and modular, which facilitates maintenance and potential future modifications.
Before adding each file to the list of processing arguments, check if its corresponding output file already exists using os.path.exists.
Conditional Processing:
Only add files to the args list for processing if their output does not already exist.
Log a message indicating that the file is skipped if its output already exists.
Processing Control:
Execute the multiprocessing Pool only if there are files in args. This avoids unnecessary processing steps.
By implementing these changes, the script efficiently skips the processing of files with existing outputs, saving time and resources especially when dealing with large datasets.