File size: 5,789 Bytes
fce70ef |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
import os
import sys
import random
import math
import re
import time
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import pdb
from sklearn.model_selection import train_test_split
import glob
# Root directory of the project
ROOT_DIR = os.path.abspath("./Mask_RCNN/")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn.config import Config
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
from mrcnn.model import log
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
class MineSectorConfig(Config):
"""Configuration for training on the toy shapes dataset.
Derives from the base Config class and overrides values specific
to the toy shapes dataset.
"""
# Give the configuration a recognizable name
NAME = "mining-sectors"
# Train on 1 GPU and 8 images per GPU. We can put multiple images on each
# GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
GPU_COUNT = 1
IMAGES_PER_GPU = 8
# Number of classes (including background)
NUM_CLASSES = 1 + 9 # background + 3 shapes
# Use small images for faster training. Set the limits of the small side
# the large side, and that determines the image shape.
IMAGE_MIN_DIM = 128
IMAGE_MAX_DIM = 128
# Use smaller anchors because our image and objects are small
RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128) # anchor side in pixels
# Reduce training ROIs per image because the images are small and have
# few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
TRAIN_ROIS_PER_IMAGE = 32
# Use a small epoch since the data is simple
STEPS_PER_EPOCH = 100
# use small validation steps since the epoch is small
VALIDATION_STEPS = 5
config = MineSectorConfig()
config.display()
class MineSectDataset(utils.Dataset):
def __init__(self, path):
self.path = path
self.mine_ids = []
def load_mine_sectors(self):
"""Generate the requested number of synthetic images.
count: number of images to generate.
height, width: the size of the generated images.
"""
self.add_class("shapes", 1, "square")
self.add_class("shapes", 2, "circle")
self.add_class("shapes", 3, "triangle")
# Add classes
'''
self.add_class("mine_sector", 3, "lh")
self.add_class("mine_sector", 4, "mf")
self.add_class("mine_sector", 5, "op")
self.add_class("mine_sector", 6, "pp")
self.add_class("mine_sector", 7, "sy")
self.add_class("mine_sector", 8, "tsf")
self.add_class("mine_sector", 9, "wr")
'''
# Add images
# Generate random specifications of images (i.e. color and
# list of shapes sizes and locations). This is more compact than
# actual images. Images are generated on the fly in load_image().
df = create_df()
print('Total Images: ', len(df))
mine_ids = np.array([])
# split mines into train, valid and test
# get unique mine ids
for patch in df['id'].values:
mine_id = int(patch.split(".")[0])
if mine_id not in mine_ids:
self.mine_ids = np.append(self.mine_ids, mine_id)
def load_image(self, filename):
# loads the image from a file, but
pdb.set_trace()
fpath = os.path.join(self.path, filename)
image = cv2.imread(fpath)
return image
def load_mask(self, filename):
# loads the image from a file, but
pdb.set_trace()
fpath = os.path.join(self.path, filename)
image = cv2.imread(fpath)
return image
def image_reference(self, image_id):
"""Return the shapes data of the image."""
info = self.image_info[image_id]
if info["source"] == "shapes":
return info["shapes"]
else:
super(self.__class__).image_reference(self, image_id)
IMG_PATH = 'dataset/images/'
MASK_PATH = 'dataset/masks/'
batch_size = 32
num_classes = 10
# create dataframe to get the image name/index in order
def create_df():
name = []
for dir, subdir, filenames in os.walk(IMG_PATH):
for filename in filenames:
name.append(filename[:-4])
return pd.DataFrame({'id': name}, index=np.arange(0, len(name)))
if __name__ == "__main__":
# pdb.set_trace()
mine_sect_ds = MineSectDataset(IMG_PATH)
mine_sect_ds.load_mine_sectors()
mine_sect_ds.load_image(mine_sect_ds.mine_ids[0])
MID_trainval, MID_test = train_test_split(mine_ids, test_size=0.15, random_state=42)
MID_train, MID_val = train_test_split(MID_trainval, test_size=0.25, random_state=42)
X_train = np.array([])
for id in MID_train:
X_train = np.append(X_train, np.transpose([os.path.basename(x) for x in glob.glob(os.path.join(IMG_PATH, str(int(id)) + "*.tif"))]))
X_val = np.array([])
for id in MID_val:
X_val = np.append(X_val, np.transpose([os.path.basename(x) for x in glob.glob(os.path.join(IMG_PATH, str(int(id)) + "*.tif"))]))
X_test = np.array([])
for id in MID_test:
X_test = np.append(X_test, np.transpose([os.path.basename(x) for x in glob.glob(os.path.join(IMG_PATH, str(int(id)) + "*.tif"))]))
print('Train Size: ', len(X_train))
print('Validation Size: ', len(X_val))
print('Test Size: ', len(X_test))
|