HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
장지원 페이지/
📕
2024 UGRP
/
Member Page
Member Page
/
장지원
장지원
/
#18. MOAT 모델 돌려보기 (X)

#18. MOAT 모델 돌려보기 (X)

태그
연구
날짜
May 15, 2024
상태
완료
 

[정리]

모델 설명
object detection, segmentation 하는 모
코드 설명
import
import collections import os import tempfile import copy from matplotlib import gridspec from matplotlib import pyplot as plt import numpy as np from PIL import Image import urllib import tensorflow as tf from google.colab import files
(import os를 다들 하는 것 같다..)
COCO_META = [ { 'color': [220, 20, 60], 'isthing': 1, 'id': 1, 'name': 'person' }, { 'color': [119, 11, 32], 'isthing': 1, 'id': 2, 'name': 'bicycle' }, ...
COCO dataset 업로드 (color는 따로 추가한 건가?)
COCO data set(Common Objects in Context) 다운로드와 구성요소 및 시각화 코드 (tistory.com)
DatasetInfo = collections.namedtuple( 'DatasetInfo', 'num_classes, label_divisor, thing_list, colormap, class_names') def _coco_label_colormap(): """Creates a label colormap used in COCO segmentation benchmark. See more about COCO dataset at https://cocodataset.org/ Tsung-Yi Lin, et al. "Microsoft COCO: Common Objects in Context." ECCV. 2014. Returns: A 2-D numpy array with each row being mapped RGB color (in uint8 range). """ colormap = np.zeros((256, 3), dtype=np.uint8) for category in COCO_META: colormap[category['id']] = category['color'] return colormap def _coco_class_names(): return ('void',) + tuple([x['name'] for x in COCO_META]) def coco_dataset_information(): return DatasetInfo( num_classes=134, label_divisor=256, thing_list=tuple(range(1, 81)), colormap=_coco_label_colormap(), class_names=_coco_class_names()) def perturb_color(color, noise, used_colors, max_trials=50, random_state=None): """Pertrubs the color with some noise. If `used_colors` is not None, we will return the color that has not appeared before in it. Args: color: A numpy array with three elements [R, G, B]. noise: Integer, specifying the amount of perturbing noise (in uint8 range). used_colors: A set, used to keep track of used colors. max_trials: An integer, maximum trials to generate random color. random_state: An optional np.random.RandomState. If passed, will be used to generate random numbers. Returns: A perturbed color that has not appeared in used_colors. """ if random_state is None: random_state = np.random for _ in range(max_trials): random_color = color + random_state.randint( low=-noise, high=noise + 1, size=3) random_color = np.clip(random_color, 0, 255) if tuple(random_color) not in used_colors: used_colors.add(tuple(random_color)) return random_color print('Max trial reached and duplicate color will be used. Please consider ' 'increase noise in `perturb_color()`.') return random_color def color_panoptic_map(panoptic_prediction, dataset_info, perturb_noise): """Helper method to colorize output panoptic map. Args: panoptic_prediction: A 2D numpy array, panoptic prediction from deeplab model. dataset_info: A DatasetInfo object, dataset associated to the model. perturb_noise: Integer, the amount of noise (in uint8 range) added to each instance of the same semantic class. Returns: colored_panoptic_map: A 3D numpy array with last dimension of 3, colored panoptic prediction map. used_colors: A dictionary mapping semantic_ids to a set of colors used in `colored_panoptic_map`. """ if panoptic_prediction.ndim != 2: raise ValueError('Expect 2-D panoptic prediction. Got {}'.format( panoptic_prediction.shape)) semantic_map = panoptic_prediction // dataset_info.label_divisor instance_map = panoptic_prediction % dataset_info.label_divisor height, width = panoptic_prediction.shape colored_panoptic_map = np.zeros((height, width, 3), dtype=np.uint8) used_colors = collections.defaultdict(set) # Use a fixed seed to reproduce the same visualization. random_state = np.random.RandomState(0) unique_semantic_ids = np.unique(semantic_map) for semantic_id in unique_semantic_ids: semantic_mask = semantic_map == semantic_id if semantic_id in dataset_info.thing_list: # For `thing` class, we will add a small amount of random noise to its # correspondingly predefined semantic segmentation colormap. unique_instance_ids = np.unique(instance_map[semantic_mask]) for instance_id in unique_instance_ids: instance_mask = np.logical_and(semantic_mask, instance_map == instance_id) random_color = perturb_color( dataset_info.colormap[semantic_id], perturb_noise, used_colors[semantic_id], random_state=random_state) colored_panoptic_map[instance_mask] = random_color else: # For `stuff` class, we use the defined semantic color. colored_panoptic_map[semantic_mask] = dataset_info.colormap[semantic_id] used_colors[semantic_id].add(tuple(dataset_info.colormap[semantic_id])) return colored_panoptic_map, used_colors def vis_segmentation(image, panoptic_prediction, dataset_info, perturb_noise=60): """Visualizes input image, segmentation map and overlay view.""" plt.figure(figsize=(30, 20)) grid_spec = gridspec.GridSpec(2, 2) ax = plt.subplot(grid_spec[0]) plt.imshow(image) plt.axis('off') ax.set_title('input image', fontsize=20) ax = plt.subplot(grid_spec[1]) panoptic_map, used_colors = color_panoptic_map(panoptic_prediction, dataset_info, perturb_noise) plt.imshow(panoptic_map) plt.axis('off') ax.set_title('panoptic map', fontsize=20) ax = plt.subplot(grid_spec[2]) plt.imshow(image) plt.imshow(panoptic_map, alpha=0.7) plt.axis('off') ax.set_title('panoptic overlay', fontsize=20) ax = plt.subplot(grid_spec[3]) max_num_instances = max(len(color) for color in used_colors.values()) # RGBA image as legend. legend = np.zeros((len(used_colors), max_num_instances, 4), dtype=np.uint8) class_names = [] for i, semantic_id in enumerate(sorted(used_colors)): legend[i, :len(used_colors[semantic_id]), :3] = np.array( list(used_colors[semantic_id])) legend[i, :len(used_colors[semantic_id]), 3] = 255 if semantic_id < dataset_info.num_classes: class_names.append(dataset_info.class_names[semantic_id]) else: class_names.append('ignore') plt.imshow(legend, interpolation='nearest') ax.yaxis.tick_left() plt.yticks(range(len(legend)), class_names, fontsize=15) plt.xticks([], []) ax.tick_params(width=0.0, grid_linewidth=0.0) plt.grid('off') plt.show()
segmentation(?)
MODEL_NAME = 'resnet50_kmax_deeplab_coco_train' # @param ['resnet50_kmax_deeplab_coco_train','axial_resnet50_kmax_deeplab_coco_train','convnext_tiny_kmax_deeplab_coco_train','convnext_small_kmax_deeplab_coco_train','convnext_base_kmax_deeplab_coco_train','convnext_large_kmax_deeplab_coco_train','convnext_large_kmax_deeplab_coco_train_unlabeled'] _MODELS = ('resnet50_kmax_deeplab_coco_train', 'axial_resnet50_kmax_deeplab_coco_train', 'convnext_tiny_kmax_deeplab_coco_train', 'convnext_small_kmax_deeplab_coco_train', 'convnext_base_kmax_deeplab_coco_train', 'convnext_large_kmax_deeplab_coco_train', 'convnext_large_kmax_deeplab_coco_train_unlabeled' ) _DOWNLOAD_URL_PATTERN = 'https://storage.googleapis.com/gresearch/tf-deeplab/saved_model/%s.tar.gz' _MODEL_NAME_TO_URL_AND_DATASET = { model: (_DOWNLOAD_URL_PATTERN % model, coco_dataset_information()) for model in _MODELS } MODEL_URL, DATASET_INFO = _MODEL_NAME_TO_URL_AND_DATASET[MODEL_NAME]
모델 정의
model_dir = tempfile.mkdtemp() download_path = os.path.join(model_dir, MODEL_NAME + '.gz') urllib.request.urlretrieve(MODEL_URL, download_path) !tar -xzvf {download_path} -C {model_dir} LOADED_MODEL = tf.saved_model.load(os.path.join(model_dir, MODEL_NAME))
모델 로딩
# Required, upload an image from your local machine. uploaded = files.upload() if not uploaded: raise AssertionError('Please upload one image') elif len(uploaded) == 1: UPLOADED_FILE = list(uploaded.keys())[0] else: raise AssertionError('Please upload one image at a time')
이미지 업로드
with tf.io.gfile.GFile(UPLOADED_FILE, 'rb') as f: im = np.array(Image.open(f)) output = LOADED_MODEL(tf.cast(im, tf.uint8)) vis_segmentation(im, output['panoptic_pred'][0], DATASET_INFO)
결과 추출
결과