4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

図形の数を自動で数える

Last updated at Posted at 2019-07-16

sikaku.png
result.png


import cv2
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

filename = input()
img = cv2.imread(filename)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
contours, hierarchy = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

def draw_contours(ax, img, contours):
        ax.imshow(img)
        ax.set_axis_off()
        for i, cnt in enumerate(contours):

                # 形状を変更する。(NumPoints, 1, 2) -> (NumPoints, 2)
                cnt = cnt.squeeze(axis=1)

                # 輪郭の点同士を結ぶ線を描画する。
                # ax.add_patch(Polygon(cnt, color="b", fill=None, lw=1))

                # 輪郭の点を描画する。
                # ax.plot(cnt[:, 0], cnt[:, 1], "ro", mew=0, ms=2)

                # 輪郭の番号を描画する。
                ax.text(cnt[0][0], cnt[0][1]-15, i+1, color="orange", size="20")

fig, ax = plt.subplots()
draw_contours(ax, img, contours)
plt.savefig('result.png')
print(len(contours))
plt.show()

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?