方法有问题,canny是检测边缘的。检测圆形一般用Hough Transform。椭圆的话复杂一些,取决于实际问题,应该尝试先简化。
比如只限定大小而不限定椭圆的几何参数,可以用blob detection算法代替,用LoG, DoG 或 DoH 之类。
如果确定椭圆的大小,形状和或朝向,可以用给定参数的Hough Transform。OpenCV里没有现成的,建议用scikit-image。文档和示例代码页面我直接复制粘贴在下面了:
Circular and Elliptical Hough Transforms
The Hough transform in its simplest form is a method to detect straight lines but it can also be used to detect circles or ellipses. The algorithm assumes that the edge is detected and it is robust against noise or missing points.
Circle detection
In the following example, the Hough transform is used to detect coin positions and match their edges. We provide a range of plausible radii. For each radius, two circles are extracted and we finally keep the five most prominent candidates. The result shows that coin positions are well-detected.
Algorithm overview