OpenCV 4.13.0
Open Source Computer Vision
読み込み中...
検索中...
見つかりません
🤖 AIによる機械翻訳(非公式) — これは OpenCV 4.13.0 公式リファレンス(英語)を AI (Claude) で自動翻訳したものです。訳に誤りを含む場合があります。正確な情報は 公式英語版(原文) を参照してください。
ハフ円変換

目標

本章では、

  • ハフ変換を用いて画像内の円を検出する方法を学ぶ。
  • ここでは次の関数を扱う: cv.HoughCircles()

理論

円は数学的に \((x-x_{center})^2 + (y - y_{center})^2 = r^2\) と表される。ここで \((x_{center},y_{center})\) は円の中心、\(r\) は円の半径である。この式から、3つのパラメータがあることがわかるので、ハフ変換には3次元のアキュムレータが必要となり、これは非常に非効率である。そこでOpenCVは、より巧妙な方法である ハフ勾配法 (Hough Gradient Method) を用いる。これはエッジの勾配情報を利用する。

ここで使用する関数は cv.HoughCircles() である。多くの引数を持つが、ドキュメントで十分に説明されている。そこで直接コードを見ていく。

import numpy as np
import cv2 as cv
img = cv.imread('opencv-logo-white.png', cv.IMREAD_GRAYSCALE)
assert img is not None, "file could not be read, check with os.path.exists()"
img = cv.medianBlur(img,5)
cimg = cv.cvtColor(img,cv.COLOR_GRAY2BGR)
circles = cv.HoughCircles(img,cv.HOUGH_GRADIENT,1,20,
param1=50,param2=30,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
# draw the outer circle
cv.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
cv.imshow('detected circles',cimg)
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
int waitKey(int delay=0)
Waits for a pressed key.
void destroyAllWindows()
Destroys all of the HighGUI windows.
Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
Loads an image from a file.
void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0, AlgorithmHint hint=cv::ALGO_HINT_DEFAULT)
Converts an image from one color space to another.
void circle(InputOutputArray img, Point center, int radius, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a circle.
void HoughCircles(InputArray image, OutputArray circles, int method, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0)
Finds circles in a grayscale image using the Hough transform.
void medianBlur(InputArray src, OutputArray dst, int ksize)
Blurs an image using the median filter.

結果を以下に示す:

image