Link OpenCV API Reference
# -*- 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)