opencv 绘制内切圆

先上效果图:
在这里插入图片描述
原图:
在这里插入图片描述

思路:

主要使用 cv2.pointPolygonTest 来寻找图像中所有点与轮廓的最短距离,根据函数的特性,轮廓外为负轮廓内为正,再使用 cv2.minMaxLoc 筛选,提取我们取最大值索引就是圆心坐标,最大值就是圆心半径。

详细说明:cv2.pointPolygonTest
Point Polygon Test
求解图像中的一个点到一个对象轮廓的最短距离。如果点在轮廓的外部,
返回值为负。如果在轮廓上,返回值为 0。如果在轮廓内部,返回值为正。
下面我们以点(50,50)为例:
dist = cv2.pointPolygonTest(cnt,(50,50),True) 此函数的第三个参数是 measureDist。如果设置为 True,就会计算最
短距离。如果是 False,只会判断这个点与轮廓之间的位置关系(返回值为
+1,-1,0)。

import cv2
import numpy as np


# 读取图片,转灰度
mask = cv2.imread("6.jpg")
mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
# 二值化
ret, mask_gray = cv2.threshold(mask_gray, 127, 255, cv2.THRESH_BINARY)

# 识别轮廓
contours, _ = cv2.findContours(mask_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# 计算到轮廓的距离
raw_dist = np.empty(mask_gray.shape, dtype=np.float32)
for i in range(mask_gray.shape[0]):
    for j in range(mask_gray.shape[1]):
        raw_dist[i, j] = cv2.pointPolygonTest(contours[0], (j, i), True)

# 获取最大值即内接圆半径,中心点坐标
minVal, maxVal, _, maxDistPt = cv2.minMaxLoc(raw_dist)


# 半径:maxVal  圆心:maxDistPt
# 转换格式
maxVal = abs(maxVal)
radius = int(maxVal)

# 原图转换格式
result = cv2.cvtColor(mask_gray, cv2.COLOR_GRAY2BGR)


# 绘制内切圆
cv2.circle(result, maxDistPt, radius, (0, 255, 0), 2, 1, 0)
# 绘制圆心
cv2.circle(result, maxDistPt, 1, (0, 255, 0), 2, 1, 0)
cv2.imshow('0', result)
cv2.waitKey(0)

猜你喜欢

转载自blog.csdn.net/qq_42102546/article/details/123372397