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

OpenCV + Pythonで特定の図形を検出する1(図形の領域を矩形で取得)
確かにここの輪郭を検出しているようだ。
タイトル
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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カメラでバーコードリーダー

VB.net Dictionaryクラスの初期化