python - 检测网球场线拦截

标签 python opencv computer-vision

我正在尝试改进我的代码以查找网球场线截距,以便我可以找到球场不同象限的边界。

输入图像 This is the tennis court image I am trying to analyze

输出图像 This is the final result

我通过首先找到图像中的白色像素,然后应用 Canny 边缘检测和一些预处理(例如高斯模糊)来实现这一点。然后放大 canny edge 输出以帮助为 hough 线检测做好准备。

然后采用 hough 线输出我使用了 Bentley–Ottmann algorithm 的 python 实现由 github 用户 ideasman42 找到 hough 线截距。

这似乎工作得很好,但我正在努力调整我的系统以找到最后 4 个拦截点。如果有人可以给我建议以改进或调整此实现,甚至提供一些想法以更好地解决寻找法院边界的问题,我将不胜感激。

# import the necessary packages
import numpy as np
import argparse
import cv2
import scipy.ndimage as ndi
import  poly_point_isect as bot

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image")
args = vars(ap.parse_args())

# load the image
image = cv2.imread(args["image"])

# define the list of boundaries
boundaries = [
    ([180, 180, 100], [255, 255, 255])
]

# loop over the boundaries
for (lower, upper) in boundaries:
    # create NumPy arrays from the boundaries
    lower = np.array(lower, dtype = "uint8")
    upper = np.array(upper, dtype = "uint8")

    # find the colors within the specified boundaries and apply
    # the mask
    mask = cv2.inRange(image, lower, upper)
    output = cv2.bitwise_and(image, image, mask = mask)

    # show the images
    cv2.imshow("images", np.hstack([image, output]))
    cv2.waitKey(0)

gray = cv2.cvtColor(output,cv2.COLOR_BGR2GRAY)

kernel_size = 5
blur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size),0)

low_threshold = 10
high_threshold = 200
edges = cv2.Canny(gray, low_threshold, high_threshold)
dilated = cv2.dilate(edges, np.ones((2,2), dtype=np.uint8))

cv2.imshow('dilated.png', dilated)
cv2.waitKey(0)

rho = 1  # distance resolution in pixels of the Hough grid
theta = np.pi / 180  # angular resolution in radians of the Hough grid
threshold = 10 # minimum number of votes (intersections in Hough grid cell)
min_line_length = 40  # minimum number of pixels making up a line
max_line_gap = 5  # maximum gap in pixels between connectable line segments
line_image = np.copy(output) * 0  # creating a blank to draw lines on

# Run Hough on edge detected image
# Output "lines" is an array containing endpoints of detected line segments

lines = cv2.HoughLinesP(dilated, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)

points = []
for line in lines:
    for x1, y1, x2, y2 in line:
        points.append(((x1 + 0.0, y1 + 0.0), (x2 + 0.0, y2 + 0.0)))
        cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 5)        

cv2.imshow('houghlines.png', line_image)
cv2.waitKey(0)

lines_edges = cv2.addWeighted(output, 0.8, line_image, 1, 0)
print(lines_edges.shape)

intersections = bot.isect_segments(points)
print(intersections)

for idx, inter in enumerate(intersections):
    a, b = inter
    match = 0
    for other_inter in intersections[idx:]:
        c, d = other_inter
        if abs(c-a) < 8 and abs(d-b) < 8:
            match = 1
            if other_inter in intersections:
                intersections.remove(other_inter)
                intersections[idx] = ((c+a)/2, (d+b)/2)

    if match == 0:
        intersections.remove(inter)

for inter in intersections:
    a, b = inter
    for i in range(6):
        for j in range(6):
            lines_edges[int(b) + i, int(a) + j] = [0, 0, 255]

# Show the result
cv2.imshow('line_intersections.png', lines_edges)
cv2.imwrite('line_intersections.png', lines_edges)
cv2.waitKey(0)

最佳答案

这是我的解决方案,使用了不同的方法。我使用 Harris 角点检测器来检测角点。参数只是匆忙调整了一下,所以请随意使用它们。 Here是来自 OpenCV 的教程。

我使用 OpenCV Wrapper library对于一些更简单的 OpenCV 代码。如果您不想翻译,应该很容易翻译。

# import the necessary packages
import numpy as np
import cv2
import opencv_wrapper as cvw

# import  poly_point_isect as bot

# construct the argument parse and parse the arguments
# load the image
image = cv2.imread("tennis.jpg")

# define the list of boundaries
boundaries = [([180, 180, 100], [255, 255, 255])]

# loop over the boundaries
for (lower, upper) in boundaries:
    # create NumPy arrays from the boundaries
    lower = np.array(lower, dtype="uint8")
    upper = np.array(upper, dtype="uint8")

    # find the colors within the specified boundaries and apply
    # the mask
    mask = cv2.inRange(image, lower, upper)
    output = cv2.bitwise_and(image, image, mask=mask)

# Start my code
gray = cvw.bgr2gray(output)

corners = cv2.cornerHarris(gray, 9, 3, 0.01)
corners = cvw.normalize(corners).astype(np.uint8)

thresh = cvw.threshold_otsu(corners)
dilated = cvw.dilate(thresh, 3)

contours = cvw.find_external_contours(dilated)

for contour in contours:
    cvw.circle(image, contour.center, 3, cvw.Color.RED, -1)

cv2.imshow("Image", image)
cv2.waitKey(0)

结果:

enter image description here

披露:我是 OpenCV Wrapper 的作者。

关于python - 检测网球场线拦截,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55496402/

相关文章:

python - n 形状列表与 n 形状数组在一行中按元素相乘

c++ - 如何在opencv2中手写一个Roi函数

machine-learning - 二进制数而不是一个热向量

Java Netbeans 显示 opencv3 错误 "Error: Could not find or load main class library"

python - conda与caffe一起安装openCV 3.4.2,但不能单独删除

android - 适用于openCV应用程序的基于Android Windows的模拟器?

c++ - 使用光流进行特征跟踪

python - 如何获得 MongoDB 的 Motor 驱动程序?

python - Keras 的 ImageDataGenerator 在访问图像文件时随机抛出错误

python - Win2003 上的 Outlook 2003 中的 Django EmailMultiAlternatives 和 HTML 电子邮件显示