从一个高度(约130英尺)点击的另一个图像中提取的图像。现在,当提取这个较小的图像时,它包含一个实际上具有非常规则和平滑形状的对象,具有非常粗糙的边缘。现在我想检测不。角落,物体有(不使用轮廓)。但由于这些粗糙的边缘,没有。检测到的角落大大增加。
如何使边缘笔直?
答案 0 :(得分:5)
我认为您正在寻找的是一种简单的边缘平滑算法。我为你实现了一个。它并没有将彩色标志保存在外形内 - 如果这也很重要 - 因为你在问题中没有提到 - 你必须在你的身上找到那个部分拥有。结果:
我已经实现了跟踪栏,因此您可以使用平滑的值,但它适合您。按" 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个中间步骤。