如评论中所述,这里的简单方法似乎是将图像与盒式滤波器(或类似的椭圆形状)卷积,这将在整个图像上给出窗口平均值。您可以在角点处简单地索引此卷积结果。如果这些点处的卷积结果超过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
中的一种方法 来成对迭代(例如,s -> (s0, s1), (s1, s2), ...
)。这对于消除从 findContours()
获取的重复点非常有用,但与问题无关。在此之后,其余部分如先前所述进行。您可以自己绘制内核或者使用 getStructuringElement()
中提供的一个内核,因为它可以创建任意大小的椭圆(请注意,这返回一个形状奇怪的内核,您可能最好自己定义一个圆)。请注意,内核的大小在此处以总宽度指定,而不仅仅是半径,并且它被其中1的数量标准化,以便结果始终在0和1之间。
returnPoints
并将其设置为False
,它将只返回原始点中在凸包内的索引(因此您还将知道不在凸包中的点的索引)。 - alkasm