10-6FindCircle.py

000: import cv2
001: import numpy as np
002:
003: def __main():
004:
005: img = cv2.imread(‘IMG_1610.JPG’)
006:
007: img = getResize(img)
008: dst = getCircles(img)
009:
010: cv2.imshow(“Final result”, dst)
011: cv2.waitKey(0)
012: cv2.destroyAllWindows()
013:
014: def getResize(src):
015:
016: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
017: height = src.shape[0]
018: width = src.shape[1]
019:
020: largeSize = max(height, width) # 大きい方の辺のサイズ
021: resizeRate = basePixSize / largeSize # 変更比率を計算
022: shotSize = min(height, width) * resizeRate
023: dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)))
024:
025: return dst
026:
027: def getCircles(src):
028:
029: gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
030: # ガウシアンフィルタ
031: ksize = (25, 25) # 正の奇数で指定する(ここの数字を変えると効果が変更できる)
032: # フィルターの実行
033: gray = cv2.GaussianBlur(gray, ksize, 0, 0)
034: ret, gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
035: cv2.imshow(‘Preimg’, gray)
036:
037: # 円を検知した座標を取得する
038: circles = cv2.HoughCircles(image=gray, method=cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=100, param2=20, minRadius=None, maxRadius=None)
039: if circles is not None:
040: circles = np.uint16(np.around(circles))
041: for circle in circles[0, :]:
042: # 元画像に取得した座標の円を描画する
043: dst = cv2.circle(src, (circle[0], circle[1]), circle[2], (255, 0, 255), 2)
044:
045: return dst
046:
047: if __name__ == ‘__main__’:
048: print(cv2.__version__)
049:
050: __main()
051: