Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 18673

How to find the colored circles in an image using using python

$
0
0

I want to analyze an image containing multiple circles of various colors and provide a count of all the colored circles present in the image.

Following is the script and image i am using but not getting desired result

enter image description hereNote: i want to find the count of big circles only not small circles on the left top of circles that you can see in the picture

import cv2import numpy as np

def count_colored_circles(image_path):# Load imageimage = cv2.imread(image_path)if image is None:print("Error: Unable to load image.")return

# Convert image to grayscalegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Apply Gaussian blur to reduce noise and improve circle detectionblurred = cv2.GaussianBlur(gray, (5, 5), 0)# Detect circlescircles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1, minDist=1,                           param1=50, param2=30, minRadius=20, maxRadius=40)if circles is not None:    circles = np.uint16(np.around(circles))    counts = {'red': 0, 'blue': 0, 'green': 0}    for circle in circles[0, :]:        # Extract region of interest (ROI) for each circle        x, y, radius = circle        roi = image[max(0, y-radius):min(y+radius, image.shape[0]), max(0, x-radius):min(x+radius, image.shape[1])]        # Calculate the average color in the ROI        avg_color = np.mean(roi, axis=(0, 1))        # Determine the color category based on the average color        if avg_color[2] > avg_color[0] and avg_color[2] > avg_color[1]:            color = 'red'        elif avg_color[0] > avg_color[1] and avg_color[0] > avg_color[2]:            color = 'blue'        else:            color = 'green'        # Increment count for the detected color        counts[color] += 1    # Print counts of each color    print("Counts of each color:")    for color, count in counts.items():        print(f"{color}: {count}")    # Visualize detected circles (optional)    for circle in circles[0, :]:        x, y, radius = circle        cv2.circle(image, (x, y), radius, (0, 255, 0), 2)    cv2.imshow('Detected Circles', image)    cv2.waitKey(0)    cv2.destroyAllWindows()else:    print("No circles detected.")

Provide the absolute path to the image file

image_path = "D:/TBL9.PNG" # Replace "your_image.jpg" with the actual image filenamecount_colored_circles(image_path)

Following is the result with image:Counts of each color:red: 15blue: 10green: 1

enter image description here


Viewing all articles
Browse latest Browse all 18673

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>