Certainly! Below is a Python program that uses only numpy, pandas, and matplotlib to count the number of filled circles in an image. The circles are considered filled if more than 75% of their circumference (270 degrees) is filled.
Overview of the Approach:
-
Image Loading and Preprocessing:
- Load the image using
matplotlib.
- Convert the image to grayscale if it's colored.
- Binarize the image to separate the shapes from the background.
-
Connected Component Labeling:
- Implement a connected component labeling algorithm to identify individual shapes in the image.
-
Circle Detection and Fill Calculation:
- For each connected component, determine if it resembles a circle by analyzing its geometry (e.g., area vs. perimeter).
- Calculate the filled angle of the detected circle to ensure it meets the 75% fill criterion.
-
Counting Filled Circles:
- Increment the count for each shape that satisfies the filled circle conditions.
Limitations:
- Accuracy: Without advanced image processing libraries like OpenCV or scikit-image, the detection might not be highly accurate, especially for complex images.
- Performance: The connected component labeling implemented here is basic and may not be optimized for large images.
Code Implementation:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def load_and_preprocess_image(image_path):
# Load image
img = mpimg.imread(image_path)
# If image has alpha channel, ignore it
if img.shape[-1] == 4:
img = img[..., :3]
# Convert to grayscale
if len(img.shape) == 3:
# Using luminosity method
img_gray = 0.2989 * img[:, :, 0] + 0.5870 * img[:, :, 1] + 0.1140 * img[:, :, 2]
else:
img_gray = img.copy()
# Binarize image (assuming shapes are darker than background)
threshold = np.mean(img_gray)
binary = img_gray < threshold # True for foreground
return binary.astype(int)
def get_neighbors(x, y, shape):
neighbors = []
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
nx, ny = x + dx, y + dy
if 0 <= nx < shape[0] and 0 <= ny < shape[1]:
neighbors.append((nx, ny))
return neighbors
def connected_component_labeling(binary_image):
labeled = np.zeros_like(binary_image, dtype=int)
label = 1
equivalences = {}
for x in range(binary_image.shape[0]):
for y in range(binary_image.shape[1]):
if binary_image[x, y] == 0:
continue
# Get neighbors
neighbors = get_neighbors(x, y, binary_image.shape)
labels = [labeled[nx, ny] for nx, ny in neighbors if labeled[nx, ny] > 0]
if not labels:
labeled[x, y] = label
equivalences[label] = [label]
label += 1
else:
min_label = min(labels)
labeled[x, y] = min_label
# Record equivalence
for l in labels:
if l != min_label:
equivalences[min_label].extend(equivalences[l])
equivalences[l] = equivalences[min_label]
# Second pass to assign the smallest equivalent label
for x in range(binary_image.shape[0]):
for y in range(binary_image.shape[1]):
if labeled[x, y] > 0:
labeled[x, y] = min(equivalences[labeled[x, y]])
# Remove duplicates in equivalences
unique_labels = np.unique(labeled)
unique_labels = unique_labels[unique_labels != 0]
return labeled, unique_labels
def analyze_components(labeled_image, labels):
count = 0
for label in labels:
component = (labeled_image == label).astype(int)
coords = np.argwhere(component)
if coords.size == 0:
continue
# Calculate centroid
centroid = coords.mean(axis=0)
# Calculate distances from centroid
distances = np.sqrt((coords[:,0] - centroid[0])**2 + (coords[:,1] - centroid[1])**2)
mean_distance = distances.mean()
std_distance = distances.std()
# Check circularity: standard deviation should be small
if std_distance / mean_distance > 0.1:
continue # Not circular enough
# Calculate perimeter pixels
from collections import deque
# Find boundary pixels
boundary = np.zeros_like(component)
for x, y in coords:
neighbors = get_neighbors(x, y, component.shape)
if any(component[nx, ny] == 0 for nx, ny in neighbors):
boundary[x, y] = 1
boundary_coords = np.argwhere(boundary)
if boundary_coords.size == 0:
continue
# Calculate angles of boundary pixels relative to centroid
angles = np.arctan2(boundary_coords[:,0] - centroid[0], boundary_coords[:,1] - centroid[1])
angles = np.degrees(angles)
angles = (angles + 360) % 360
# Sort angles
angles_sorted = np.sort(angles)
# Find the largest gap between consecutive angles
angle_diffs = np.diff(angles_sorted)
max_gap = np.max(angle_diffs)
if max_gap < 90: # 360 - max_gap > 270
count += 1
return count
def count_filled_circles(image_path):
binary_image = load_and_preprocess_image(image_path)
labeled_image, labels = connected_component_labeling(binary_image)
filled_circles = analyze_components(labeled_image, labels)
return filled_circles
# Example usage:
if __name__ == "__main__":
image_path = 'path_to_your_image.png' # Replace with your image path
num_filled_circles = count_filled_circles(image_path)
print(f"Number of filled circles: {num_filled_circles}")
Explanation of the Code:
-
Loading and Preprocessing:
- The
load_and_preprocess_image function reads the image, converts it to grayscale, and binarizes it. Binarization assumes that the shapes are darker than the background.
-
Connected Component Labeling:
- The
connected_component_labeling function assigns a unique label to each connected component (shape) in the binary image.
- It uses a basic union-find approach to handle label equivalences.
-
Analyzing Components:
- The
analyze_components function processes each labeled component to determine if it's a filled circle.
- Circularity Check: It calculates the centroid and the distances of all pixels in the component from the centroid. A low standard deviation relative to the mean distance suggests circularity.
- Filled Angle Calculation: It identifies the boundary pixels and calculates their angles relative to the centroid. If there's no gap larger than 90 degrees between consecutive angles, it implies that more than 270 degrees are filled.
-
Counting Filled Circles:
- The
count_filled_circles function ties everything together and returns the count of filled circles in the image.
How to Use:
-
Prepare Your Image:
- Ensure your image is in a supported format (e.g., PNG, JPEG) and that the shapes are distinct and have a contrasting color compared to the background.
-
Update the Image Path:
- Replace
'path_to_your_image.png' with the actual path to your image.
-
Run the Script:
- Execute the script. It will print the number of filled circles detected in the image.
Notes:
- Thresholding: The binarization uses the mean intensity as the threshold. Depending on your image, you might need to adjust the thresholding method for better results.
- Connected Component Labeling: This implementation is simplistic and may not handle all edge cases, especially with touching or overlapping shapes.
- Filled Angle Calculation: This method assumes that the filled portion is continuous. If the shape has multiple gaps, it might not be accurately detected.
Feel free to enhance the code further based on the specific characteristics of your images and the requirements of your application.