♦️

OpenCVで楕円フィッティング

元画像

notion image

出力画像

notion image
# code by Daiki TOMIOKA import cv2 as cv img = cv.imread('image_large.png') # 画像の読み込み height = img.shape[0] # 画像の高さを取得 width = img.shape[1] # 画像の幅を取得 # サイズの変更 resized_img = cv.resize(img, (int(width*0.3), int(height*0.3))) img = resized_img # img = cv.imread('image.png') # 画像読み込み gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # グレースケール化 ret, thresh = cv.threshold(gray, 80, 255, cv.THRESH_BINARY) # 二値化 thresh = cv.bitwise_not(thresh) # 反転 # 輪郭抽出 contours, hierarchies = cv.findContours( thresh, cv.RETR_LIST, cv.CHAIN_APPROX_NONE) for i, count in enumerate(contours): ellipse = cv.fitEllipse(count) # 楕円でフィッティング img_ellipse = cv.ellipse(img, ellipse, (0, 0, 255), 2) # 画像imgに楕円の描画 cv.imshow('img_ellipse', img_ellipse) # 画像を出す cv.imwrite('image_ellipse.jpg', img_ellipse) # 画像の保存 cv.waitKey()