카테고리 없음

[python] ConvexHull, AlphaShape

yennle 2023. 7. 21. 17:34
728x90

2차원 데이터에서 최외곽선을 표시하기 위한 함수 convexHull, alphashape 함수에 대해서 정리하고자 한다.

 

ConvexHull

모든 데이터를 다 포함하는 외곽선을 그려주는 함수이다.

 

from scipy.spatial import ConvexHull

# 랜덤한 점 10개
x = [random.randint(1,10) for i in range(10)]
y = [random.randint(1,10) for i in range(10)]

# convex hull 구하기
points = np.array([list(p) for p in zip(x,y)])
hull = ConvexHull(points)

# 시각화
plt.scatter(x,y)
for s in hull.simplices:
    plt.plot(points[s, 0], points[s, 1], 'r--')
    plt.plot(points[s, 0], points[s, 1], 'ro')

 

 

 

 

AlphaShape

ConvexHull과 비슷한 함순데, alpha를 조정해 더욱 세밀하게 조정할 수 있는 함수다.

 

import numpy as np
import alphashape
from descartes import PolygonPatch
import matplotlib.pyplot as plt


# 점 생성
x = [random.randint(1,10) for i in range(10)]
y = [random.randint(1,10) for i in range(10)]

points = np.array([list(point) for point in zip(x,y)])


# alphashape 실행
alpha = 0.5
alphashape = alphashape.alphashape(points, alpha)



# 시각화
# polygon
if alphashape.geom_type == 'Polygon':

    fig, ax = plt.subplots()
    ax.scatter(points[:,0],points[:,1])
    ax.add_patch(PolygonPatch(alphashape,alpha=0.2))

    
# multipolygon
else:
    fig, ax = plt.subplots()
    ax.scatter(points[:,0],points[:,1], alpha=0.2)

    for g in alphashape.geoms:
        ax.plot(*g.exterior.xy)

 

왼쪽 그래프는 Polygon일 때의 모습이고, 오른쪽 그래프는 multipolygon일 때의 모습이다.

그래서 아래 if문을 작성해준 것!

 

 

 

 

※ AlphaShape 코드를 돌릴 때 아래 오류가 난다면 이 링크를 참고 하도록!

IndexError: too many indices for array: array is 0-dimensional, but 2 were indexed

https://stackoverflow.com/questions/75287534/indexerror-descartes-polygonpatch-wtih-shapely

 

 

728x90