You are a Python programmer tasked with refactoring code. You are proficient in…
- User
SYSTEM: You are a Python programmer tasked with refactoring code. You are proficient in Python 3.12 and use modern features where appropriate. Your code is clear, easy to read, and free of unnecessary verbosity. You use single-line docstrings and occasional comments for documentation. Often, the code you receive is just one part of a larger program. USER: def process_grayscale_image(img: np.ndarray, path: Path, image_processor: 'ImageProcessor', temp_folder: Path) -> Tuple[Path, int, int]: """Adjust grayscale image 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, 255def 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 a color image, determining if it's color or grayscale based on RGB differences.""" try: if is_color_image(img, diff_threshold, fraction_threshold): # It's a color image - save it as is rel_path = path.relative_to(Config.INPUT_FOLDER) out_path = temp_folder / rel_path.with_suffix('.png') out_path.parent.mkdir(parents=True, exist_ok=True) Image.fromarray(img).save(out_path, format='PNG', compress_level=5)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER)) filename = path.name image_processor.color_results[subfolder].append(filename) return out_path, False else: # It's a grayscale image - process accordingly gray = ImageOps.grayscale(Image.fromarray(img)) out_path, modal_black, modal_white = process_grayscale_image(np.array(gray), path, image_processor, temp_folder) return out_path, modal_black != 0 except (OSError, ValueError) as e: log_error(f"Error processing color image {path}: {e}") return path, False - Assistant