画像にある曲線をSplineフィッティングしたい

python

1import cv2 2import numpy as np 3import matplotlib.pyplot as plt 4from skimage.morphology import skeletonize 5from skimage.filters import gaussian 6from scipy.interpolate import UnivariateSpline 7from scipy.interpolate import splprep, splev 8 9# 画像の読み込み10image = cv2.imread(r'C:\Users\phanton\Pictures\FTC\momentum\momentum_7.png',11 cv2.IMREAD_GRAYSCALE)12 13 14# スプライン曲線をフィットする関数15def fit_spline_curve(points):16 # x座標とy座標を分離17 x = points[:, 1] # 画像の座標系では (y, x) なので、ここで順番を変えます18 y = points[:, 0]19 20 # パラメータ u を計算21 u = np.linspace(0, 1, len(x))22 23 # パラメトリックスプラインをフィット24 tck, _ = splprep([x, y], s=0)25 return tck, u 26 27# ガウシアンフィルタでノイズを除去28blurred_image = gaussian(image, sigma=1)29 30# エッジ検出(Canny法を使用)31edges = cv2.Canny((blurred_image * 255).astype(np.uint8), 50, 150)32 33# 輪郭検出34contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)35contour = max(contours, key=cv2.contourArea)36 37# 輪郭の描画38contour_image = np.zeros_like(image)39cv2.drawContours(contour_image, [contour], -1, (255, 255, 255), 1)40 41# 形態学的変換を使用して輪郭を膨張させて連結を強化42kernel = np.ones((2, 2), np.uint8)43dilated = cv2.dilate(contour_image, kernel, iterations=1)44 45# 輪郭を再度検出し、内部を塗りつぶす46filled_contour_image = np.zeros_like(image)47contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)48contour = max(contours, key=cv2.contourArea)49cv2.drawContours(filled_contour_image, [contour], -1, (255, 255, 255),50 thickness=cv2.FILLED)51 52# スケルトン化の前に2値化53binary_image = filled_contour_image // 25554# スケルトン化55skeleton = skeletonize(binary_image)56 57# スケルトンから点を抽出58points = np.column_stack(np.where(skeleton))59# 結果の表示60# スプライン曲線のフィット61tck, u = fit_spline_curve(points)62 63u_fine = np.linspace(0, 1, 1000)64# # 画像の描画65plt.figure(figsize=(15, 5))66plt.subplot(1, 2, 1)67plt.imshow(skeleton, cmap='gray')68plt.title('Skeletonized Central Line')69 70# スプライン曲線の描画71plt.subplot(1, 2, 2)72plt.imshow(skeleton, cmap='gray')73x_fine, y_fine = splev(u_fine, tck)74plt.plot(x_fine, y_fine, color='red')75plt.title('Fitted Spline Curve')76plt.show()77

コメントを投稿

0 コメント