Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@vaiorabbit
Created June 19, 2011 15:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaiorabbit/1034377 to your computer and use it in GitHub Desktop.
Save vaiorabbit/1034377 to your computer and use it in GitHub Desktop.
HoughCircles.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# USAGE : $ ./HoughCircles.py Media/foo.jpg
import cv
import sys
if __name__ == "__main__":
image = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_GRAYSCALE)
src = cv.LoadImage(sys.argv[1])
# - Python 版 OpenCV では cv.HoughCircles の引数にメモリストレージは利用不可。
# Nx1 または 1xN の行列を使う。
# - 行数(または列数)は大きく取っておかないと
# OpenCV Error: Null pointer () in cvSetSeqBlockSize, ...
# というエラーが出て止まるので注意。
circle_storage = cv.CreateMat(256, 1, cv.CV_32FC3) # CV_32FC3 == (x, y, radius)
cv.Smooth(image, image, cv.CV_GAUSSIAN, 5, 5)
# 検出
cv.HoughCircles(
image, # 画像
circle_storage, # 結果を受けとるバッファ
cv.CV_HOUGH_GRADIENT, # アルゴリズムの指定
2, # 内部でアキュムレーションに使う画像の分解能(入力画像の解像度に対する逆比)
image.width / 10, # 円同士の間の最小距離
100, # 内部のエッジ検出(Canny)で使う閾値
100, # 内部のアキュムレーション処理で使う閾値
image.width / 4, # 円の最小半径
image.width / 3) # 円の最大半径
# 結果を入力画像に重ね打ち
for r in range(circle_storage.rows):
p = circle_storage[r,0]
pt = (cv.Round(p[0]), cv.Round(p[1]))
cv.Circle(
src, # 画像
pt, # 円の中心
cv.Round(p[2]), # 円の半径
cv.CV_RGB(0, 0, 0xff), # 円の色
3) # 円の太さ
# 表示
cv.NamedWindow("cvHoughCircles", 1)
cv.ShowImage("cvHoughCircles", src)
cv.WaitKey(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment