这有点笨拙,但是您可以比较从内部轮廓上的点到外部轮廓上的点的距离,如果距离小于某个阈值,则“紧贴”到外部轮廓。
你的图像在星星的边缘周围有一些奇怪的伪影,所以我在 Paint 中绘制了我自己的图像。
原始图像
“紧贴”之后(25 距离截止)
import cv2
import numpy as np
import math
# 2d distance
def dist2D(p1, p2):
dx = p1[0] - p2[0];
dy = p1[1] - p2[1];
return math.sqrt(dx*dx + dy*dy);
# cling to closest point
def cling(point, other_points, cutoff):
# find closest point
best_dist = 10000000; # JUST A BIG NUMBER
best_point = [0,0];
for op in other_points:
dist = dist2D(point, op);
if dist < best_dist:
best_dist = dist;
best_point = op[:];
# if less than cutoff, cling to point
if best_dist <= cutoff:
return best_point;
return point;
# go through each point on inner and cling to nearby outer points
def clingy(inner, outer, cutoff):
new_inner = [];
for point in inner:
point = cling(point, outer, cutoff);
new_inner.append(point);
return new_inner;
# load image
img = cv2.imread("my_stars.png");
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
# make a mask
mask_outer = cv2.inRange(gray, 0, 1);
mask_inner = cv2.inRange(gray, 2, 254);
# contours OpenCV3.4, if you're using OpenCV 2 or 4, it returns (contours, _)
_, outer, _ = cv2.findContours(mask_outer, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE);
_, inner, _ = cv2.findContours(mask_inner, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE);
# just take the first contour
outer = outer[0];
inner = inner[0];
# strip out annoying extra brackets
stripped_inner = np.array([p[0] for p in inner]);
stripped_outer = np.array([p[0] for p in outer]);
# cling
cling_inner = clingy(stripped_inner, stripped_outer, 25);
# add back in annoying brackets
cling_inner = np.array([[p] for p in cling_inner]);
# draw on original image
cv2.drawContours(img, [cling_inner], -1, (240,200,0), -1);
# draw original contour again
cv2.drawContours(img, [inner], -1, (150,100,0), 1);
# show
cv2.imshow("Image", img);
cv2.waitKey(0);