質問するログイン新規登録

質問編集履歴

1

ここまでにやっているコードを追記しました。

2021/10/10 01:24

投稿

totoro33
totoro33

スコア1

title CHANGED
File without changes
body CHANGED
@@ -22,12 +22,71 @@
22
22
  です。
23
23
 
24
24
  分割後の各点から垂線を引く方法と垂線と輪郭線との交点の座標を取得する方法がわからず試行錯誤しています。
25
+ ```ここに言語を入力 python
26
+ コード
27
+ #モジュールのインポート
28
+ import cv2
29
+ import matplotlib.pyplot as plt
30
+ %matplotlib inline
31
+ import numpy as np
32
+ import math
25
33
 
34
+ #最大輪郭を得る関数
35
+ def find_max_contour(img):
36
+ contours, _ = cv2.findContours(
37
+ img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
38
+ )
39
+ max_contour = max(contours, key=lambda x:cv2.contourArea(x))
26
40
 
41
+ return max_contour
42
+ # 画像の読み込み
43
+ img = cv2.imread("opening2.png", 0)
44
+ color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
45
+ lines = cv2.HoughLinesP(img, rho=1, theta=np.pi/360, threshold=80, minLineLength=80, maxLineGap=10)
46
+ # 複数の直線がある場合、y座標の和がもっとも大きいものを採用
47
+ # 中点(mid_x, mid_y)
48
+ y_sum_dict = {}
49
+ for i, pos in enumerate(lines.squeeze(1)):
50
+ y1, y2 = pos[1], pos[3]
51
+ y_sum_dict[i] = y1 + y2
27
52
 
53
+ index = 0
28
- ```ここに言語名を入力
54
+ y_sum_max = 0
55
+ for i, y_sum in y_sum_dict.items():
56
+ if i == 0:
57
+ index = i
58
+ y_sum_max = y_sum
29
- python
59
+ else:
60
+ if y_sum_max < y_sum:
61
+ y_sum_max =y_sum
62
+ index = i
30
63
 
64
+ pos = lines.squeeze(1)[index]
65
+ x1, y1, x2, y2 = pos[0], pos[1], pos[2], pos[3]
66
+ print(x1, y1, x2, y2)
67
+ mid_x, mid_y = int((x1+x2)/2), int((y1+y2)/2)
68
+ print(mid_x, mid_y)
69
+
70
+ # 全ての輪郭上の点に対してユークリッド距離を計算する方針
71
+ def get_distance(x1, y1, x2, y2):
72
+ d = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
73
+ return d
74
+ # 中点から最大距離の点を見つける(api_x, api_y)
75
+ dist_list = []
76
+ for point in max_cnt.squeeze(1):
77
+ x, y = point[0], point[1]
78
+ dist = get_distance(mid_x, mid_y, x, y)
79
+ dist_list.append(dist)
80
+ max(dist_list)
81
+
82
+ max_dist_index = dist_list.index(max(dist_list))
83
+ apical = max_cnt.squeeze(1)[max_dist_index]
84
+
85
+ api_x, api_y = apical[0], apical[1]
86
+ # 20等分する
87
+ lins = np.linspace((api_x, api_y), (mid_x, mid_y), 21)
88
+ ```
89
+
31
90
  ### 試したこと
32
91
  ベクトルの内積から垂線をひけるのではないかと考えましたが、その実装ができていません。
33
92