ラべリング(ブロブ情報付き)

V3.0.0
In [1]:
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import random

#Ipythonで表示用の設定
import matplotlib.pyplot as plt
%matplotlib inline

#画像生成(300x300 3ch)
height = 200
width  = 300
in_img = np.zeros((height,width,1),dtype='uint8')
out_img = np.zeros((height,width,3),dtype='uint8')

# 入力画像生成(文字の描画)
cv2.putText(in_img,"Take it easy!!",(10,100), cv2.FONT_HERSHEY_SIMPLEX, 1,(255),2)

#ラべリング
result = cv2.connectedComponentsWithStats(in_img)

print "ブロブ数:",result[0]
print "各ブロブを囲む矩形領域(左上座標、幅、高さ)、及び各ブロブの面積:\n",result[2]
print "各ブロブの中心座標:\n",result[3]

#ラベル数分の色を準備(ランダム)
colors = []
for i in range(1, result[0] + 1):
    colors.append(np.array([random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]))

#ラベル画像をもとに色づけ
for y in range(0, height):
    for x in range(0, width):
        if result[1][y, x] > 0:
            out_img[y, x] = colors[result[1][y, x]]
        else:
            out_img[y, x] = [0, 0, 0]

#RGBに変換
disp_in_img  = cv2.cvtColor(in_img,  cv2.COLOR_GRAY2RGB)
disp_out_img = cv2.cvtColor(out_img,  cv2.COLOR_BGR2RGB)
   
#画像表示
plt.figure(figsize=(16,8))
plt.subplot(121)
plt.imshow(disp_in_img)
plt.subplot(122)
plt.imshow(disp_out_img)
ブロブ数: 16
各ブロブを囲む矩形領域(左上座標、幅、高さ)、及び各ブロブの面積:
[[    0     0   300   200 58653]
 [   98    77     5     5    21]
 [   10    78    17    24   108]
 [   48    78    14    24   146]
 [  105    78    11    24    93]
 [  206    78     3    17    47]
 [  216    78     3    17    47]
 [   28    85    15    17   138]
 [   64    85    15    17   147]
 [   99    85     3    17    47]
 [  134    85    15    17   147]
 [  152    85    15    17   138]
 [  171    85    14    17   117]
 [  186    85    16    24   109]
 [  205    97     5     5    21]
 [  215    97     5     5    21]]
各ブロブの中心座標:
[[ 150.28354901   99.67989702]
 [ 100.           79.        ]
 [  18.           85.59259259]
 [  52.79452055   91.32876712]
 [ 109.68817204   89.75268817]
 [ 207.           86.        ]
 [ 217.           86.        ]
 [  35.73913043   93.        ]
 [  70.9047619    92.79591837]
 [ 100.           93.        ]
 [ 140.9047619    92.79591837]
 [ 159.73913043   93.        ]
 [ 177.64102564   92.94017094]
 [ 193.00917431   95.90825688]
 [ 207.           99.        ]
 [ 217.           99.        ]]

Out[1]:
<matplotlib.image.AxesImage at 0x584b7d0>

inserted by FC2 system