Zoom

PHOTO EMBED

Sat Feb 08 2025 14:03:42 GMT+0000 (Coordinated Universal Time)

Saved by @mateusz021202

def process_masks(input_directory):
    """
    Processes all masks in a directory to calculate the percentage of masks 
    with a bounding box to total image area ratio >= 20%, considering only masks
    that have at least 5 unique structures (values > 0).
    
    :param input_directory: Path to the directory containing PNG mask files.
    :return: Percentage of masks passing the filter and total processed count.
    """
    total_valid_masks = 0  # Total masks with at least 5 structures
    passed_masks = 0       # Masks passing the area ratio filter

    for filename in os.listdir(input_directory):
        if filename.endswith(".png"):
            filepath = os.path.join(input_directory, filename)

            # Open the image and convert it to numpy array
            mask = Image.open(filepath)
            mask_array = np.array(mask)

            # Get unique structure IDs excluding the background (0)
            unique_structures = set(mask_array.flatten()) - {0}

            # Check if the mask has at least 5 structures
            if len(unique_structures) >= 5:
                total_valid_masks += 1

                # Find all non-background pixels (non-zero)
                structure_pixels = np.argwhere(mask_array > 0)

                if structure_pixels.size > 0:
                    # Calculate the bounding box for all structures
                    y_min, x_min = structure_pixels.min(axis=0)
                    y_max, x_max = structure_pixels.max(axis=0)

                    # Compute the area of the bounding box
                    bounding_box_area = (x_max - x_min + 1) * (y_max - y_min + 1)

                    # Compute the total area of the image
                    total_area = mask_array.shape[0] * mask_array.shape[1]

                    # Calculate the ratio in percentage
                    ratio = (bounding_box_area / total_area) * 100

                    # Check if the mask passes the filter
                    if ratio >= 17:
                        passed_masks += 1

    # Calculate the percentage of masks passing the filter
    passed_percentage = (passed_masks / total_valid_masks) * 100 if total_valid_masks > 0 else 0

    return passed_percentage, total_valid_masks

# Example usage
input_directory = "./app/mask_prediction"  # Replace with the path to your masks directory
passed_percentage, total_valid_masks = process_masks(input_directory)

print(f"Total masks with at least 5 structures: {total_valid_masks}")
print(f"Percentage of masks passing the filter: {passed_percentage:.2f}%")
content_copyCOPY