Modify the code so that it determines (for black, white keep the same as before) the…
- User
Modify the code so that it determines (for black, white keep the same as before) the modal value between 0 - 40 and the modal value for 0 - 55. If the modal value for 0 - 40 is at least 2 standard derivations above the mean (mean of pixels per value calculated for image in the range 0 - 55) take this value as modal black. If it is not 2 standard derivations above the mean calculate the modal value between 0 - 55. Code: def adjust_grayscale_values(img: np.ndarray) -> tuple[np.ndarray, int, int]: """Adjust the values of a grayscale image using a LUT.""" try: # Calculate modal white value in the range [250, 255] hist_white, bins_white = np.histogram(img[img >= 250], bins=6, range=(250, 256)) modal_white = int(bins_white[np.argmax(hist_white)])
code# Calculate modal black value in the range [0, 55] hist_black, bins_black = np.histogram(img[img < 56], bins=56, range=(0, 56)) modal_black = int(bins_black[np.argmax(hist_black)]) # Create LUT for the given modal values lut = create_lut(modal_black, modal_white) # Apply LUT to the original image adjusted = lut[img] return adjusted, modal_black, modal_white except ValueError as e: log_error_message(f"Error adjusting values for image: {e}") return img, 0, 255def create_lut(modal_black: int, modal_white: int) -> np.ndarray: """Create a lookup table (LUT) for adjusting grayscale values.""" # Initialize LUT with direct conversion lut = np.arange(256, dtype=np.float64)
code# Scale the LUT based on the modal white value if it's not 255 if modal_white != 255: lut *= 255.0 / modal_white lut = np.clip(lut, 0, 255) # Adjust LUT based on the modal black value if it's not 0 if modal_black: lut -= modal_black lut = np.clip(lut, 0, 255) lut *= 255.0 / (255.0 - modal_black) gamma = 1.0 - (modal_black / 255.0) lut = np.power(lut / 255.0, gamma) * 255 # Convert LUT to uint8 for direct lookup and round values lut = np.rint(lut).astype(np.uint8) return lut - Assistant