【发布时间】: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] > 0]应该提出了TypeError。 -
感谢您发现这一点。它是复制粘贴编辑的一种类型。
标签: python image-processing optimization numpy mathematical-optimization