主要思想是在Python中找到距离图像中心最远的轮廓点坐标。
通常可以在 OpenCV 中使用
findcontours
和 argmin
和 argmax
找到轮廓的极值点。
然而,对于这个问题,我们需要离图像中心最远的点,如下图所示:
.
我们怎样才能得到这个距离?
看起来很简单:
import cv2 as cv
import numpy as np
file = r'/Users/lh/Downloads/LTSmL.png'
img = cv.imread(file, 0)
max_intensity = np.max(img)
mask = np.argwhere(img == max_intensity)
center = (img.shape[0]/2, img.shape[1]/2)
maxdist = 0
maxpoint = None
for point in mask:
dist = np.sqrt((center[0] - point[0])**2 + (center[1] - point[1])**2)
if dist > maxdist:
maxdist = dist
maxpoint = point
img_color = cv.cvtColor(img, cv.COLOR_GRAY2RGB)
img_color[maxpoint[0] - 5:maxpoint[0] + 5, maxpoint[1] - 5:maxpoint[1] + 5] = [0, 0, 255]
cv.imshow('Farthest point in red', img_color)
cv.waitKey()
cv.destroyAllWindows()
print(dist, point)
首先对图像进行遮罩以找到构成圆的像素,然后计算到每个点的距离并返回最大距离以及对应的点。
编辑:您可以使用
np.linalg.norm
和 np.argwhere
更优雅地执行此操作,但方法保持不变。