ハフ円検出¶
ハフ円検出を行い、検出結果を画像として保存するサンプルコードです。
import pyfie
import matplotlib.pyplot as plt
# 利便のため PyFIE 関数が返すエラーコードに応じて例外を発生させる機能を有効化
pyfie.ctrl.enable_f_err_exception(True)
# 入力画像読み込み
himg = pyfie.imread("houghcircle_input.png")
# ソーベルフィルタを利用したエッジ検出
edges = pyfie.F_DEDGE.PTR()
nedges = pyfie.INT()
pyfie.fnFIE_edge_sobel_subpix(
himg, None, pyfie.F_EDGE_SOBEL_PARAMS(mag_threshold=120, nms_length=3),
pyfie.F_EDGE_FEAT_DIRECT, pyfie.F_BORDER_NONE, (0.0, 0.0),
edges, nedges
)
# エッジ点をプロットし途中画像として保存
himg.imshow()
edges.plot(nedges, c="lime", s=0.5)
plt.savefig("houghcircle_edge.png")
plt.close()
# エッジ点を円ハフ検出用に変換
dedges = pyfie.DEDGE_T.ARRAY(nedges)
dedges.value = [pyfie.DEDGE_T(e.x, e.y, e.q) for e in edges[:nedges]]
# データ受け取り用変数を用意
circles = pyfie.HCD_CIRCLE_T.PTR()
ncircles = pyfie.INT()
# 円の検出
pyfie.hough_circles_detect(
dedges, len(dedges),
dRMin=20,
dRMax=250,
dRsl=1.0,
iQRange=10,
iEdgePercent=30,
iMinScore=8,
iCircleColor=pyfie.BLACK_WHITE_COLOR,
bRefine=True,
iMergeXY=2,
iMergeR=1,
vppCircles=circles,
ipCirclesNum=ncircles,
ipPntsIndex=None,
)
# 取得した円を表示
print("num circles:", ncircles)
for i, circle in enumerate(circles[:ncircles]):
print("#{}: xc = {:.2f}, yc = {:.2f}, r = {:.2f}, score = {}".format(
i, circle.xc, circle.yc, circle.r, circle.score
))
# 取得した円をプロットし結果画像として保存
himg.imshow()
ax = plt.gca()
for c in circles[:ncircles]:
ax.add_artist(plt.Circle((c.xc, c.yc), c.r, color="red", fill=False))
plt.savefig("houghcircle_result.png")
# 解放処理
edges.fnOAL_free()
circles.fnOAL_free()
処理結果例¶
$ python sample_houghcircle.py
num circles: 14
#0: xc = 255.92, yc = 236.11, r = 22.04, score = 55
#1: xc = 256.91, yc = 236.35, r = 37.25, score = 96
#2: xc = 256.91, yc = 236.65, r = 41.60, score = 106
#3: xc = 256.85, yc = 236.77, r = 55.97, score = 180
#4: xc = 256.90, yc = 236.79, r = 60.23, score = 208
#5: xc = 256.87, yc = 236.97, r = 74.74, score = 246
#6: xc = 256.88, yc = 237.06, r = 78.92, score = 313
#7: xc = 256.83, yc = 237.23, r = 93.21, score = 223
#8: xc = 256.88, yc = 237.38, r = 97.67, score = 244
#9: xc = 256.38, yc = 237.85, r = 112.00, score = 318
#10: xc = 256.45, yc = 237.90, r = 116.22, score = 319
#11: xc = 256.26, yc = 238.19, r = 130.86, score = 343
#12: xc = 256.92, yc = 238.16, r = 135.07, score = 388
#13: xc = 255.13, yc = 239.05, r = 147.01, score = 473
入力画像
エッジ画像
円検出結果