Refactor the code so that the color/grayscale detection is always done by the…
- User
Refactor the code so that the color/grayscale detection is always done by the is_color_image function and not by the analyze files function. Code: def is_color_image(img: np.ndarray, diff_threshold: int = Config.COLORDIFF_THRESHOLD, fraction_threshold: float = Config.FRACTION_COLORED_PIXELS_THRESHOLD) -> bool: """Determine if an image is color based on RGB channel differences.""" # Check if the image has three channels (RGB) if img.ndim != 3 or img.shape[2] != 3: return False
# Calculate the peak-to-peak (max - min) difference across the RGB channels for each pixel max_diff = np.ptp(img, axis=2) # Compute the fraction of pixels where the max difference exceeds the threshold fraction_colored = np.mean(max_diff > diff_threshold) # Determine if the image meets or exceeds the required fraction of colored pixels return fraction_colored >= fraction_threshold def analyze_file(path: Path, start_time: float, total: int) -> None: """Analyze a single image file to determine its color status based on RGB differences.""" if not is_valid_image(path): return try: img = np.array(open_and_convert_image(path)) subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER)) filename = path.name if img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1): # Grayscale image based on dimensions adjusted, modal_black, modal_white = adjust_values(img) 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)) elif is_color_image( img, diff_threshold=Config.COLORDIFF_THRESHOLD, fraction_threshold=Config.FRACTION_COLORED_PIXELS_THRESHOLD, ): # Image is determined to be color image_processor.color_results[subfolder].append(filename) else: # Image is not color; treat as grayscale adjusted, modal_black, modal_white = adjust_values(img) 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)) except (OSError, ValueError) as e: log_error(f"Error processing image {path}: {e}") finally: with shared_state.processed_files_lock: shared_state.processed_files_count += 1 update_status(start_time, shared_state.processed_files_count, total) - Assistant