OpenCV + Pythonで特定の図形を検出する

OpenCV + Pythonで特定の図形を検出する1(図形の領域を矩形で取得)
確かにここの輪郭を検出しているようだ。
import cv2 as cv
def main():
    # ファイルを読み込み
    image_file = 'debug_1.png'
    src = cv.imread(image_file, cv.IMREAD_COLOR)
    # 画像の大きさ取得
    height, width, channels = src.shape
    image_size = height * width
    # グレースケール化
    img_gray = cv.cvtColor(src, cv.COLOR_RGB2GRAY)
    # しきい値指定によるフィルタリング
    retval, dst = cv.threshold(img_gray, 127, 255, cv.THRESH_TOZERO_INV )
    # 白黒の反転
    dst = cv.bitwise_not(dst)
    # 再度フィルタリング
    retval, dst = cv.threshold(dst, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    # 輪郭を抽出
    #dst, contours, hierarchy = cv.findContours(dst, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    contours, hierarchy = cv.findContours(dst, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    
    # この時点での状態をデバッグ出力
    dst = cv.imread(image_file, cv.IMREAD_COLOR)
    dst = cv.drawContours(dst, contours, -1, (0, 0, 255, 255), 2, cv.LINE_AA)
    cv.imwrite('debug_1.png', dst)
    dst = cv.imread(image_file, cv.IMREAD_COLOR)
    for i, contour in enumerate(contours):

        img = cv.drawContours(src, contours, i, (0,255,0), 3)
        cv.imshow("out"+str(i), img)
        cv.waitKey(0)
        
        # 小さな領域の場合は間引く
        area = cv.contourArea(contour)
        if area < 500:
            continue
        # 画像全体を占める領域は除外する
        if image_size * 0.99 < area:
            continue
        
        # 外接矩形を取得
        x,y,w,h = cv.boundingRect(contour)
        dst = cv.rectangle(dst,(x,y),(x+w,y+h),(0,255,0),2)
    # 結果を保存
    cv.imwrite('result.png', dst)
    cv.destroyAllWindows()
    
if __name__ == '__main__':
    main()

コメント

このブログの人気の投稿

Python OpenCVとWebカメラでバーコードリーダー

OpenCV 画像の足し算

OpenCV3とPython3で形状のある物体の輪郭と方向を認識する(主成分分析:PCA、固有ベクトル)