我的目標是確定點是否位于形狀內部。考慮以下示例:
import numpy as np
from matplotlib import pyplot as plt
import warnings
warnings.filterwarnings('ignore', 'invalid value encountered in sqrt')
r1 = 10
r2 = 4
a = 12 # x shift for circle 2
b = -4 # y shift for circle 2
theta = np.arange(0, 2*np.pi, 0.0006)
r1_complex = r1*np.exp(1j*theta)
r1_x, r1_y = np.real(r1_complex), np.imag(r1_complex)
r2_complex = r2*np.exp(1j*theta)
r2_x, r2_y = np.real(r2_complex) a, np.imag(r2_complex) b
fig, ax = plt.subplots()
ax.plot(r1_x, r1_y)
ax.plot(r2_x, r2_y)
ax.set_aspect('equal')
ax.grid()
plt.show()
輸出

我想找到橙色圓圈內的藍色圓圈的點。如果可能的話,最好在沒有迭代的情況下嘗試找到它。
對于這種情況,我可以輕松確定橙色圓圈內的點,因為我知道圓圈的方程。將代碼修改為:
import numpy as np
from matplotlib import pyplot as plt
import warnings
warnings.filterwarnings('ignore', 'invalid value encountered in sqrt')
r1 = 10
r2 = 4
a = 12 # x shift for circle 2
b = -4 # y shift for circle 2
theta = np.arange(0, 2*np.pi, 0.0006)
r1_complex = r1*np.exp(1j*theta)
r1_x, r1_y = np.real(r1_complex), np.imag(r1_complex)
r1_inside_y = np.logical_and(r1_y < np.sqrt(r2**2 - (r1_x - a)**2) b, r1_y > -np.sqrt(r2**2 - (r1_x - a)**2) b)
r2_complex = r2*np.exp(1j*theta)
r2_x, r2_y = np.real(r2_complex) a, np.imag(r2_complex) b
fig, ax = plt.subplots()
ax.plot(r1_x, r1_y)
ax.plot(r2_x, r2_y)
ax.plot(r1_x[r1_inside_y], r1_y[r1_inside_y])
ax.set_aspect('equal')
ax.grid()
plt.show()
輸出

產生我正在尋找的東西。有沒有辦法在不知道圓的方程的情況下得到同樣的結果?也許是一種演算法,或者巧妙的numpy操作方法?
編輯
我所說的任意形狀是一種具有 N 個點的封閉形狀。考慮這個影像:

I would like to know the points from the black line that lie inside the bounds of the red line. For this example, there are two points that this algorithm should find, the x4 and x5 points in blue. And the points x1, x2, ... xN would be coordinate points where both shapes share the same origin.
uj5u.com熱心網友回復:
事實證明,這個演算法已經在 matplotlib.path 模塊中標準化了。您可以使用Path該類產生相同的結果。考慮對上述代碼進行以下更改:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import path
r1 = 10
r2 = 4
a = 12 # x shift for circle 2
b = -4 # y shift for circle 2
theta = np.arange(0, 2*np.pi, 0.0006)
r1_complex = r1*np.exp(1j*theta)
r1_x, r1_y = np.real(r1_complex), np.imag(r1_complex)
stacked1 = np.stack((r1_x, r1_y), axis=1) # A list of coordinates
r2_complex = r2*np.exp(1j*theta)
r2_x, r2_y = np.real(r2_complex) a, np.imag(r2_complex) b
stacked2 = np.stack((r2_x, r2_y), axis=1) # A list of coordinates
p = path.Path(stacked2)
r1_inside = p.contains_points(stacked1)
fig, ax = plt.subplots()
ax.plot(r1_x, r1_y)
ax.plot(r2_x, r2_y)
ax.plot(r1_x[r1_inside], r1_y[r1_inside])
ax.set_aspect('equal')
ax.grid()
plt.show()
這會在不了解形狀的數學特性的情況下生成相同的影像。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/392564.html
標籤:python algorithm numpy geometry
下一篇:python中物件方法的多執行緒
