python Copy code
from pathlib import Path
from typing import Tuple
import time
import shutil
import numpy as np
from PIL import Image, ImageOps
# Assuming shared_state, Config, app, and other dependencies are defined elsewhere
def process_file(
path: Path,
start_time: float,
total_files: int,
image_processor: 'ImageProcessor',
temp_folder: Path,
resize: bool = False,
auto_correct_and_resize: bool = False
) -> None:
"""Process a single image file."""
if shared_state.stop_event.is_set():
return
if not is_valid_image(path):
log_error(f"Invalid image file: {path}")
_increment_and_update(start_time, total_files)
return
try:
img = np.array(open_and_convert_image(path))
except (OSError, ValueError) as e:
log_error(f"Error reading image {path}: {e}")
_increment_and_update(start_time, total_files)
return
relative_path = path.relative_to(Config.INPUT_FOLDER)
temp_output_path = temp_folder / relative_path.with_suffix('.png')
temp_output_path.parent.mkdir(parents=True, exist_ok=True)
if auto_correct_and_resize:
temp_output_path = _auto_correct_and_resize_image(
img, path, image_processor, temp_folder, temp_output_path
)
elif resize:
temp_output_path = resize_image(path, temp_output_path)
else:
temp_output_path = _process_image(img, path, image_processor, temp_folder)
final_output_path = Config.OUTPUT_FOLDER / relative_path.with_suffix(
'.jpg' if app.RESIZE_FORMAT.get() == 'jpg' else '.png'
)
final_output_path.parent.mkdir(parents=True, exist_ok=True)
if app.RESIZE_FORMAT.get() == 'jpg':
convert_png_to_jpg(temp_output_path, final_output_path)
else:
shutil.move(str(temp_output_path), str(final_output_path))
_increment_and_update(start_time, total_files)
def process_folder(
folder: Path,
image_processor: 'ImageProcessor',
auto_correct_and_resize: bool = False
) -> None:
"""Process all images in a folder."""
image_processor.reset_results()
if auto_correct_and_resize:
try:
check_imagemagick()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = [
path for path in folder.rglob('*')
if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS
]
if not tasks:
log_error(f"No image files found in '{folder}'")
return
with create_temp_folder() as temp_folder:
run_with_thread_pool(
tasks,
process_file,
start_time=time.time(),
total_files=len(tasks),
image_processor=image_processor,
temp_folder=temp_folder,
resize=False,
auto_correct_and_resize=auto_correct_and_resize
)
def process_grayscale_image(
img: np.ndarray,
path: Path,
image_processor: 'ImageProcessor',
temp_folder: Path
) -> Tuple[Path, int, int]:
"""Adjust grayscale values and save the processed image."""
try:
adjusted, modal_black, modal_white = adjust_values(img)
relative_parent = path.parent.relative_to(Config.INPUT_FOLDER)
out_path = temp_folder / relative_parent / f"{path.stem}.png"
out_path.parent.mkdir(parents=True, exist_ok=True)
Image.fromarray(adjusted).convert('L').save(out_path, format='PNG', compress_level=5)
subfolder = relative_parent.as_posix()
filename = path.name
if modal_black:
image_processor.black_results[subfolder].append((filename, modal_black))
if modal_white != 255:
image_processor.white_results[subfolder].append((filename, modal_white))
return out_path, modal_black, modal_white
except (ValueError, OSError) as e:
log_error(f"Error processing grayscale image {path}: {e}")
return path, 0, 255
def process_color_image(
img: np.ndarray,
path: Path,
image_processor: 'ImageProcessor',
temp_folder: Path,
diff_threshold: int = Config.COLORDIFF_THRESHOLD,
fraction_threshold: float = Config.FRACTION_COLORED_PIXELS_THRESHOLD
) -> Tuple[Path, bool]:
"""Process an image to determine if it's color or grayscale and handle accordingly."""
try:
if is_color_image(img, diff_threshold, fraction_threshold):
return _save_color_image(img, path, image_processor, temp_folder)
gray_image = ImageOps.grayscale(Image.fromarray(img))
gray_array = np.array(gray_image)
out_path, modal_black, modal_white = process_grayscale_image(
gray_array, path, image_processor, temp_folder
)
return out_path, modal_black != 0
except (OSError, ValueError) as e:
log_error(f"Error processing image {path}: {e}")
return path, False
def _increment_and_update(start_time: float, total_files: int) -> None:
"""Increment the processed files count and update the status."""
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
def _auto_correct_and_resize_image(
img: np.ndarray,
path: Path,
image_processor: 'ImageProcessor',
temp_folder: Path,
temp_output_path: Path
) -> Path:
"""Handle auto-correction and resizing of the image."""
if is_color_image(img):
intermediate_path, _ = process_color_image(img, path, image_processor, temp_folder)
else:
intermediate_path, _, _ = process_grayscale_image(img, path, image_processor, temp_folder)
return resize_image(intermediate_path, temp_output_path)
def _process_image(
img: np.ndarray,
path: Path,
image_processor: 'ImageProcessor',
temp_folder: Path
) -> Path:
"""Process the image based on its color type."""
if is_color_image(img):
temp_output_path, _ = process_color_image(img, path, image_processor, temp_folder)
else:
temp_output_path, _, _ = process_grayscale_image(img, path, image_processor, temp_folder)
return temp_output_path
def _save_color_image(
img: np.ndarray,
path: Path,
image_processor: 'ImageProcessor',
temp_folder: Path
) -> Tuple[Path, bool]:
"""Save a color image as PNG and log the result."""
relative_path = path.relative_to(Config.INPUT_FOLDER).with_suffix('.png')
out_path = temp_folder / relative_path
out_path.parent.mkdir(parents=True, exist_ok=True)
Image.fromarray(img).save(out_path, format='PNG', compress_level=5)
subfolder = path.parent.relative_to(Config.INPUT_FOLDER).as_posix()
image_processor.color_results[subfolder].append(path.name)
return out_path, False