opencv draw inscribed circle

First on the renderings:
insert image description here
original image:
insert image description here

Ideas:

Mainly use cv2.pointPolygonTest to find the shortest distance between all points in the image and the contour. According to the characteristics of the function, the outer contour is negative and the inner contour is positive. Then use cv2.minMaxLoc to filter, extract the maximum index we take is the center coordinate, the maximum value is the center radius.

Detailed description: cv2.pointPolygonTest
Point Polygon Test
solves the shortest distance from a point in the image to the outline of an object. If the point is outside the contour, the
return value is negative. If on the contour, the return value is 0. If inside the contour, the return value is positive.
Let's take the point (50, 50) as an example:
dist = cv2.pointPolygonTest(cnt,(50,50),True) The third parameter of this function is measureDist. If set to True, the
shortest distance will be calculated. If it is False, only the positional relationship between this point and the contour will be judged (the return value is
+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)

Guess you like

Origin blog.csdn.net/qq_42102546/article/details/123372397