ラべリング

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)

#ラべリング
num_Labels, labeled_Image  = cv2.connectedComponents(in_img)

#ラベル数分の色を準備(ランダム)
colors = []
for i in range(1, num_Labels + 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 labeled_Image[y, x] > 0:
            out_img[y, x] = colors[labeled_Image[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)
Out[1]:
<matplotlib.image.AxesImage at 0x585b450>

inserted by FC2 system