図形の検出

2019/09/05

Python2.7.8, OpenCV4.1.1

輪郭を単純な形状へ近似し、点の数で図形を判別

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

import numpy as np
import cv2

img = cv2.imread('shapes.png')
img_src = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==5:
        print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 8:
        print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 10:
        print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


How to detect simple geometric shapes using OpenCV
https://stackoverflow.com/questions/11424002/how-to-detect-simple-geometric-shapes-using-opencv

OpenCV-Pythonでの図形検出、図形数える
http://data-analysis-stats.jp/2019/03/25/opencv-python%E3%81%A7%E3%81%AE%E5%9B%B3%E5%BD%A2%E6%A4%9C%E5%87%BA%E3%80%81%E5%9B%B3%E5%BD%A2%E6%95%B0%E3%81%88%E3%82%8B/

領域(輪郭)の特徴 4. 輪郭の近似(公式ドキュメント和訳)
http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html#id5