英文:
The distance from center of the binary image to the furthest point of the contour
问题
The main idea is to find the furthest point coordinates of the contour from the center of the image in Python.
Normally it is possible to find the extreme points of the contour using findcontours
and argmin
and argmax
in OpenCV.
However, for this problem we need the most distant point from the center of the image as illustrated in the image below:
.
How can we get this distance?
英文:
The main idea is to find the furthest point coordinates of the contour from the center of the image in Python.
Normally it is possible to find the extreme points of the contour using findcontours
and argmin
and argmax
in OpenCV.
However, for this problem we need the most distant point from the center of the image as illustrated in the image below:
.
How can we get this distance?
答案1
得分: 3
以下是翻译后的代码部分:
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)
英文:
Seems straightforward enough:
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)
You start by masking the image to find the pixels making up the circle, then you calculate the distance to each of these points and return the max distance as well as the corresponding point.
Edit: You can probably do this way more elegantly using np.linalg.norm
and np.argwhere
, but the approach stays the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论