Python OpenCV - 过滤掉不在附近的等高线。

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

我试图让我的程序只显示道路中心,过滤掉其他的部分。我首先找到道路中心的每个矩形的宽度和长度,然后过滤掉其他的部分。

问题:一些不在道路中心的矩形仍然可见,因为它们在道路中心的其他矩形的宽度和长度范围内。

我的想法:对每一个显示的矩形运行一个for-loop,它将:用一个小半径的矩形一端,看是否有另一个矩形在该半径内,如果有,就显示该矩形,->如果没有:用相同半径的矩形另一端,看是否有另一个矩形在该半径内,如果有,就显示该矩形,->如果这两种说法都是假的:不显示该矩形,它已经被用来寻找附近的另一个矩形。

我的想法是过滤掉所有其他已经找到的不在道路中心的矩形,因为在道路中心的每个矩形都是相互接近的(附近至少有一个矩形)。基本上每个不在道路中心的矩形与另一个矩形有更大的距离,这就是为什么我认为我可以在这里使用半径或距离,但这只是我的想法。我希望这段代码不仅适用于这条路,而且适用于其他图像看起来相同的道路。

原图。这是原图左边有长方形的图片。这是左边有长方形的图片。

EDIT!: 有人告诉我可以用scipy.spatial.KDTree来寻找邻居。

这是我的代码。

import cv2
import numpy as np

# Read image

image = cv2.imread('Resources/StreckeUni.png')

# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# show image
cv2.imshow('Gray', gray)
cv2.waitKey(0)

# Adjust Contrass and brightness
alpha = 50  # Kontrast (0-100)
beta = 0  # Helligkeit (0-100)
adjusted = cv2.convertScaleAbs(gray, alpha=alpha, beta=beta)

# Bild anzeigen
cv2.imshow('Contrast', adjusted)
cv2.waitKey(0)

#  find Canny Edges
edged = cv2.Canny(adjusted, 30, 200)

# Use Blur
blur = cv2.GaussianBlur(edged, (3, 3), 0)

# find Conturs
contours, hierarchy = cv2.findContours(blur, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# show img
cv2.imshow('Canny Edges', blur)
cv2.waitKey(0)

# show number of contours
print("Anzahl der Konturen = " + str(len(contours)))

# draw rectangles
for cnt in contours:
    rect = cv2.minAreaRect(cnt)
    box = cv2.boxPoints(rect)
    box = np.int0(box)

    if rect[1][0] > rect[1][1]:
        laenge = rect[1][0]
        breite = rect[1][1]
    else:
        laenge = rect[1][1]
        breite = rect[1][0]

    if 13.9 < laenge < 25.1 and 3.2 < breite < 7.7:
        cv2.drawContours(image, [box], -1, (0, 255, 0), 1)

# show final pic
cv2.imshow('Rectangles', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

python opencv pycharm radius
1个回答
0
投票

我以评论的形式发帖,因为我不知道该怎么做,我找到了这段代码,觉得它应该能用在我的程序上。

    def get_laser_points(image):
        """
        Return centers of laser-points found in the given image as list of coordinate-tuples.
        """
        # get the contour areas for the steppers
        mask = cv2.inRange(image, whiteLower, whiteUpper)
        contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        # compute the center of the contour areas
        centroids = []
        for contour in contours:
            m = cv2.moments(contour)
            # avoid division by zero error!
            if m['m00'] != 0:
                cx = int(m['m10'] / m['m00'])
                cy = int(m['m01'] / m['m00'])
                centroids.append((cx, cy))
                # following line manages sorting the found contours from left to right, sorting
                # first tuple value (x coordinate) ascending
                centroids = sorted(centroids)
        return centroids

现在我有了每个轮廓的中心,我该怎么做?

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