ก่อนอื่น เราจะสร้าง Polygon โดยใช้เมธอด mplPath.Path และเพื่อตรวจสอบว่าจุดที่กำหนดอยู่ใน Polygon หรือไม่ เราจะใช้เมธอด poly_path.contains_point
ขั้นตอน
สร้างลิสต์ของจุดเพื่อทำ Polygon
สร้าง Path ใหม่ด้วย vertices และ codes ที่กำหนด ใช้
mplPath.Path()ตรวจสอบว่าจุด (200, 100) อยู่ใน Polygon หรือไม่ ใช้เมธอด
contains_point()คืนค่าว่า Path (ปิด) มีจุดที่กำหนดหรือไม่ => Trueตรวจสอบว่าจุด (1200, 1000) อยู่ใน Polygon หรือไม่ ใช้เมธอด
contains_point()คืนค่าว่า Path (ปิด) มีจุดที่กำหนดหรือไม่ => False
ตัวอย่าง
import matplotlib.path as mplPath
import numpy as np
poly = [190, 50, 500, 310]
poly_path = mplPath.Path(np.array([[190, 50],
[50, 500],
[500, 310],
[310, 190]]))
point = (200, 100)
print(point, " is in polygon: ", poly_path.contains_point(point))
point = (1200, 1000)
print(point, " is in polygon: ", poly_path.contains_point(point))
ผลลัพธ์
(200, 100) is in polygon: True (1200, 1000) is in polygon: False