import cv2
import numpy as np

def draw_lines(image, lines, color=(0, 255, 0), thickness=2):
    if lines is not None:
        for line in lines:
            for x1, y1, x2, y2 in line:
                cv2.line(image, (x1, y1), (x2, y2), color, thickness)

def find_intersection(line1, line2):
    # 各直線のパラメータを計算
    x1, y1, x2, y2 = line1[0]
    x3, y3, x4, y4 = line2[0]
    denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)

    # 交点を計算
    if denom != 0:
        px = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / denom
        py = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / denom
        return int(px), int(py)
    else:
        return None

# 画像を読み込む
image_path = 'path_to_your_image.jpg'
original_image = cv2.imread(image_path)

# 中心座標と半径を設定
mask_center = (x_center, y_center) # 中心座標を設定
mask_radius = 5 # 半径を設定

# 中略(マスク適用、Cannyエッジ検出、ハフ変換までのコード)

# 最長の2つの直線を見つける
sorted_lines = sorted(lines, key=lambda l: np.sqrt((l[0][2] - l[0][0]) ** 2 + (l[0][3] - l[0][1]) ** 2), reverse=True)
top_lines = sorted_lines[:min(2, len(sorted_lines))] # 最長の2本またはそれ以下

# 最長の2本の直線を描画
top_lines_image = np.copy(masked_image)
draw_lines(top_lines_image, top_lines, color=(0, 255, 0), thickness=2)

# 交点または円弧との交点を求め、中心座標と結ぶ緑色の直線を描画
if len(top_lines) == 2:
    # 2本の直線の交点を求める
    intersection_point = find_intersection(top_lines[0], top_lines[1])
    if intersection_point is not None:
        cv2.line(top_lines_image, mask_center, intersection_point, (0, 255, 0), 2)
elif len(top_lines) == 1:
    # ここに円弧との交点を計算するコードを追加(別途実装が必要)
    pass
else:
    print("直線無し")

cv2.imwrite('top_lines_image.jpg', top_lines_image)

# 結果を表示
cv2.imshow('Top Lines Image', top_lines_image)
cv2.waitKey(0)
cv2.destroyAllWindows()