|
| 1 | +import numpy as np |
| 2 | +from PIL import Image |
| 3 | + |
| 4 | +""" |
| 5 | +Otsu thresholding algorithm for image processing |
| 6 | +https://en.wikipedia.org/wiki/Otsu%27s_method |
| 7 | +""" |
| 8 | + |
| 9 | + |
| 10 | +def otsu_threshold(image: Image) -> Image: |
| 11 | + """ |
| 12 | + Applies Otsu's thresholding method to a grayscale image. |
| 13 | +
|
| 14 | + Parameters: |
| 15 | + image (PIL.Image.Image): A grayscale PIL image object. |
| 16 | +
|
| 17 | + Returns: |
| 18 | + PIL.Image.Image: A binary image after applying Otsu's thresholding. |
| 19 | +
|
| 20 | + Example: |
| 21 | + >>> from PIL import Image |
| 22 | + >>> import numpy as np |
| 23 | + >>> image_array = np.array( |
| 24 | + ... [[0, 0, 0, 0], [255, 255, 255, 255], [0, 0, 0, 0], [255, 255, 255, 255]], |
| 25 | + ... dtype=np.uint8 |
| 26 | + ... ) |
| 27 | + >>> image = Image.fromarray(image_array) |
| 28 | + >>> binary_image = otsu_threshold(image) |
| 29 | + >>> np.array(binary_image) |
| 30 | + array([[ 0, 0, 0, 0], |
| 31 | + [255, 255, 255, 255], |
| 32 | + [ 0, 0, 0, 0], |
| 33 | + [255, 255, 255, 255]], dtype=uint8) |
| 34 | + """ |
| 35 | + # Convert the image to numpy array |
| 36 | + pixel_array = np.array(image) |
| 37 | + |
| 38 | + # Compute histogram |
| 39 | + hist, _ = np.histogram(pixel_array, bins=256, range=(0, 256)) |
| 40 | + |
| 41 | + # Compute between class variance |
| 42 | + total_pixels = pixel_array.size |
| 43 | + current_max, threshold = 0.0, 0 # Ensure current_max is a float |
| 44 | + sum_total, sum_foreground = 0.0, 0.0 # Ensure these are floats |
| 45 | + weight_background, weight_foreground = 0.0, 0.0 # Ensure these are floats |
| 46 | + |
| 47 | + for i in range(256): |
| 48 | + sum_total += i * hist[i] |
| 49 | + |
| 50 | + for i in range(256): |
| 51 | + weight_background += hist[i] |
| 52 | + if weight_background == 0: |
| 53 | + continue |
| 54 | + weight_foreground = total_pixels - weight_background |
| 55 | + if weight_foreground == 0: |
| 56 | + break |
| 57 | + sum_foreground += i * hist[i] |
| 58 | + |
| 59 | + mean_background = sum_foreground / weight_background |
| 60 | + mean_foreground = (sum_total - sum_foreground) / weight_foreground |
| 61 | + |
| 62 | + between_class_variance = ( |
| 63 | + weight_background |
| 64 | + * weight_foreground |
| 65 | + * (mean_background - mean_foreground) ** 2 |
| 66 | + ) |
| 67 | + |
| 68 | + if between_class_variance > current_max: |
| 69 | + current_max = between_class_variance |
| 70 | + threshold = i |
| 71 | + |
| 72 | + # Apply threshold to the image |
| 73 | + binary_image = pixel_array > threshold |
| 74 | + binary_image = binary_image.astype(np.uint8) * 255 |
| 75 | + |
| 76 | + # Convert numpy array back to PIL image |
| 77 | + return Image.fromarray(binary_image) |
0 commit comments