如何使用Python找到图像中的彩色圆圈

问题描述 投票:0回答:1

我想分析包含多个不同颜色的圆圈的图像,并提供图像中存在的所有彩色圆圈的计数。

以下是我正在使用的脚本和图像,但没有得到想要的结果

enter image description here 注意:我只想找到大圆圈的数量,而不是你在图片中看到的圆圈左上角的小圆圈

导入CV2 将 numpy 导入为 np

def count_colored_circles(image_path): # 加载图像 图像 = cv2.imread(图像路径) 如果图像为无: print("错误:无法加载图像。") 返回

# Convert image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply Gaussian blur to reduce noise and improve circle detection
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# Detect circles
circles = 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.")

提供图像文件的绝对路径

image_path = "D:/TBL9.PNG" # 将“your_image.jpg”替换为实际图像文件名 count_colored_circles(图像路径)

以下是带图像的结果: 每种颜色的数量: 红色:15 蓝色:10 绿色:1

enter image description here

python opencv image-processing deep-learning image-recognition
1个回答
0
投票

使用您的原始图像,我调整了 cv2.HoughCircles() 的参数,并且能够检测到所有圆圈。我发现你识别颜色的技术很有趣。其余的代码我保留与你的相同。请在下面找到代码。

minDist 是“检测到的圆的中心之间的最小距离”,因为您保留它会导致重复检测。 minRadius 和 maxRadius 是根据原始图像设置的,如果设置比实际半径大或小都会导致误检或漏检。

import cv2
import numpy as np

image = cv2.imread("circles.png")
# Convert image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply Gaussian blur to reduce noise and improve circle detection
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# Detect circles
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=2, minDist=10,
                           param1=100, param2=50, minRadius=8, maxRadius=15)

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.imwrite('detected_circles.jpg',image)
    cv2.imshow('Detected Circles', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
else:
    print("No circles detected.")

输出

red: 28
blue: 30
green: 6

© www.soinside.com 2019 - 2024. All rights reserved.