카테고리 없음

Mask R-CNN with TensorFlow 2.4.0 on Windows 10

Wood Pecker 2021. 9. 30. 00:02

1. 개요

Mask R-CNN은 Deep Learing Network로 이미지 영상에서 물체를 분류(Classification)하고 분류 영역을 MASK하고 분류영역의 Bounding Box를 알아낼 수 있다. 인터넷에 많은 버전이 있으나 실행이 다소 까다롭다. 내 PC의 설정환경에 맞는 버전을 구하여 실행하여야 한다.

 

2. 설치

아래 다운로드 싸이트에서 프로그램을 받는다. 프로젝트를 생성한다(예, PyCharm virtual 개발환경).

python version은 3.6로 설정한다. 처음에는 python 3.9로 시작하였으나 tensorflow 2.5이상만 사용이 가능하며 CuDNN 8.1.0을 사용하여야 하는가 보다. 실행시에 발생하는 오류를 해결하지 못하고 결국 돌고 돌아 버전을 낮추었다. 이 프로그램은 GPU를 사용한다.

 

[다운로드] https://github.com/akTwelve/Mask_RCNN.git aktwelve_mask_rcnn

[참고] https://www.immersivelimit.com/tutorials/mask-rcnn-for-windows-10-tensorflow-2-cuda-101

 

Mask R-CNN with TensorFlow 2 + Windows 10 Tutorial — Immersive Limit

Matterport's Mask R-CNN, updated for TensorFlow 2.2, plus a tutorial for setup on Windows 10 (using Anaconda) with CUDA support.

www.immersivelimit.com

 

3. 필요한 라이브러리 설치 ( 버전에 따라 영향을 많이 받는다 ㅠㅠ)
       >python setup.py clean --all install
       > pip install -r requirements.txt
       > pip install tensorflow==2.4.0 
       > pip3 install torch==1.9.1+cu111 torchvision==0.10.1+cu111 torchaudio===0.9.1 -f 
             
https://download.pytorch.org/whl/torch\_stable.html

 

   cuda를 지원하는 pytorch를 설치한다.    pytorch.org

4. Pretrained Data 얻어 오기
        mask_rcnn_coco.h5 파일을 프로젝트 실행 코드(아래에서 작성) 폴더에 저장.

         https://github.com/matterport/Mask_RCNN/releases

 

5. 소스 수정 (버전에 따른 문제)

  mode.py 의 353라인 부근의   tf.log(x) / tf.log(2.0) 부분을 아래와 같이 수정한다.

      ==> tf.math.log(x) / tf.math.log(2.0)

 

mode.py 의 955라인 부근의 다음코드를  아래와 같이 수정한다(Option). 

    mrcnn\_bbox = KL.Reshape((s\[1\], num\_classes, 4), name\="mrcnn\_bbox")(x)
    ==> 수정
         if s\[1\] == None:  
               mrcnn\_bbox = KL.Reshape((-1, num\_classes, 4), name="mrcnn\_bbox")(x)  
         else:  
               mrcnn\_bbox = KL.Reshape((s\[1\], num\_classes, 4), name="mrcnn\_bbox")(x)

 

6.  다음 코드를 작성하고 실행한다.

import os
import cv2
import random
import skimage.io
import matplotlib.pyplot as plt
from  samples.coco import coco
import mrcnn.model as modellib
from mrcnn import visualize
import torch
import tensorflow as tf

class InferenceConfig(coco.CocoConfig):  
    # Set batch size to 1 since we'll be running inference on  
    # one image at a time. Batch size = GPU\_COUNT \* IMAGES\_PER\_GPU  
    # GPU_COUNT = 0 for CPU  
    GPU_COUNT = 1  
    IMAGES_PER_GPU = 1  
    BATCH_SIZE = 1

def checkGPU():
    print(tf.__version__)
    print("gpu_device_name =>"+ tf.test.gpu_device_name())
    print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
    #check with torch
    isAvailable= torch.cuda.is_available()
    print("cuda is available ? ",  isAvailable)
    if isAvailable:
        count= torch.cuda.device_count()
        print("cuda number of device =",count)
        for index in range(0,count):
            print("cuda device_name(0)", torch.cuda.get_device_name(0))
        return True
    else:
        return False

if __name__ == '__main__':  
    isAvailable =checkGPU()
    if not isAvailable:
       exit(0)

    ROOT_DIR = os.getcwd()
    COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
    IMAGE_DIR = os.path.join(ROOT_DIR, "images")

    config = InferenceConfig()
    config.display()

    model = modellib.MaskRCNN(mode="inference", model_dir='./log', config=config)
    model.load_weights('mask_rcnn_coco.h5', by_name=True)
    class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
                   'bus', 'train', 'truck', 'boat', 'traffic light',
                   'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
                   'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
                   'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
                   'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
                   'kite', 'baseball bat', 'baseball glove', 'skateboard',
                   'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
                   'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
                   'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
                   'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
                   'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
                   'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
                   'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
                   'teddy bear', 'hair drier', 'toothbrush']

    image = cv2.imread("./images/4410436637_7b0ca36ee7_z.jpg")
    cv2.imshow('Image', image)
    if cv2.waitKey(1000) == 27:
        exit(0)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    # Run detection
    results = model.detect([image], verbose=1)

    # Visualize results
    r = results[0]
    visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],class_names, r['scores'])
    pass

 

7. 실행결과

 

반응형