二值图中心到轮廓最远点的距离

问题描述 投票:0回答:1

主要思想是在Python中找到距离图像中心最远的轮廓点坐标。

binary image with a contour

通常可以在 OpenCV 中使用

findcontours
argmin
argmax
找到轮廓的极值点。

然而,对于这个问题,我们需要离图像中心最远的点,如下图所示:

binary image with a circle.

我们怎样才能得到这个距离?

python opencv image-processing distance euclidean-distance
1个回答
1
投票

看起来很简单:

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
更优雅地执行此操作,但方法保持不变。

© www.soinside.com 2019 - 2024. All rights reserved.