opencv 如何检测真实的图像上的椭圆

9rnv2umw  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(133)

我正在尝试识别足球场的中场椭圆。我尝试了在网上找到的不同解决方案,如霍夫变换和模板匹配,但不幸的是,我无法使它们工作。图像取自真实的足球比赛,所以有不同的相机镜头和方向。
目前,我获得了最好的结果,过滤掉了音高之外的像素(使用颜色遮罩),并使用了一些转换,如高斯模糊,Canny,以及边缘轮廓,以及来自openCV的fitEllipse()等技术。
蒙版后的起始图像:

Canny图像:

在这里,我执行了边缘轮廓,并使用aspect_ratio过滤掉不相关的边缘:

contours, _ = cv2.findContours(canny_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

min_aspect_ratio = 3  # Minimum aspect ratio threshold (adjust as needed)
max_aspect_ratio = 50  # Maximum aspect ratio threshold (adjust as needed)

# Create a copy of the original image to draw bounding rectangles
image_with_rectangles = image.copy()

# Iterate through the contours
for contour in contours:
    # Calculate the aspect ratio of the bounding rectangle
    x, y, w, h = cv2.boundingRect(contour)
    aspect_ratio = float(w) / h

    # Check if the aspect ratio falls within the specified range
    if min_aspect_ratio < aspect_ratio < max_aspect_ratio:
        # Draw a green bounding rectangle around the contour
        cv2.rectangle(image_with_rectangles, (x, y), (x + w, y + h), (255, 255, 0), 2)

# Display the image with the bounding rectangles
print("Image with Bounding Rectangles")
cv2_imshow(image_with_rectangles)

filtered_contours = [
    cnt for cnt in contours
    if min_aspect_ratio < (float(cv2.boundingRect(cnt)[2]) / cv2.boundingRect(cnt)[3]) < max_aspect_ratio
]

result_image = np.zeros_like(original_image)  # Create a blank canvas

cv2.drawContours(result_image, filtered_contours, -1, (0, 255, 0), 2)  # Draw the filtered contours in green

# Display or save the result_image as needed
cv2_imshow(result_image)

带边框的图像:

图像轮廓:

最后一步包括尝试拟合椭圆,我遇到了很多问题,使cv2.fitEllipse()工作,这里我的解决方案:

gray_image = cv2.cvtColor(result_image, cv2.COLOR_BGR2GRAY)
cv2_imshow(gray_image)

# find the contours
contours,hierarchy = cv2.findContours(gray_image, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
print("\nNumber of contours detected:", len(contours))

ellipse_image = original_image.copy()
ellipses = []
orientations = []

for c in filtered_contours:

  #if it contains at least 5 points (higher the value lower the number of ellipses)
  if len(c) >= 10:
    print(len(c))

    ellipse = cv2.fitEllipse(c)

    # Get the major and minor axes of the ellipse
    major_axis, minor_axis = ellipse[1]
    # Calculate the aspect ratio of the ellipse
    aspect_ratio = major_axis / minor_axis
    #we want a high aspect ratio, meaning that is much wider then taller
    if 0.1 <= aspect_ratio <= 0.2:
      print("\nRatio: ", aspect_ratio)
      print("M and m axes: ", major_axis, minor_axis)

      if major_axis < minor_axis:
        ellipses.append(ellipse)
        orientations.append(int(ellipse[2]))

for e in ellipses:
   cv2.ellipse(ellipse_image, e, (255, 255, 0), 2)

print("\nMiddlefield contour:")
cv2_imshow(ellipse_image)

最终结果:

如何保持只有一个椭圆(正确的一个)?

VITOR发布后编辑

为了在输入图像上检测到更多的轮廓,需要进行大量的图像预处理操作,如果你能得到一个良好的、干净的中场椭圆形状,那么他的算法就可以只检测和保留一个椭圆。结果有一些假阳性,但是对椭圆的面积、长宽比和长度施加了一些范围限制,我得到了很好的结果。
下面是一些例子。正如你所看到的,这取决于过滤后的轮廓。
好结果:

不太坏的结果:

错误结果(未检测到椭圆):

i1icjdpr

i1icjdpr1#

我所做的就是用形态学运算符关闭椭圆。然后选择最大的椭圆(面积最大)。

  • 调用库并阅读灰度图像
import cv2
import matplotlib.pyplot as plt
import numpy as np

img = cv.imread('K8hNf.png',0)
  • 形态学运算
kernel_square = cv.getStructuringElement(cv.MORPH_ELLIPSE,(50,50))
img = cv.morphologyEx(img,cv.MORPH_CLOSE,kernel_square,iterations=1)
  • 找到轮廓,并将图像从灰色改为RGB,这样我们就可以用绿色绘制椭圆。
contours, _ = cv.findContours(img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
img = cv.cvtColor(img,cv.COLOR_GRAY2RGB)
  • 下面的算法找到最大面积椭圆。它很简单。你也可以使用cv2.contourArea
largest_ellipse = None
max_area = 0

for contour in contours:
    if len(contour) >= 5:
        ellipse = cv.fitEllipse(contour)
        area = ellipse[1][0] * ellipse[1][1] * np.pi # Calculate the area of the fitted ellipse
        if area > max_area:
            max_area = area
            largest_ellipse = ellipse

if largest_ellipse is not None:
    cv.ellipse(img, largest_ellipse, (0,255,0),2)
else:
    print('No ellipses found')

plt.imshow(img,cmap='gray')

通过删除图像顶部不需要的线条,并删除球员 backbone ,您可以改善椭圆的拟合。
由于相机Angular 失真,拟合可能永远不会完美。

相关问题