纠正粗糙的边缘

3
从某个高度(约130英尺)拍摄的另一张图像中提取出一张图像,现在当提取出这张较小的图像时,其中包含一个对象,它实际上具有非常规则和平滑的形状,但边缘非常粗糙。现在我想检测该对象具有的角数(不使用轮廓),但由于这些粗糙的边缘,检测到的角数增加了很多。
以下是样本图像: Rectangle Semi-Circle 如何使边缘变直?
1个回答

7
我认为你需要的是一个简单的边缘平滑算法。我已经为你实现了一个。它不能保存外形内的彩色标记 - 如果这一点很重要 - 因为你在问题中没有提到 - 你将不得不自己解决这部分。结果如下: enter image description here 我已经实现了轨迹条,因此您可以根据需要调整平滑值。按“c”键确认您选择的值。
import cv2
import numpy as np


def empty_function(*arg):
    pass


def SmootherEdgesTrackbar(img, win_name):
    trackbar_name = win_name + "Trackbar"

    cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)
    cv2.resizeWindow(win_name, 1000, 500)
    cv2.createTrackbar("first_blur", win_name, 3, 255, empty_function)
    cv2.createTrackbar("second_blur", win_name, 3, 255, empty_function)
    cv2.createTrackbar("threshold", win_name, 0, 255, empty_function)

    while True:
        first_blur_pos = cv2.getTrackbarPos("first_blur", win_name)
        second_blur_pos = cv2.getTrackbarPos("second_blur", win_name)
        thresh_pos = cv2.getTrackbarPos("threshold", win_name)
        if first_blur_pos < 3:
            first_blur_pos = 3
        if second_blur_pos < 3:
            second_blur_pos = 3
        img_res = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img_res = smoother_edges(img_res, (first_blur_pos * 2 + 1, first_blur_pos * 2 + 1),
                                 (second_blur_pos * 2 + 1, second_blur_pos * 2 + 1))
        _, img_res = cv2.threshold(img_res, thresh_pos, 255, 0)
        cv2.imshow(win_name, img_res)

        key = cv2.waitKey(1) & 0xFF
        if key == ord("c"):
            break

    cv2.destroyAllWindows()
    return img_res


def unsharp_mask(img, blur_size, imgWeight, gaussianWeight):
    gaussian = cv2.GaussianBlur(img, blur_size, 0)
    return cv2.addWeighted(img, imgWeight, gaussian, gaussianWeight, 0)


def smoother_edges(img, first_blur_size, second_blur_size=(5, 5),
                   imgWeight=1.5, gaussianWeight=-0.5):
    # blur the image before unsharp masking
    img = cv2.GaussianBlur(img, first_blur_size, 0)
    # perform unsharp masking
    return unsharp_mask(img, second_blur_size, imgWeight, gaussianWeight)


# read the image
img = cv2.imread("sample.jpg")
# smoothen edges
img = SmootherEdgesTrackbar(img, "Smoother Edges Trackbar")
# show and save image
cv2.imshow("img", img)
cv2.imwrite("result.png", img)
cv2.waitKey(0)

编辑: 当您确定适合您的值后,只需删除滑块功能,并使用固定值执行步骤。 算法如下:

convert to gray
blur
unsharp mask
threshold 

在 smoother_edges() 函数中,将 2 个中间步骤合并。


你发布的输出真的很好。让我告诉你我能理解你的程序在做什么。首先,它要求用户手动设置阈值和模糊值,然后将这些值传递给其他函数,这些函数隐式地使用这些值来应用阈值和模糊到图像上。此外,我只看到一个小白窗口,在设置阈值和模糊之后。顺便说一句,谢谢。 - StupidGuy
而且我想要一个不涉及任何手动工作的方案。 - StupidGuy
1
确定合适的数值后,只需删除轨迹条功能并使用固定值执行步骤。算法如下:转换为灰度、模糊、反锐化掩蔽、阈值化。中间的两个步骤在smoother_edges()函数中合并。 - Michał Gacka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接