【问题标题】:Fitting circle inside image. Exit condition for loop图像内的拟合圆圈。循环的退出条件
【发布时间】:2015-02-03 06:50:49
【问题描述】:

我正在尝试编写一些代码来检查我的圆圈是否适合二进制掩码。

所以,我有一个给定中心和半径的圆。我也有一个二值图像,我可以绘制它并查看圆圈是否适合蒙版。附上剧情:

所以我要做的是找到适合这个二进制掩码的最佳圆。所以,我目前的情况如下:

import numpy as np
# Start with a random radius
radius = 100
# Keep track of the best radius
best_radius = 0
# Mask is the binary mask
x, y = np.ogrid[:mask.shape[0], :mask.shape[1]]
# distance computation
distance = np.sqrt((x-r)**2 + (y-c)**2)

while True:
    # check if the distance < radius
    m = distance < radius
    # if this is true everything in the circle is in the image
    if np.all[mask[m] > 0]:
        # Update best radius
        best_radius = radius
        # Increase radius for next try
        radius += radius/2
    else:
        # decrease radius
        radius -= radius/2
        if radius <= best_radius:
            break

所以,我遇到的第一个问题是中断条件。虽然这很有效,但它总是给我一个圆圈,它在面具内,但它并不总是最佳的。因此,在上面的示例中运行它,我得到以下最佳圆圈:

如您所见,半径仍然可以增加。所以,我有一种感觉,我增加和减少半径的方式是不对的。

另一个大问题是,这是一种非常老套的方法,可以像野蛮人一样粗暴地做到这一点。如果有人有更优雅的解决方案可以分享,我将不胜感激。也许,这里可以使用一些数值优化程序?

【问题讨论】:

  • np.all[closed[m] &gt; 0] 应该提出了TypeError
  • 感谢您发现这一点。它是复制粘贴编辑的一种类型。

标签: python image-processing optimization numpy mathematical-optimization


【解决方案1】:
  • 计算每个非屏蔽点到(r,c) 的距离。
  • 最大半径是距离中的最小值。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

h, w = 600, 700
r, c = 250, 350

def make_mask():
    x, y = np.ogrid[:h, :w]
    y -= c
    x -= r
    theta = np.arctan2(y, x)
    rad = 200 + 100*(np.sin(theta+np.pi/2)**2) 
    mask = (x**2 + y**2) < rad**2
    return mask

mask = make_mask()
x, y = np.ogrid[:h, :w]
distance_sq = (x-r)**2+(y-c)**2
radius = np.sqrt((distance_sq[~mask]).min())

fig, ax = plt.subplots()
ax.imshow(mask)
ax.add_patch(patches.Circle((c,r), radius=radius))
plt.show()


yields

【讨论】:

    猜你喜欢
    • 2015-06-09
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多