TD(webcam)→python(Deeplab)→TDする

前回の続き

TD側

videoDeviceOut->SpoutOut(senderName=input)で設定
SpoutIn(senderName=output)で設定

Python側

前回のwebcam用deeplabのコードを参考に変更させていただく。

モデルをローカルから読み込む
サンプルままだとwebからモデルをダウンロードしてたので、ローカルに落として毎回そこから読み込みたい。

コード内モデルダウンロードのところをコメント

## Select and download models
"""
_MODEL_URLS = {
   'mobilenetv2_coco_voctrainaug':'http://download.tensorflow.org/models/deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz',
   'mobilenetv2_coco_voctrainval':'http://download.tensorflow.org/models/deeplabv3_mnv2_pascal_trainval_2018_01_29.tar.gz',
   'xception_coco_voctrainaug': 'http://download.tensorflow.org/models/deeplabv3_pascal_train_aug_2018_01_04.tar.gz',
   'xception_coco_voctrainval': 'http://download.tensorflow.org/models/deeplabv3_pascal_trainval_2018_01_04.tar.gz',
}

_TARBALL_NAME = 'deeplab_model.tar.gz'

## fast model
model_url = _MODEL_URLS['mobilenetv2_coco_voctrainaug']
## accurate model #model_url  = _MODEL_URLS['xception_coco_voctrainaug']

model_dir = tempfile.mkdtemp()
tf.io.gfile.makedirs(model_dir)

download_path = os.path.join(model_dir, _TARBALL_NAME)
print('downloading model to %s, this might take a while...' % download_path)
urllib.request.urlretrieve(model_url, download_path)
print('download completed!')
"""

代わりにコード内のモデルリンクからダウンロードしてdeeplab内にmodelsファイルを作成して中に配置した。

##  Select local models
download_path = 'models/deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz' #download_path  = 'deeplabv3_pascal_train_aug_2018_01_04.tar.gz'


SpoutForPythonの追加

セットアップは前回ページ参照

Libraryフォルダをdeeplab階層に移動させる。

コードの追加

# load spout
from Library.Spout import Spout

spout sender, receiver作成

# create spout object
spout = Spout(silent = False)
# create receiver
spout.createReceiver('input')
# create sender
spout.createSender('output')

receiverで受け取り、PILへ渡す。あとは従来通りseg_imageを生成

while True:

   # From Spout to PIL
   data = spout.receive()
   pil_im = Image.fromarray(data)

   # Run model
   resized_im, seg_map = model.run(pil_im)
   
   # Adjust color of mask
   seg_image = get_dataset_colormap.label_to_color_image(
       seg_map, get_dataset_colormap.get_pascal_name()).astype(np.uint8)
       
   #show  seg_image
   #cv2 .imshow('frame', seg_image)

seg_imageをcvに変換、リサイズしてspoutでsend

 #Convert  PIL seg_image back to cv2 and resize
   frame = np.array(seg_image)
   r = data.shape[1] / frame.shape[1]
   dim = (int(frame.shape[0] * r), data.shape[1])[::-1]
   resized = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
   resized = cv2.cvtColor(resized, cv2.COLOR_RGB2BGR)

   # check on close window
   spout.check()

   # send data
   spout.send(resized)

これでOK。あとはTD側で煮るなり焼くなり。



この記事が気に入ったらサポートをしてみませんか?