1

I would like to get the enclosing circle on simple filled shapes. I'm using opencv and python for that. I use the minEnclosingCircle function. However on some examples I get weird results:

enter image description here

The center is supposed to be centred on the shape, and the circle is supposed to touch the shape. This is obviously not the case.

The interesting thing is that the center is not the same with the same picture rotated 90°. It is less shifted. There is no reason why a rotation changes the center of the minimum enclosing circle. This means this function is bugged, and I need an alternative. I just need the center of the circle though.

enter image description here

Here is a small version of my code:

import cv2
import numpy as np

img = cv2.imread('testodd3.jpg',cv2.CV_LOAD_IMAGE_COLOR)
pic = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(pic,127,255,0)
thresh = cv2.bitwise_not(thresh)
contours,hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
cv2.circle(img,center,radius,(0,255,0),3)
cv2.circle(img,center,3,(255,255,0),3)
cv2.drawContours(img, [cnt], 0, (0,0,255), 3)

cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

I saw a similar problem, but the solution uses a C++ library: Unexpected results of minEnclosingCircle in OpenCV

Tom
  • 834
  • 1
  • 14
  • 24
  • 1
    Seems a bug was filed, a pull request attempted to fix it, and then the pull was cancelled because it broke the test. Maybe should be reopened. See the discussion on [GitHub](https://github.com/opencv/opencv/pull/2758). – alkasm Sep 01 '17 at 15:29
  • Thanks for pointing me this. The bug report mentions a larger circle, which I noticed, but fortunately it doesn't matter to me since I am only interested in the center. However in my case the center is wrong. I'll add a message to the discussion and see what happens. – Tom Sep 02 '17 at 10:39
  • @Tom Check if my answer suffices your question – Jeru Luke Sep 02 '17 at 11:44

1 Answers1

1

The opencv version I used is 2.4.13.2_2 (latest homebrew version on Mac at this date). The implementation seems broken: https://github.com/opencv/opencv/issues/6438

Opencv 3.3 uses another implementation, which works fine.

Vertical image with correct center Horizontal image with correct center

Here is a simple code:

import cv2
import numpy as np

img = cv2.imread('testodd7.jpg',cv2.IMREAD_GRAYSCALE)
ret,thresh = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
img,contours,hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)

img2 = cv2.imread('testodd7.jpg',cv2.IMREAD_COLOR)
cv2.circle(img2,center,radius,(0,255,0),3)
cv2.circle(img2,center,3,(255,255,0),3)
cv2.drawContours(img2, [cnt], 0, (0,0,255), 3)

cv2.imshow('image',img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
Tom
  • 834
  • 1
  • 14
  • 24