目标:基于轮廓与边缘的参考,计算图像中每个像素点到最近轮廓的距离,生成距离系数图像。
应用场景:对象跟踪时,可以判断一个点或对象是否在指定区域内
首先需要获取几何图像的轮廓:
contours, hierachy = cv.findContours(dst, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
然后计算出每个像素距离轮廓的距离:
dist_flag = cv.pointPolygonTest(contours[i],(col,row),True)
代码如下:
def point_ploygon_test_demo():
src = cv.imread("D:/pythonTest/img/4.jpg")
cv.imshow("input", src)
src = cv.GaussianBlur(src, (3, 3), 0)
grey = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
ret, dst = cv.threshold(grey, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
cv.imshow("output", dst)
contours, hierachy = cv.findContours(dst, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
print(len(contours))
h,w = dst.shape
for i in range(len(contours)):
for row in range(h):
for col in range(w):
dist_flag = cv.pointPolygonTest(contours[i],(col,row),True)
if dist_flag > 0 :
src[row,col] = (np.abs(dist_flag)+150,0,0)
cv.imshow("dist_flag",src)
效果如下: