python - 获取中心像素周围的像素周长

标签 python opencv trigonometry

我试图在中心像素周围得到一个像素圈。即,就像FAST关键点检测器的工作方式一样,我想在给定半径的情况下获取其周围的周边像素。无论数学如何,我从理论上都知道如何使用三角函数获得数学。即,我可以使用for循环并以15度进行迭代。我知道三角形的斜边长度是半径,我知道 Angular 。

任何建议如何获得给定像素周围的像素周长?

最佳答案

公式为:

(x-cx)**2 + (y-cy)**2 = r**2

其中cx和cy是圆的中心,x和y是要测试的坐标...现在,我们可以遍历x并使用如下公式获得y:
y = sqrt(r**2 - (x-cx)**2) + cy

另一种方法是迭代360度并计算x和y并添加偏移量(中心),如下所示:
x = cos(radians) * radius + cx
y = sin(radians) * radius + cy

第二版使我的测试更加完整。这是我在python中的测试脚本:
import numpy as np
import cv2
import math

img = np.zeros((480, 640, 1), dtype="uint8")
img2 = np.zeros((480, 640, 1), dtype="uint8")

center = (200, 200)
radius = 100

x = np.arange(center[0] - radius, center[0]+radius+1)
y_off = np.sqrt(radius**2 - (x - center[0]) **2)
y1 = np.int32(np.round(center[1] + y_off))
y2 = np.int32(np.round(center[1] - y_off))
img[y1, x] = 255
img[y2, x] = 255


degrees = np.arange(360)
x = np.int32(np.round(np.cos(degrees) * radius)) + center[0]
y = np.int32(np.round(np.sin(degrees) * radius)) + center[1]
img2[y,x] = 255


cv2.imshow("First method", img)
cv2.imshow("Second method", img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果是:

方法1

enter image description here

方法2

enter image description here

第三种方法...您在半径为半径x半径的圆周围取一个框,并使用上述给定的圆公式计算每个点,如果为true,则为圆点...但是绘制起来很不错整个圆,因为您有整数并且很可能没有多少点相等...

更新:

提醒一下,请确保您的点在图像中,在上面的示例中,如果将中心置于0,0,则它将在每个角上绘制一个圆的1/4,因为它认为负值从数组的末尾。

要删除重复项,您可以尝试以下代码:
c = np.unique(np.array(list(zip(y,x))), axis=0  )
img2[c[:,0], c[:,1]] = 255

关于python - 获取中心像素周围的像素周长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53334694/

相关文章:

python数组过滤越界

python - 阻塞套接字客户端示例

python - 绘制具有特定位置、大小和旋转的图像

opencv - OpenCV摄像机校准:distCoeffs中的k3值非常大

已知所有边, Angular 和前两个点时查找三 Angular 形第三点的Javascript函数

math - 选择圆半径以完全填充矩形

java - 如何根据加速度估计角度以及根据 3 维角度估计加速度?

python - 如何表示 tensorflow 中的稀疏特征列表?

python - 在 Python 中絮凝数据

image - 选择霍夫变换的参数