正如 cmets 中所提到的,这里似乎很容易做的事情是用箱形过滤器(或类似但具有椭圆形状)对您的图像进行卷积,这将为您提供整个图像的窗口平均值。你可以简单地在你的角点索引这个卷积结果。如果这些点的卷积结果超过 50%,则该点周围有更多的白色,因此,它是一个凹点。否则,它是凸的。这是代码中的样子。
import cv2
import numpy as np
from itertools import tee
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
# read image as grayscale
img = cv2.imread('example.png', 0)
# get corner points, remove duplicate/nearby points
contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
contour = contours[0]
pts = np.array([contour[0]] + [pt1 for pt0, pt1 in pairwise(contour) if not (abs(pt0 - pt1) <= 1).all()])
x, y = pts[:, -1, 0], pts[:, -1, 1]
# get the kernel that you will sum around your corner points
kernel = np.float64(cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (13, 13)))
kernel /= np.sum(kernel)
# convolve the image with the kernel, and pull out the sums at the corner points
conv = cv2.filter2D(img/255, cv2.CV_64F, kernel)
neighborhood_sums = conv[y, x]
# concave indices have more white than black around them, so convolution will be >= 1/2
concave_indices = neighborhood_sums >= 0.5
# draw markers
marked = cv2.merge([img, img, img])
for pt, concave in zip(pts, concave_indices):
color = (255, 0, 255) if concave else (0, 255, 0)
marker = cv2.MARKER_TRIANGLE_UP if concave else cv2.MARKER_TRIANGLE_DOWN
cv2.drawMarker(marked, tuple(pt[0]), color, markerType=marker, markerSize=10, thickness=3)
在导入之后,我定义了一个 itertools recipes 用于成对地迭代事物(例如 s -> (s0, s1), (s1, s2), ...)。这对问题来说根本不重要,但对我摆脱从findContours() 抓取的重复点很有用。之后,其余的如前所述进行。你可以画你自己的内核或者你喜欢的任何东西,但我只是从getStructuringElement() 中拉了一个,因为你可以做任意大小的椭圆(尽管注意这会返回一个形状奇怪的内核,你可以自己定义一个更好的圆)。请注意,内核的大小在此处以总宽度指定,而不仅仅是半径,并且通过其中 1 的数量进行归一化,因此结果始终在 0 和 1 之间。
这是您第一张图片的上述结果: