はじまる

適当な事を適当に書く

Python & OpenCV で 画像に含まれる円を検出する(OpenCVがver2の場合)

これの続きです。

maroyaka.hateblo.jp

mac での場合

❯❯❯ uname -a
Darwin xxxx 14.5.0 Darwin Kernel Version 14.5.0: Wed Jul 29 02:26:53 PDT 2015; root:xnu-2782.40.9~1/RELEASE_X86_64 x86_64
❯❯❯ brew --version                                                                                                                                                                                                                                                   
Homebrew 1.1.13
Homebrew/homebrew-core (git revision 7b34e; last commit 2017-04-19)

homebrew で opencv をインストールすると、バージョンが2系のがはいる。

❯❯❯ python
Python 2.7.13 (default, Dec 18 2016, 07:03:34)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'2.4.13.2'

前回のPythonスクリプトをそのまま使うと、エラーになる。

解決にはここを参考にした。

stackoverflow.com

修正後はこんな感じ

import sys
import cv2
import cv2.cv as cv #2系だと HOUGH_GRADIENT がこのモジュールにはいってる
import numpy as np

args = sys.argv

img = cv2.imread(args[1], 0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img, cv.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
        cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    # draw the center of the circle
        cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

cv2.imwrite('detected_' + args[1], cimg)