Help us understand the problem. What is going on with this article?

Python+Scipyでランダムに作成した点から凸包を描く

More than 1 year has passed since last update.

久しぶりに小ネタ。

やること

  • 適当に2次元に点群を取得する
  • 点群から凸包を計算する
  • 点群と凸包をmatplotlibで描画する

ソース

# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import scipy.spatial as ssp


def point_in_hull(point, hull, tolerance=1e-6):
  return all(
    (np.dot(eq[:-1], point) + eq[-1] <= tolerance)
    for eq in hull.equations)


def main():
  N = 100
  points = np.random.rand(N, 2)
  idx_bases = np.random.choice(range(N), 5, replace=False)
  bases = points[idx_bases, :]

  # hull
  hull = ssp.ConvexHull(bases)
  idx = [i for i in range(N) if point_in_hull(points[i, :], hull)]

  # vis
  fig = plt.figure(figsize=(5, 5))
  ax = fig.gca()
  ax.scatter(points[:, 0], points[:, 1], c='r', marker='o')
  ax.scatter(bases[:, 0], bases[:, 1], c='b', marker='o')

  # in hull vertex and borders
  pidx = points[idx, :]
  ax.scatter(pidx[:, 0], pidx[:, 1], c='c', marker='x')
  for simplex in hull.simplices:
    plt.plot(bases[simplex, 0], bases[simplex, 1], "k--")

  ax.axis("off")
  ax.margins(x=0.015, y=0.015)
  ax.set_position([0.05, 0.05, 0.9, 0.9])
  plt.show()
  plt.close()


if __name__ == '__main__':
  main()

実行例

example.png

takilog
機械学習・数理最適化を用いた研究業務に従事しています (see @cocomoff)
http://takiblog.hateblo.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away