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: # --- Color Detection ---
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 - Assistant
Here's a refactored version of your
is_color_imagefunction incorporating modern Python features for improved clarity and conciseness:import numpy as np from typing import Any def is_color_image( img: np.ndarray, diff_threshold: int = Config.COLORDIFF_THRESHOLD, fraction_threshold: float = Config.FRACTION_COLORED_PIXELS_THRESHOLD ) -> bool: """Check if an image is color based on RGB channel differences.""" if img.ndim != 3 or img.shape[2] != 3: return False max_diff = np.ptp(img, axis=2) return np.mean(max_diff > diff_threshold) >= fraction_thresholdRefactoring Highlights:
-
Consistent Formatting:
- Parameters are aligned vertically for better readability.
-
Clear Naming:
- Variable names like
max_diffremain descriptive and concise.
- Variable names like
-
Simplified Return Statement:
-