Upload 17 files
Browse files- LSM_Chile_sectors_class.geojson +0 -0
- LSM_Chile_sectors_class_epsg3857.geojson +0 -0
- check_img-vs-msk_size.py +35 -0
- crop-to-tiles.sh +10 -0
- crop-to-tiles_masks.sh +10 -0
- docker-run.sh +1 -0
- extract_mapbox_files.py +50 -0
- keras_seg.py +523 -0
- keras_seg_cats_dogs.py +253 -0
- mask-rcnn.py +378 -0
- pad-files.py +41 -0
- pytorch_seg.py +23 -0
- requirements.txt +13 -0
- run.py +194 -0
- run_maskrcnn.sh +2 -0
- seg_stats.py +56 -0
- subset.py +60 -0
LSM_Chile_sectors_class.geojson
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
LSM_Chile_sectors_class_epsg3857.geojson
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
check_img-vs-msk_size.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import os
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import subprocess
|
| 5 |
+
import pdb
|
| 6 |
+
from osgeo import gdal
|
| 7 |
+
import operator
|
| 8 |
+
|
| 9 |
+
# checks if a mask-patch exists for each image-patch and the pixel size equals
|
| 10 |
+
|
| 11 |
+
path_images = "/home/maduschek/DATA/mine-sector-detection/patches_img_trainset/"
|
| 12 |
+
path_masks = "/home/maduschek/DATA/mine-sector-detection/patches_mask_trainset/"
|
| 13 |
+
|
| 14 |
+
filecount = len(glob.glob(path_images + "*.png"))
|
| 15 |
+
print("file count: ", str(filecount))
|
| 16 |
+
|
| 17 |
+
# pdb.set_trace()
|
| 18 |
+
i = 0
|
| 19 |
+
for img, msk in zip(sorted(glob.glob(path_images + "*.png")), sorted(glob.glob(path_masks + "*.png"))):
|
| 20 |
+
|
| 21 |
+
ds_img = gdal.Open(img)
|
| 22 |
+
ds_msk = gdal.Open(msk)
|
| 23 |
+
|
| 24 |
+
i += 1
|
| 25 |
+
if i % 1000 == 0:
|
| 26 |
+
print(str(i), " / ", str(filecount))
|
| 27 |
+
|
| 28 |
+
if ds_img.RasterXSize != ds_msk.RasterXSize or ds_img.RasterYSize != ds_msk.RasterYSize:
|
| 29 |
+
print("###################################################")
|
| 30 |
+
print(img, " ", msk)
|
| 31 |
+
print("image-size: ", ds_img.RasterXSize, "x", ds_img.RasterYSize, " mask-size: ", ds_msk.RasterXSize, "x", ds_msk.RasterYSize)
|
| 32 |
+
print(" ")
|
| 33 |
+
input("press")
|
| 34 |
+
|
| 35 |
+
|
crop-to-tiles.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
TARGDIR="/home/maduschek/ssd/mine-sector-detection/images_trainset/"
|
| 2 |
+
FILES="/home/maduschek/ssd/mine-sector-detection/images/*.jp2"
|
| 3 |
+
|
| 4 |
+
mkdir -p $TARGDIR
|
| 5 |
+
|
| 6 |
+
for f in $FILES
|
| 7 |
+
do
|
| 8 |
+
echo "Processing file $f"
|
| 9 |
+
/usr/bin/gdal_retile.py -resume -v -ps 256 256 -overlap 128 -of PNG -targetDir $TARGDIR $f
|
| 10 |
+
done
|
crop-to-tiles_masks.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
TARGDIR="/home/maduschek/ssd/mine-sector-detection/masks_trainset/"
|
| 2 |
+
FILES="/home/maduschek/ssd/mine-sector-detection/masks/*.tif"
|
| 3 |
+
|
| 4 |
+
mkdir -p $TARGDIR
|
| 5 |
+
|
| 6 |
+
for f in $FILES
|
| 7 |
+
do
|
| 8 |
+
echo "Processing file $f"
|
| 9 |
+
/usr/bin/gdal_retile.py -v -ps 256 256 -overlap 128 -of PNG -targetDir $TARGDIR $f
|
| 10 |
+
done
|
docker-run.sh
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
sudo docker run -it -v /home/maduschek:/home/maduschek osgeo/gdal:latest /bin/bash
|
extract_mapbox_files.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import os
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import subprocess
|
| 5 |
+
import pdb
|
| 6 |
+
from osgeo import gdal
|
| 7 |
+
|
| 8 |
+
# gdal_rasterize -l LSM_Chile_sectors_class_epsg3857 -a class -ts 25729.0 13441.0 -a_nodata 0.0 -te -7663806.3641 -2396313.3772 -7633077.4844 -2380260.4069 -ot Float32 -of GTiff "C:/Dropbox/TUM SIPEO/Projekte/RS mining facilities/L-ASM Mining Dataset/ds/LSM_Chile_sectors_class_epsg3857.geojson" C:/Users/matthias/AppData/Local/Temp/processing_KFVIRc/2f32c9c1db924811af36352bf5f8fdf4/OUTPUT.tif
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# creates mask files based on images and geojson file
|
| 12 |
+
|
| 13 |
+
Image.MAX_IMAGE_PIXELS = 10000000000
|
| 14 |
+
|
| 15 |
+
path_images = "C:/data/mine-sectors/mapbox_mines_0.8m_RGB/"
|
| 16 |
+
path_images = "../../ssd/mine-sector-detection/images/"
|
| 17 |
+
path_json = "./"
|
| 18 |
+
os.makedirs("./out", exist_ok=True)
|
| 19 |
+
|
| 20 |
+
# pdb.set_trace()
|
| 21 |
+
for file in sorted(glob.glob(path_images + "*.jp2")):
|
| 22 |
+
|
| 23 |
+
# pdb.set_trace()
|
| 24 |
+
ds = gdal.Open(file, gdal.GA_ReadOnly)
|
| 25 |
+
geoTransform = ds.GetGeoTransform()
|
| 26 |
+
minx = geoTransform[0]
|
| 27 |
+
maxy = geoTransform[3]
|
| 28 |
+
maxx = minx + geoTransform[1] * ds.RasterXSize
|
| 29 |
+
miny = maxy + geoTransform[5] * ds.RasterYSize
|
| 30 |
+
data = None
|
| 31 |
+
rb = (ds.GetRasterBand(1)).ReadAsArray()
|
| 32 |
+
pixelsize = str(rb.shape[1]) + " " + str(rb.shape[0])
|
| 33 |
+
|
| 34 |
+
print(file)
|
| 35 |
+
print([minx, miny, maxx, maxy])
|
| 36 |
+
print(pixelsize)
|
| 37 |
+
|
| 38 |
+
# "-te -7825738.2085 -2675527.0926 -7821399.2129 -2672659.5097 " \
|
| 39 |
+
|
| 40 |
+
string = "gdal_rasterize -l LSM_Chile_sectors_class_epsg3857 -a class -ts " + pixelsize + \
|
| 41 |
+
" -te " + str(minx) + " " + str(miny) + " " + str(maxx) + " " + str(maxy) + " " \
|
| 42 |
+
"-ot Byte -of GTiff '" + path_json + "LSM_Chile_sectors_class_epsg3857.geojson' " \
|
| 43 |
+
"./out/mask_" + os.path.basename(file)[:-4] + ".tif"
|
| 44 |
+
|
| 45 |
+
print(string)
|
| 46 |
+
# input("press enter")
|
| 47 |
+
|
| 48 |
+
os.system(string)
|
| 49 |
+
|
| 50 |
+
|
keras_seg.py
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import glob
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import pdb
|
| 7 |
+
import platform
|
| 8 |
+
# from IPython.display import display
|
| 9 |
+
from tensorflow.keras.preprocessing.image import load_img
|
| 10 |
+
from PIL import ImageOps, Image
|
| 11 |
+
from matplotlib import pyplot as plt
|
| 12 |
+
from tensorflow import keras
|
| 13 |
+
import tensorflow as tf
|
| 14 |
+
import numpy as np
|
| 15 |
+
from tensorflow.keras.preprocessing.image import load_img
|
| 16 |
+
from tensorflow.keras import layers
|
| 17 |
+
from imgrender import render
|
| 18 |
+
from sklearn.metrics import confusion_matrix
|
| 19 |
+
np.set_printoptions(edgeitems=30, linewidth=100000,
|
| 20 |
+
formatter=dict(float=lambda x: "%.3g" % x))
|
| 21 |
+
|
| 22 |
+
# TODO:
|
| 23 |
+
# The predicted output masks are somewhat working, but the output is not the class value (0-10), it is a proportional
|
| 24 |
+
# value from 0-1 * 255 (e.g. 3 -> 76 or 229 -> 9)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
'''
|
| 28 |
+
base_dir = "../../data/cats_dogs/"
|
| 29 |
+
input_dir_train = base_dir + "images/"
|
| 30 |
+
target_dir_train = base_dir + "annotations/trimaps"
|
| 31 |
+
input_dir_test = base_dir + "images/"
|
| 32 |
+
target_dir_test = base_dir + "annotations/trimaps"
|
| 33 |
+
img_size = (160, 160)
|
| 34 |
+
num_classes = 3
|
| 35 |
+
batch_size = 32
|
| 36 |
+
'''
|
| 37 |
+
|
| 38 |
+
# a priori knowledge
|
| 39 |
+
# class weights gained from seg_stats.py
|
| 40 |
+
class_weights = {0: 1,
|
| 41 |
+
1: 50.3606,
|
| 42 |
+
2: 195.0304,
|
| 43 |
+
3: 202.9463,
|
| 44 |
+
4: 64.3299,
|
| 45 |
+
5: 83.5509,
|
| 46 |
+
6: 745.9514,
|
| 47 |
+
7: 119.1049,
|
| 48 |
+
8: 41.1413,
|
| 49 |
+
9: 33.946,
|
| 50 |
+
10: 33216.4873}
|
| 51 |
+
|
| 52 |
+
# mine sectors
|
| 53 |
+
if platform.system() == "Windows":
|
| 54 |
+
base_dir = "C:/DATA/mine-sector-detection/"
|
| 55 |
+
else:
|
| 56 |
+
base_dir = "/home/maduschek/DATA/mine-sector-detection/"
|
| 57 |
+
# base_dir = "/home/maduschek/ssd/mine-sector-detection/DEBUG/"
|
| 58 |
+
|
| 59 |
+
# path to train and test set
|
| 60 |
+
input_dir_train = base_dir + "patches_img_trainset/"
|
| 61 |
+
target_dir_train = base_dir + "patches_mask_trainset/"
|
| 62 |
+
input_dir_test = base_dir + "patches_img_trainset/"
|
| 63 |
+
target_dir_test = base_dir + "patches_mask_trainset/"
|
| 64 |
+
img_size = (256, 256)
|
| 65 |
+
num_classes = 10
|
| 66 |
+
batch_size = 16
|
| 67 |
+
|
| 68 |
+
epochs = int(input("epochs: "))
|
| 69 |
+
subset_percent = float(input("subset_size in %: "))/100
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# load the image files
|
| 73 |
+
input_img_paths_train = sorted(
|
| 74 |
+
[
|
| 75 |
+
os.path.join(input_dir_train, fname)
|
| 76 |
+
for fname in os.listdir(input_dir_train)
|
| 77 |
+
if fname.endswith(".png")
|
| 78 |
+
]
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# load the mask files
|
| 82 |
+
target_img_paths_train = sorted(
|
| 83 |
+
[
|
| 84 |
+
os.path.join(target_dir_train, fname)
|
| 85 |
+
for fname in os.listdir(target_dir_train)
|
| 86 |
+
if fname.endswith(".png") and not fname.startswith(".")
|
| 87 |
+
]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# load the image files
|
| 91 |
+
input_img_paths_test = sorted(
|
| 92 |
+
[
|
| 93 |
+
os.path.join(input_dir_test, fname)
|
| 94 |
+
for fname in os.listdir(input_dir_test)
|
| 95 |
+
if fname.endswith(".png")
|
| 96 |
+
]
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# load the mask files
|
| 100 |
+
target_img_paths_test = sorted(
|
| 101 |
+
[
|
| 102 |
+
os.path.join(target_dir_test, fname)
|
| 103 |
+
for fname in os.listdir(target_dir_test)
|
| 104 |
+
if fname.endswith(".png") and not fname.startswith(".")
|
| 105 |
+
]
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# random subset for faster DEBUGGING
|
| 110 |
+
if subset_percent != 0:
|
| 111 |
+
np.random.seed(42)
|
| 112 |
+
subset_idx_train = (np.random.random(int(len(input_img_paths_train) * subset_percent)) * len(input_img_paths_train)).astype(int)
|
| 113 |
+
input_img_paths_train = np.asarray(input_img_paths_train)[subset_idx_train]
|
| 114 |
+
target_img_paths_train = np.asarray(target_img_paths_train)[subset_idx_train]
|
| 115 |
+
|
| 116 |
+
np.random.seed(42)
|
| 117 |
+
subset_idx_test = (np.random.random(int(len(input_img_paths_test) * subset_percent)) * len(input_img_paths_test)).astype(int)
|
| 118 |
+
input_img_paths_test = np.asarray(input_img_paths_test)[subset_idx_test]
|
| 119 |
+
target_img_paths_test = np.asarray(target_img_paths_test)[subset_idx_test]
|
| 120 |
+
|
| 121 |
+
print("Number of train samples:", len(input_img_paths_train))
|
| 122 |
+
for i in range(5):
|
| 123 |
+
print(input_img_paths_train[i])
|
| 124 |
+
print("...")
|
| 125 |
+
print("Number of test samples:", len(input_img_paths_test))
|
| 126 |
+
for i in range(5):
|
| 127 |
+
print(input_img_paths_test[i])
|
| 128 |
+
print("...")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# show image and its mask
|
| 132 |
+
for input_path, target_path in zip(input_img_paths_train[:], target_img_paths_train[:]):
|
| 133 |
+
arr = np.array(Image.open(target_path))
|
| 134 |
+
|
| 135 |
+
# the following step is necessarey becaus all 0 valued mask-pixels are set to 255
|
| 136 |
+
# if arr.min() == 0:
|
| 137 |
+
# print(target_path, " mask pixels +1")
|
| 138 |
+
# Image.fromarray(arr + 1).save(target_path)
|
| 139 |
+
|
| 140 |
+
# if arr.max() > 3 or len(arr.shape) > :
|
| 141 |
+
# print(input_path, "|", target_path, " max: ", str(arr.max()))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
if False:
|
| 145 |
+
rnd_idx = (np.random.random(10)*len(input_img_paths_train)).astype(int)
|
| 146 |
+
for i in rnd_idx:
|
| 147 |
+
os.system('clear')
|
| 148 |
+
render(os.path.join(input_img_paths_train[i]), scale=(128, 128))
|
| 149 |
+
print(input_img_paths_train[i])
|
| 150 |
+
print("---------------------------------------")
|
| 151 |
+
|
| 152 |
+
mask = Image.open(os.path.join(target_img_paths_train[i]))
|
| 153 |
+
ImageOps.autocontrast(mask).save(
|
| 154 |
+
os.path.join("./", "mask_contrast" + str(i) + ".png"))
|
| 155 |
+
render(os.path.join("./", "mask_contrast" + str(i) + ".png"), scale=(128, 128))
|
| 156 |
+
print(target_img_paths_train[i])
|
| 157 |
+
time.sleep(5)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class MineSectorHelper(keras.utils.Sequence):
|
| 162 |
+
"""Helper to iterate over the data (as Numpy arrays)."""
|
| 163 |
+
|
| 164 |
+
def __init__(self, batch_size, img_size, input_img_paths, target_img_paths):
|
| 165 |
+
self.batch_size = batch_size
|
| 166 |
+
self.img_size = img_size
|
| 167 |
+
self.input_img_paths = input_img_paths
|
| 168 |
+
self.target_img_paths = target_img_paths
|
| 169 |
+
|
| 170 |
+
def __len__(self):
|
| 171 |
+
return len(self.target_img_paths) // self.batch_size
|
| 172 |
+
|
| 173 |
+
def __getitem__(self, idx):
|
| 174 |
+
"""Returns tuple (input, target) correspond to batch #idx."""
|
| 175 |
+
i = idx * self.batch_size
|
| 176 |
+
batch_input_img_paths = self.input_img_paths[i: i + self.batch_size]
|
| 177 |
+
batch_target_img_paths = self.target_img_paths[i: i + self.batch_size]
|
| 178 |
+
|
| 179 |
+
x = np.zeros((self.batch_size,) + self.img_size + (3,), dtype="uint8")
|
| 180 |
+
for j, path in enumerate(batch_input_img_paths):
|
| 181 |
+
# print(path)
|
| 182 |
+
img = load_img(path, target_size=self.img_size)
|
| 183 |
+
x[j] = img
|
| 184 |
+
|
| 185 |
+
y = np.zeros((self.batch_size,) + self.img_size + (1,), dtype="uint8")
|
| 186 |
+
for j, path in enumerate(batch_target_img_paths):
|
| 187 |
+
img = load_img(path, target_size=self.img_size, color_mode="grayscale")
|
| 188 |
+
y[j] = np.expand_dims(img, 2)
|
| 189 |
+
# Ground truth labels are 1, 2, 3. Subtract one to make them 0, 1, 2:
|
| 190 |
+
# y[j] -= 1
|
| 191 |
+
|
| 192 |
+
w = generate_sample_weights(y, class_weights)
|
| 193 |
+
|
| 194 |
+
return x, y, w
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def get_item(idx):
|
| 198 |
+
"""Returns tuple (input, target) correspond to batch #idx."""
|
| 199 |
+
i = idx * self.batch_size
|
| 200 |
+
batch_input_img_paths = self.input_img_paths[i: i + self.batch_size]
|
| 201 |
+
batch_target_img_paths = self.target_img_paths[i: i + self.batch_size]
|
| 202 |
+
x = np.zeros((self.batch_size,) + self.img_size + (3,), dtype="uint8")
|
| 203 |
+
|
| 204 |
+
for j, path in enumerate(batch_input_img_paths):
|
| 205 |
+
# print(path)
|
| 206 |
+
img = load_img(path, target_size=self.img_size)
|
| 207 |
+
x[j] = img
|
| 208 |
+
y = np.zeros((self.batch_size,) + self.img_size + (1,), dtype="uint8")
|
| 209 |
+
|
| 210 |
+
for j, path in enumerate(batch_target_img_paths):
|
| 211 |
+
img = load_img(path, target_size=self.img_size, color_mode="grayscale")
|
| 212 |
+
y[j] = np.expand_dims(img, 2)
|
| 213 |
+
# Ground truth labels are 1, 2, 3. Subtract one to make them 0, 1, 2:
|
| 214 |
+
y[j] -= 1
|
| 215 |
+
return x, y
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def get_model(img_size, num_classes):
|
| 219 |
+
inputs = keras.Input(shape=img_size + (3,))
|
| 220 |
+
|
| 221 |
+
### [First half of the network: downsampling inputs] ###
|
| 222 |
+
|
| 223 |
+
# Entry block
|
| 224 |
+
x = layers.Conv2D(32, 3, strides=2, padding="same")(inputs)
|
| 225 |
+
x = layers.BatchNormalization()(x)
|
| 226 |
+
x = layers.Activation("relu")(x)
|
| 227 |
+
|
| 228 |
+
previous_block_activation = x # Set aside residual
|
| 229 |
+
|
| 230 |
+
# Blocks 1, 2, 3 are identical apart from the feature depth.
|
| 231 |
+
for filters in [64, 128, 256]:
|
| 232 |
+
x = layers.Activation("relu")(x)
|
| 233 |
+
x = layers.SeparableConv2D(filters, 3, padding="same")(x)
|
| 234 |
+
x = layers.BatchNormalization()(x)
|
| 235 |
+
|
| 236 |
+
x = layers.Activation("relu")(x)
|
| 237 |
+
x = layers.SeparableConv2D(filters, 3, padding="same")(x)
|
| 238 |
+
x = layers.BatchNormalization()(x)
|
| 239 |
+
|
| 240 |
+
x = layers.MaxPooling2D(3, strides=2, padding="same")(x)
|
| 241 |
+
|
| 242 |
+
# Project residual
|
| 243 |
+
residual = layers.Conv2D(filters, 1, strides=2, padding="same")(
|
| 244 |
+
previous_block_activation
|
| 245 |
+
)
|
| 246 |
+
x = layers.add([x, residual]) # Add back residual
|
| 247 |
+
previous_block_activation = x # Set aside next residual
|
| 248 |
+
|
| 249 |
+
### [Second half of the network: upsampling inputs] ###
|
| 250 |
+
|
| 251 |
+
for filters in [256, 128, 64, 32]:
|
| 252 |
+
x = layers.Activation("relu")(x)
|
| 253 |
+
x = layers.Conv2DTranspose(filters, 3, padding="same")(x)
|
| 254 |
+
x = layers.BatchNormalization()(x)
|
| 255 |
+
|
| 256 |
+
x = layers.Activation("relu")(x)
|
| 257 |
+
x = layers.Conv2DTranspose(filters, 3, padding="same")(x)
|
| 258 |
+
x = layers.BatchNormalization()(x)
|
| 259 |
+
|
| 260 |
+
x = layers.UpSampling2D(2)(x)
|
| 261 |
+
|
| 262 |
+
# Project residual
|
| 263 |
+
residual = layers.UpSampling2D(2)(previous_block_activation)
|
| 264 |
+
residual = layers.Conv2D(filters, 1, padding="same")(residual)
|
| 265 |
+
x = layers.add([x, residual]) # Add back residual
|
| 266 |
+
previous_block_activation = x # Set aside next residual
|
| 267 |
+
|
| 268 |
+
# Add a per-pixel classification layer
|
| 269 |
+
outputs = layers.Conv2D(num_classes, 3, activation="softmax", padding="same")(x)
|
| 270 |
+
|
| 271 |
+
# Define the model
|
| 272 |
+
model = keras.Model(inputs, outputs)
|
| 273 |
+
return model
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def generate_sample_weights(training_data, class_weights):
|
| 277 |
+
|
| 278 |
+
# replaces values for up to 3 classes with the values from class_weights
|
| 279 |
+
sample_weights = [np.where(y == 0, class_weights[0],
|
| 280 |
+
np.where(y == 1, class_weights[1],
|
| 281 |
+
np.where(y == 2, class_weights[2],
|
| 282 |
+
np.where(y == 3, class_weights[3],
|
| 283 |
+
np.where(y == 4, class_weights[4],
|
| 284 |
+
np.where(y == 5, class_weights[5],
|
| 285 |
+
np.where(y == 6, class_weights[6],
|
| 286 |
+
np.where(y == 7, class_weights[7],
|
| 287 |
+
np.where(y == 8, class_weights[8],
|
| 288 |
+
np.where(y == 9, class_weights[9],
|
| 289 |
+
np.where(y == 10, class_weights[10], y))))))))))) for y in training_data]
|
| 290 |
+
|
| 291 |
+
return np.asarray(sample_weights)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def get_optimizer(optimizer="adam"):
|
| 295 |
+
|
| 296 |
+
if optimizer == "adam":
|
| 297 |
+
return keras.optimizers.Adam(
|
| 298 |
+
learning_rate=0.0001,
|
| 299 |
+
beta_1=0.9,
|
| 300 |
+
beta_2=0.999,
|
| 301 |
+
epsilon=1e-07,
|
| 302 |
+
amsgrad=False)
|
| 303 |
+
|
| 304 |
+
if optimizer == "sgd":
|
| 305 |
+
return keras.optimizers.SGD(
|
| 306 |
+
learning_rate=0.01,
|
| 307 |
+
momentum=0.0,
|
| 308 |
+
nesterov=False,
|
| 309 |
+
weight_decay=None)
|
| 310 |
+
|
| 311 |
+
if optimizer == "rmsprop":
|
| 312 |
+
return keras.optimizers.RMSprop(
|
| 313 |
+
learning_rate=0.0001,
|
| 314 |
+
rho=0.9,
|
| 315 |
+
momentum=0.0,
|
| 316 |
+
epsilon=1e-07,
|
| 317 |
+
centered=False)
|
| 318 |
+
|
| 319 |
+
if optimizer == "adagrad":
|
| 320 |
+
return keras.optimizers.Adagrad(
|
| 321 |
+
learning_rate=0.001,
|
| 322 |
+
initial_accumulator_value=0.1,
|
| 323 |
+
epsilon=1e-07,
|
| 324 |
+
weight_decay=None)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
if __name__ == "__main__":
|
| 328 |
+
# Free up RAM in case the model definition cells were run multiple times
|
| 329 |
+
keras.backend.clear_session()
|
| 330 |
+
|
| 331 |
+
# Build model
|
| 332 |
+
model = get_model(img_size, num_classes)
|
| 333 |
+
model.summary()
|
| 334 |
+
|
| 335 |
+
"""
|
| 336 |
+
## Set aside a validation split
|
| 337 |
+
"""
|
| 338 |
+
|
| 339 |
+
# Split our img paths into a training and a validation set
|
| 340 |
+
train_input_img_paths = input_img_paths_train
|
| 341 |
+
train_target_img_paths = target_img_paths_train
|
| 342 |
+
|
| 343 |
+
val_input_img_paths = input_img_paths_test
|
| 344 |
+
val_target_img_paths = target_img_paths_test
|
| 345 |
+
|
| 346 |
+
print(val_input_img_paths[0])
|
| 347 |
+
print(train_input_img_paths[0])
|
| 348 |
+
|
| 349 |
+
# Instantiate data Sequences for each split
|
| 350 |
+
train_gen = MineSectorHelper(batch_size, img_size, train_input_img_paths, train_target_img_paths)
|
| 351 |
+
val_gen = MineSectorHelper(batch_size, img_size, val_input_img_paths, val_target_img_paths)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
# load the model
|
| 355 |
+
model_file = "mining-segments-model.h5"
|
| 356 |
+
if os.path.isfile(model_file):
|
| 357 |
+
model = keras.models.load_model("mining-segments-model.h5")
|
| 358 |
+
else:
|
| 359 |
+
|
| 360 |
+
# Train the model
|
| 361 |
+
# Configure the model for training.
|
| 362 |
+
# We use the "sparse" version of categorical_crossentropy
|
| 363 |
+
# because our target data is integers.
|
| 364 |
+
|
| 365 |
+
model.compile(optimizer=get_optimizer("adam"), loss="sparse_categorical_crossentropy")
|
| 366 |
+
log_dir = "logs/fit/" + datetime.now().strftime("%Y%m%d-%H%M%S")
|
| 367 |
+
tensorboard_callback = keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
|
| 368 |
+
|
| 369 |
+
callbacks = [
|
| 370 |
+
keras.callbacks.ModelCheckpoint("mining-segments-model.h5", save_best_only=True),
|
| 371 |
+
tensorboard_callback]
|
| 372 |
+
|
| 373 |
+
# apply class weights as sample weights
|
| 374 |
+
# for train_batch in train_gen:
|
| 375 |
+
# sample_weights = generate_sample_weights(train_batch[1], class_weights)
|
| 376 |
+
|
| 377 |
+
'''
|
| 378 |
+
model.fit(x=train_gen[0][0],
|
| 379 |
+
y=train_gen[0][1],
|
| 380 |
+
epochs=epochs,
|
| 381 |
+
validation_data=val_gen,
|
| 382 |
+
callbacks=callbacks,
|
| 383 |
+
sample_weight=train_gen[0][2])
|
| 384 |
+
'''
|
| 385 |
+
|
| 386 |
+
model.fit(train_gen,
|
| 387 |
+
epochs=epochs,
|
| 388 |
+
validation_data=val_gen,
|
| 389 |
+
callbacks=callbacks)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
'''
|
| 393 |
+
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)
|
| 394 |
+
# optimizer = keras.optimizers.SGD(learning_rate=1e-3)
|
| 395 |
+
optimizer = get_optimizer("adam")
|
| 396 |
+
|
| 397 |
+
# Train the model in manual loop
|
| 398 |
+
for epoch in range(epochs):
|
| 399 |
+
print("\nStart of epoch %d" % (epoch,))
|
| 400 |
+
|
| 401 |
+
# Iterate over the batches of the dataset.
|
| 402 |
+
for step, train_batch in enumerate(train_gen):
|
| 403 |
+
|
| 404 |
+
# Open a GradientTape to record the operations run
|
| 405 |
+
# during the forward pass, which enables auto-differentiation.
|
| 406 |
+
with tf.GradientTape() as tape:
|
| 407 |
+
|
| 408 |
+
# Run the forward pass of the layer.
|
| 409 |
+
# The operations that the layer applies
|
| 410 |
+
# to its inputs are going to be recorded
|
| 411 |
+
# on the GradientTape.
|
| 412 |
+
logits = model(train_batch[0], training=True) # Logits for this minibatch
|
| 413 |
+
|
| 414 |
+
# Compute the loss value for this minibatch.
|
| 415 |
+
loss_value = loss_fn(train_batch[1], logits)
|
| 416 |
+
|
| 417 |
+
# Use the gradient tape to automatically retrieve
|
| 418 |
+
# the gradients of the trainable variables with respect to the loss.
|
| 419 |
+
grads = tape.gradient(loss_value, model.trainable_weights)
|
| 420 |
+
|
| 421 |
+
# Run one step of gradient descent by updating
|
| 422 |
+
# the value of the variables to minimize the loss.
|
| 423 |
+
optimizer.apply_gradients(zip(grads, model.trainable_weights))
|
| 424 |
+
|
| 425 |
+
# Log every 200 batches.
|
| 426 |
+
print("Training loss (for one batch) at step %d: %.4f"
|
| 427 |
+
% (step, float(loss_value)))
|
| 428 |
+
|
| 429 |
+
print("Seen so far: %s samples" % ((step + 1) * batch_size))
|
| 430 |
+
|
| 431 |
+
'''
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
# Visualize predictions
|
| 436 |
+
|
| 437 |
+
# Generate predictions for all images in the validation set
|
| 438 |
+
# val_gen = MineSectorHelper(batch_size, img_size, val_input_img_paths, val_target_img_paths)
|
| 439 |
+
# val_preds = model.predict(val_gen, workers=1, max_queue_size=2)
|
| 440 |
+
|
| 441 |
+
sum_conf_mat = np.array([])
|
| 442 |
+
acc_total = 0
|
| 443 |
+
count = 0
|
| 444 |
+
for img_path, mask_path in zip(val_input_img_paths, val_target_img_paths):
|
| 445 |
+
count += 1
|
| 446 |
+
img_arr = np.asarray(Image.open(img_path))
|
| 447 |
+
mask_arr = np.asarray(Image.open(mask_path))
|
| 448 |
+
|
| 449 |
+
# pdb.set_trace()
|
| 450 |
+
|
| 451 |
+
dict_metrics = model.evaluate(x=np.expand_dims(img_arr, axis=0), y=np.expand_dims(mask_arr, axis=0), return_dict=True)
|
| 452 |
+
pred_mask = model.predict(np.expand_dims(img_arr, axis=0))
|
| 453 |
+
|
| 454 |
+
# save the predicted mask file and compare with gt target
|
| 455 |
+
os.makedirs("output", exist_ok=True)
|
| 456 |
+
pred_mask_path = os.path.join("./", "output", "mask_pred" + os.path.basename(img_path) + ".png")
|
| 457 |
+
pred_mask = np.argmax(pred_mask, axis=-1)
|
| 458 |
+
# pred_mask = np.expand_dims(pred_mask[0], axis=-1)
|
| 459 |
+
|
| 460 |
+
Image.fromarray(((pred_mask/10)*255).astype('B')[0]).save(pred_mask_path)
|
| 461 |
+
|
| 462 |
+
os.system('clear')
|
| 463 |
+
# os.system("cls")
|
| 464 |
+
render(img_path)
|
| 465 |
+
print("-------------")
|
| 466 |
+
render(mask_path)
|
| 467 |
+
print("-------------")
|
| 468 |
+
render(pred_mask_path)
|
| 469 |
+
|
| 470 |
+
res = (mask_arr == pred_mask[0]).astype(int)
|
| 471 |
+
acc = np.sum(res)/np.size(res)
|
| 472 |
+
acc_total += acc
|
| 473 |
+
print("total accuracy: ", acc_total / count)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
if sum_conf_mat.size == 0:
|
| 477 |
+
sum_conf_mat = confusion_matrix(y_true=mask_arr.flatten(), y_pred=pred_mask[0].flatten(), labels=range(10))
|
| 478 |
+
else:
|
| 479 |
+
conf_mat = confusion_matrix(y_true=mask_arr.flatten(), y_pred=pred_mask[0].flatten(), labels=range(10))
|
| 480 |
+
sum_conf_mat += conf_mat
|
| 481 |
+
# print(sum_conf_mat)
|
| 482 |
+
|
| 483 |
+
plt.matshow(sum_conf_mat)
|
| 484 |
+
|
| 485 |
+
a = input("continue...")
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def display_img_mask_gt(i):
|
| 493 |
+
os.makedirs("images", exist_ok=True)
|
| 494 |
+
|
| 495 |
+
pred_mask_path = os.path.join("./", "images", "mask" + str(i) + ".png")
|
| 496 |
+
gt_mask_path = os.path.join("./", "images", "mask_gt" + str(i) + ".png")
|
| 497 |
+
img_path = os.path.join("./", "images", "img" + str(i) + ".png")
|
| 498 |
+
|
| 499 |
+
# predicted mask
|
| 500 |
+
pred_mask = np.argmax(val_preds[i], axis=-1)
|
| 501 |
+
pred_mask = np.expand_dims(pred_mask, axis=-1)
|
| 502 |
+
ImageOps.autocontrast(keras.preprocessing.image.array_to_img(pred_mask)).\
|
| 503 |
+
save(pred_mask_path)
|
| 504 |
+
|
| 505 |
+
# ground truth mask
|
| 506 |
+
gt_mask = np.asarray(Image.open(val_target_img_paths[i]))
|
| 507 |
+
gt_mask = np.expand_dims(gt_mask, axis=-1)
|
| 508 |
+
ImageOps.autocontrast(keras.preprocessing.image.array_to_img(gt_mask)). \
|
| 509 |
+
save(gt_mask_path)
|
| 510 |
+
|
| 511 |
+
# input image
|
| 512 |
+
Image.open(val_input_img_paths[i]).\
|
| 513 |
+
save(img_path)
|
| 514 |
+
|
| 515 |
+
os.system('clear')
|
| 516 |
+
render(pred_mask_path)
|
| 517 |
+
print("---------------")
|
| 518 |
+
render(gt_mask_path)
|
| 519 |
+
print("---------------")
|
| 520 |
+
render(img_path)
|
| 521 |
+
time.sleep(5)
|
| 522 |
+
|
| 523 |
+
# for i in range(10): display_img_mask_gt(i)
|
keras_seg_cats_dogs.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from tensorflow.keras import layers
|
| 3 |
+
import os
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from tensorflow import keras
|
| 6 |
+
import numpy as np
|
| 7 |
+
from tensorflow.keras.preprocessing.image import load_img
|
| 8 |
+
from tensorflow.keras.preprocessing.image import load_img
|
| 9 |
+
from PIL import ImageOps, Image
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
import io
|
| 12 |
+
import itertools
|
| 13 |
+
from packaging import version
|
| 14 |
+
import tensorflow as tf
|
| 15 |
+
from tensorflow import keras
|
| 16 |
+
import matplotlib.pyplot as plt
|
| 17 |
+
import numpy as np
|
| 18 |
+
import sklearn.metrics
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
input_dir = "../../data/cats_dogs/images/"
|
| 22 |
+
target_dir = "../../data/cats_dogs/annotations/trimaps/"
|
| 23 |
+
img_size = (160, 160)
|
| 24 |
+
num_classes = 3
|
| 25 |
+
batch_size = 32
|
| 26 |
+
|
| 27 |
+
input_img_paths = sorted(
|
| 28 |
+
[
|
| 29 |
+
os.path.join(input_dir, fname)
|
| 30 |
+
for fname in os.listdir(input_dir)
|
| 31 |
+
if fname.endswith(".jpg")
|
| 32 |
+
]
|
| 33 |
+
)
|
| 34 |
+
target_img_paths = sorted(
|
| 35 |
+
[
|
| 36 |
+
os.path.join(target_dir, fname)
|
| 37 |
+
for fname in os.listdir(target_dir)
|
| 38 |
+
if fname.endswith(".png") and not fname.startswith(".")
|
| 39 |
+
]
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
print("Number of samples:", len(input_img_paths))
|
| 43 |
+
|
| 44 |
+
for input_path, target_path in zip(input_img_paths[:10], target_img_paths[:10]):
|
| 45 |
+
print(input_path, "|", target_path)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def plot_to_image(figure):
|
| 50 |
+
"""Converts the matplotlib plot specified by 'figure' to a PNG image and
|
| 51 |
+
returns it. The supplied figure is closed and inaccessible after this call."""
|
| 52 |
+
# Save the plot to a PNG in memory.
|
| 53 |
+
buf = io.BytesIO()
|
| 54 |
+
plt.savefig(buf, format='png')
|
| 55 |
+
# Closing the figure prevents it from being displayed directly inside
|
| 56 |
+
# the notebook.
|
| 57 |
+
plt.close(figure)
|
| 58 |
+
buf.seek(0)
|
| 59 |
+
# Convert PNG buffer to TF image
|
| 60 |
+
image = tf.image.decode_png(buf.getvalue(), channels=4)
|
| 61 |
+
# Add the batch dimension
|
| 62 |
+
image = tf.expand_dims(image, 0)
|
| 63 |
+
return image
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def image_grid():
|
| 67 |
+
"""Return a 5x5 grid of the MNIST images as a matplotlib figure."""
|
| 68 |
+
# Create a figure to contain the plot.
|
| 69 |
+
figure = plt.figure(figsize=(10,10))
|
| 70 |
+
for i in range(25):
|
| 71 |
+
# Start next subplot.
|
| 72 |
+
plt.subplot(5, 5, i + 1, title=class_names[train_labels[i]])
|
| 73 |
+
plt.xticks([])
|
| 74 |
+
plt.yticks([])
|
| 75 |
+
plt.grid(False)
|
| 76 |
+
plt.imshow(train_images[i], cmap=plt.cm.binary)
|
| 77 |
+
|
| 78 |
+
return figure
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class OxfordPets(keras.utils.Sequence):
|
| 82 |
+
"""Helper to iterate over the data (as Numpy arrays)."""
|
| 83 |
+
|
| 84 |
+
def __init__(self, batch_size, img_size, input_img_paths, target_img_paths):
|
| 85 |
+
self.batch_size = batch_size
|
| 86 |
+
self.img_size = img_size
|
| 87 |
+
self.input_img_paths = input_img_paths
|
| 88 |
+
self.target_img_paths = target_img_paths
|
| 89 |
+
|
| 90 |
+
def __len__(self):
|
| 91 |
+
return len(self.target_img_paths) // self.batch_size
|
| 92 |
+
|
| 93 |
+
def __getitem__(self, idx):
|
| 94 |
+
"""Returns tuple (input, target) correspond to batch #idx."""
|
| 95 |
+
i = idx * self.batch_size
|
| 96 |
+
batch_input_img_paths = self.input_img_paths[i : i + self.batch_size]
|
| 97 |
+
batch_target_img_paths = self.target_img_paths[i : i + self.batch_size]
|
| 98 |
+
x = np.zeros((self.batch_size,) + self.img_size + (3,), dtype="float32")
|
| 99 |
+
for j, path in enumerate(batch_input_img_paths):
|
| 100 |
+
img = load_img(path, target_size=self.img_size)
|
| 101 |
+
x[j] = img
|
| 102 |
+
y = np.zeros((self.batch_size,) + self.img_size + (1,), dtype="uint8")
|
| 103 |
+
for j, path in enumerate(batch_target_img_paths):
|
| 104 |
+
img = load_img(path, target_size=self.img_size, color_mode="grayscale")
|
| 105 |
+
y[j] = np.expand_dims(img, 2)
|
| 106 |
+
# Ground truth labels are 1, 2, 3. Subtract one to make them 0, 1, 2:
|
| 107 |
+
y[j] -= 1
|
| 108 |
+
return x, y
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# Prepare U-Net Xception-style model
|
| 112 |
+
def get_model(img_size, num_classes):
|
| 113 |
+
inputs = keras.Input(shape=img_size + (3,))
|
| 114 |
+
|
| 115 |
+
# [First half of the network: down-sampling inputs] #
|
| 116 |
+
|
| 117 |
+
# Entry block
|
| 118 |
+
x = layers.Conv2D(32, 3, strides=2, padding="same")(inputs)
|
| 119 |
+
x = layers.BatchNormalization()(x)
|
| 120 |
+
x = layers.Activation("relu")(x)
|
| 121 |
+
|
| 122 |
+
previous_block_activation = x # Set aside residual
|
| 123 |
+
|
| 124 |
+
# Blocks 1, 2, 3 are identical apart from the feature depth.
|
| 125 |
+
for filters in [64, 128, 256]:
|
| 126 |
+
x = layers.Activation("relu")(x)
|
| 127 |
+
x = layers.SeparableConv2D(filters, 3, padding="same")(x)
|
| 128 |
+
x = layers.BatchNormalization()(x)
|
| 129 |
+
|
| 130 |
+
x = layers.Activation("relu")(x)
|
| 131 |
+
x = layers.SeparableConv2D(filters, 3, padding="same")(x)
|
| 132 |
+
x = layers.BatchNormalization()(x)
|
| 133 |
+
|
| 134 |
+
x = layers.MaxPooling2D(3, strides=2, padding="same")(x)
|
| 135 |
+
|
| 136 |
+
# Project residual
|
| 137 |
+
residual = layers.Conv2D(filters, 1, strides=2, padding="same")(
|
| 138 |
+
previous_block_activation
|
| 139 |
+
)
|
| 140 |
+
x = layers.add([x, residual]) # Add back residual
|
| 141 |
+
previous_block_activation = x # Set aside next residual
|
| 142 |
+
|
| 143 |
+
### [Second half of the network: upsampling inputs] ###
|
| 144 |
+
|
| 145 |
+
for filters in [256, 128, 64, 32]:
|
| 146 |
+
x = layers.Activation("relu")(x)
|
| 147 |
+
x = layers.Conv2DTranspose(filters, 3, padding="same")(x)
|
| 148 |
+
x = layers.BatchNormalization()(x)
|
| 149 |
+
|
| 150 |
+
x = layers.Activation("relu")(x)
|
| 151 |
+
x = layers.Conv2DTranspose(filters, 3, padding="same")(x)
|
| 152 |
+
x = layers.BatchNormalization()(x)
|
| 153 |
+
|
| 154 |
+
x = layers.UpSampling2D(2)(x)
|
| 155 |
+
|
| 156 |
+
# Project residual
|
| 157 |
+
residual = layers.UpSampling2D(2)(previous_block_activation)
|
| 158 |
+
residual = layers.Conv2D(filters, 1, padding="same")(residual)
|
| 159 |
+
x = layers.add([x, residual]) # Add back residual
|
| 160 |
+
previous_block_activation = x # Set aside next residual
|
| 161 |
+
|
| 162 |
+
# Add a per-pixel classification layer
|
| 163 |
+
outputs = layers.Conv2D(num_classes, 3, activation="softmax", padding="same")(x)
|
| 164 |
+
|
| 165 |
+
# Define the model
|
| 166 |
+
model = keras.Model(inputs, outputs)
|
| 167 |
+
return model
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# Free up RAM in case the model definition cells were run multiple times
|
| 171 |
+
keras.backend.clear_session()
|
| 172 |
+
|
| 173 |
+
# Build model
|
| 174 |
+
model = get_model(img_size, num_classes)
|
| 175 |
+
model.summary()
|
| 176 |
+
|
| 177 |
+
"""
|
| 178 |
+
## Set aside a validation split
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# Split our img paths into a training and a validation set
|
| 183 |
+
val_samples = 1000
|
| 184 |
+
random.Random(1337).shuffle(input_img_paths)
|
| 185 |
+
random.Random(1337).shuffle(target_img_paths)
|
| 186 |
+
train_input_img_paths = input_img_paths[:-val_samples]
|
| 187 |
+
train_target_img_paths = target_img_paths[:-val_samples]
|
| 188 |
+
val_input_img_paths = input_img_paths[-val_samples:]
|
| 189 |
+
val_target_img_paths = target_img_paths[-val_samples:]
|
| 190 |
+
|
| 191 |
+
# Instantiate data Sequences for each split
|
| 192 |
+
train_gen = OxfordPets(
|
| 193 |
+
batch_size, img_size, train_input_img_paths, train_target_img_paths
|
| 194 |
+
)
|
| 195 |
+
val_gen = OxfordPets(batch_size, img_size, val_input_img_paths, val_target_img_paths)
|
| 196 |
+
|
| 197 |
+
"""
|
| 198 |
+
## Train the model
|
| 199 |
+
"""
|
| 200 |
+
|
| 201 |
+
# Configure the model for training.
|
| 202 |
+
# We use the "sparse" version of categorical_crossentropy
|
| 203 |
+
# because our target data is integers.
|
| 204 |
+
model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy")
|
| 205 |
+
log_dir = "logs/fit/" + datetime.now().strftime("%Y%m%d-%H%M%S")
|
| 206 |
+
tensorboard_callback = keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
|
| 207 |
+
|
| 208 |
+
callbacks = [
|
| 209 |
+
keras.callbacks.ModelCheckpoint("oxford_segmentation.h5", save_best_only=True),
|
| 210 |
+
tensorboard_callback
|
| 211 |
+
]
|
| 212 |
+
|
| 213 |
+
logdir = "logs/plots/" + datetime.now().strftime("%Y%m%d-%H%M%S")
|
| 214 |
+
file_writer = tf.summary.create_file_writer(logdir)
|
| 215 |
+
|
| 216 |
+
# Prepare the plot
|
| 217 |
+
figure = image_grid()
|
| 218 |
+
|
| 219 |
+
# Convert to image and log
|
| 220 |
+
with file_writer.as_default():
|
| 221 |
+
tf.summary.image("Training data", plot_to_image(figure), step=0)
|
| 222 |
+
|
| 223 |
+
# Train the model, doing validation at the end of each epoch.
|
| 224 |
+
epochs = 15
|
| 225 |
+
model.fit(train_gen, epochs=epochs, validation_data=val_gen, callbacks=callbacks)
|
| 226 |
+
|
| 227 |
+
"""
|
| 228 |
+
## Visualize predictions
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
# Generate predictions for all images in the validation set
|
| 232 |
+
|
| 233 |
+
val_gen = OxfordPets(batch_size, img_size, val_input_img_paths, val_target_img_paths)
|
| 234 |
+
val_preds = model.predict(val_gen)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def display_mask(i):
|
| 238 |
+
"""Quick utility to display a model's prediction."""
|
| 239 |
+
mask = np.argmax(val_preds[i], axis=-1)
|
| 240 |
+
mask = np.expand_dims(mask, axis=-1)
|
| 241 |
+
img = ImageOps.autocontrast(keras.preprocessing.image.array_to_img(mask))
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# Display results for validation image #10
|
| 246 |
+
i = 10
|
| 247 |
+
|
| 248 |
+
# Display input image
|
| 249 |
+
Image.open(val_input_img_paths[i]).save(str(i) + ".png")
|
| 250 |
+
|
| 251 |
+
# Display ground-truth target mask
|
| 252 |
+
img = ImageOps.autocontrast(load_img(val_target_img_paths[i]))
|
| 253 |
+
Image.open(val_input_img_paths[i]).save(str(i) + "_mask.png")
|
mask-rcnn.py
ADDED
|
@@ -0,0 +1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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Mask R-CNN
|
| 3 |
+
Train on the toy Balloon dataset and implement color splash effect.
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2018 Matterport, Inc.
|
| 6 |
+
Licensed under the MIT License (see LICENSE for details)
|
| 7 |
+
Written by Waleed Abdulla
|
| 8 |
+
|
| 9 |
+
------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
Usage: import the module (see Jupyter notebooks for examples), or run from
|
| 12 |
+
the command line as such:
|
| 13 |
+
|
| 14 |
+
# Train a new model starting from pre-trained COCO weights
|
| 15 |
+
python3 balloon.py train --dataset=/path/to/balloon/dataset --weights=coco
|
| 16 |
+
|
| 17 |
+
# Resume training a model that you had trained earlier
|
| 18 |
+
python3 balloon.py train --dataset=/path/to/balloon/dataset --weights=last
|
| 19 |
+
|
| 20 |
+
# Train a new model starting from ImageNet weights
|
| 21 |
+
python3 balloon.py train --dataset=/path/to/balloon/dataset --weights=imagenet
|
| 22 |
+
|
| 23 |
+
# Apply color splash to an image
|
| 24 |
+
python3 balloon.py splash --weights=/path/to/weights/file.h5 --image=<URL or path to file>
|
| 25 |
+
|
| 26 |
+
# Apply color splash to video using the last weights you trained
|
| 27 |
+
python3 balloon.py splash --weights=last --video=<URL or path to file>
|
| 28 |
+
"""
|
| 29 |
+
import glob
|
| 30 |
+
import os
|
| 31 |
+
import pdb
|
| 32 |
+
import sys
|
| 33 |
+
import json
|
| 34 |
+
import datetime
|
| 35 |
+
import numpy as np
|
| 36 |
+
import skimage.draw
|
| 37 |
+
import platform
|
| 38 |
+
import pdb
|
| 39 |
+
import glob
|
| 40 |
+
from PIL import Image
|
| 41 |
+
|
| 42 |
+
# Root directory of the project
|
| 43 |
+
ROOT_DIR = os.path.abspath("../../../")
|
| 44 |
+
|
| 45 |
+
# mine sectors
|
| 46 |
+
if platform.system() == "Windows":
|
| 47 |
+
base_dir = "C:/data/"
|
| 48 |
+
else:
|
| 49 |
+
base_dir = "/root/host/ssd/mine-sector-detection/"
|
| 50 |
+
# base_dir = "/home/maduschek/ssd/mine-sector-detection/DEBUG/"
|
| 51 |
+
|
| 52 |
+
# Import Mask RCNN
|
| 53 |
+
sys.path.append(ROOT_DIR) # To find local version of the library
|
| 54 |
+
from mrcnn.config import Config
|
| 55 |
+
from mrcnn import model as modellib, utils
|
| 56 |
+
|
| 57 |
+
# Path to trained weights file
|
| 58 |
+
COCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
|
| 59 |
+
|
| 60 |
+
# Directory to save logs and model checkpoints, if not provided
|
| 61 |
+
# through the command line argument --logs
|
| 62 |
+
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")
|
| 63 |
+
|
| 64 |
+
############################################################
|
| 65 |
+
# Configurations
|
| 66 |
+
############################################################
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class BalloonConfig(Config):
|
| 70 |
+
"""Configuration for training on the toy dataset.
|
| 71 |
+
Derives from the base Config class and overrides some values.
|
| 72 |
+
"""
|
| 73 |
+
# Give the configuration a recognizable name
|
| 74 |
+
NAME = "mining_sectors"
|
| 75 |
+
|
| 76 |
+
# We use a GPU with 12GB memory, which can fit two images.
|
| 77 |
+
# Adjust down if you use a smaller GPU.
|
| 78 |
+
IMAGES_PER_GPU = 1
|
| 79 |
+
|
| 80 |
+
# Number of classes (including background)
|
| 81 |
+
NUM_CLASSES = 10 # Background + balloon
|
| 82 |
+
|
| 83 |
+
# Number of training steps per epoch
|
| 84 |
+
STEPS_PER_EPOCH = 50
|
| 85 |
+
|
| 86 |
+
# Skip detections with < 90% confidence
|
| 87 |
+
DETECTION_MIN_CONFIDENCE = 0.9
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
############################################################
|
| 91 |
+
# Dataset
|
| 92 |
+
############################################################
|
| 93 |
+
|
| 94 |
+
class BalloonDataset(utils.Dataset):
|
| 95 |
+
|
| 96 |
+
def load_balloon(self, dataset_dir, subset):
|
| 97 |
+
"""Load a subset of the Balloon dataset.
|
| 98 |
+
dataset_dir: Root directory of the dataset.
|
| 99 |
+
subset: Subset to load: train or val
|
| 100 |
+
"""
|
| 101 |
+
# Add classes.
|
| 102 |
+
self.add_class("balloon", 0, "surrounding")
|
| 103 |
+
self.add_class("balloon", 1, "ASM")
|
| 104 |
+
self.add_class("balloon", 2, "LSM")
|
| 105 |
+
self.add_class("balloon", 3, "Leaching Heap")
|
| 106 |
+
self.add_class("balloon", 4, "Mining Facilities")
|
| 107 |
+
self.add_class("balloon", 5, "Open Pit")
|
| 108 |
+
self.add_class("balloon", 6, "Processing Plant")
|
| 109 |
+
self.add_class("balloon", 7, "Stockyard")
|
| 110 |
+
self.add_class("balloon", 8, "Tailings Storage Facility")
|
| 111 |
+
self.add_class("balloon", 9, "Waste Rock Dump")
|
| 112 |
+
|
| 113 |
+
# Train or validation dataset?
|
| 114 |
+
assert subset in ["images_trainset", "images_testset"]
|
| 115 |
+
dataset_dir = os.path.join(dataset_dir, subset)
|
| 116 |
+
|
| 117 |
+
image_paths = sorted(glob.glob(os.path.join(dataset_dir, "*.png")))
|
| 118 |
+
|
| 119 |
+
for idx, image_path in enumerate(image_paths):
|
| 120 |
+
filename = os.path.basename(image_path)
|
| 121 |
+
self.add_image(
|
| 122 |
+
"balloon",
|
| 123 |
+
image_id=idx, # use file name as a unique image id
|
| 124 |
+
image_fname=os.path.basename(image_path),
|
| 125 |
+
path=image_path,
|
| 126 |
+
width=256,
|
| 127 |
+
height=256)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def load_mask(self, image_id):
|
| 137 |
+
|
| 138 |
+
"""Generate instance masks for an image.
|
| 139 |
+
Returns:
|
| 140 |
+
masks: A bool array of shape [height, width, instance count] with
|
| 141 |
+
one mask per instance.
|
| 142 |
+
class_ids: a 1D array of class IDs of the instance masks.
|
| 143 |
+
"""
|
| 144 |
+
# print(image_id)
|
| 145 |
+
|
| 146 |
+
# If not a balloon dataset image, delegate to parent class.
|
| 147 |
+
image_info = self.image_info[image_id]
|
| 148 |
+
if image_info["source"] != "balloon":
|
| 149 |
+
return super(self.__class__, self).load_mask(image_id)
|
| 150 |
+
|
| 151 |
+
# Convert polygons to a bitmap mask of shape
|
| 152 |
+
# [height, width, instance_count]
|
| 153 |
+
info = self.image_info[image_id]
|
| 154 |
+
|
| 155 |
+
# get number of classes in this mask image and create for each class a binary mask
|
| 156 |
+
# img = Image.open(info.path)
|
| 157 |
+
# instance_count = np.unique(np.asarray(img, dtype=np.uint8))
|
| 158 |
+
|
| 159 |
+
mask = np.zeros([256, 256, 1], dtype=np.uint8)
|
| 160 |
+
return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)
|
| 161 |
+
|
| 162 |
+
'''
|
| 163 |
+
mask = np.zeros([info["height"], info["width"], len(info["polygons"])],
|
| 164 |
+
dtype=np.uint8)
|
| 165 |
+
for i, p in enumerate(info["polygons"]):
|
| 166 |
+
# Get indexes of pixels inside the polygon and set them to 1
|
| 167 |
+
rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])
|
| 168 |
+
mask[rr, cc, i] = 1
|
| 169 |
+
|
| 170 |
+
# Return mask, and array of class IDs of each instance. Since we have
|
| 171 |
+
# one class ID only, we return an array of 1s
|
| 172 |
+
return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)
|
| 173 |
+
'''
|
| 174 |
+
|
| 175 |
+
def image_reference(self, image_id):
|
| 176 |
+
"""Return the path of the image."""
|
| 177 |
+
info = self.image_info[image_id]
|
| 178 |
+
if info["source"] == "balloon":
|
| 179 |
+
return info["path"]
|
| 180 |
+
else:
|
| 181 |
+
super(self.__class__, self).image_reference(image_id)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def train(model):
|
| 185 |
+
|
| 186 |
+
"""Train the model."""
|
| 187 |
+
# Training dataset.
|
| 188 |
+
dataset_train = BalloonDataset()
|
| 189 |
+
dataset_train.load_balloon(args.dataset, "images_trainset")
|
| 190 |
+
dataset_train.prepare()
|
| 191 |
+
|
| 192 |
+
# Validation dataset
|
| 193 |
+
dataset_val = BalloonDataset()
|
| 194 |
+
dataset_val.load_balloon(args.dataset, "images_testset")
|
| 195 |
+
dataset_val.prepare()
|
| 196 |
+
|
| 197 |
+
dataset_train.load_mask(23)
|
| 198 |
+
|
| 199 |
+
# *** This training schedule is an example. Update to your needs ***
|
| 200 |
+
# Since we're using a very small dataset, and starting from
|
| 201 |
+
# COCO trained weights, we don't need to train too long. Also,
|
| 202 |
+
# no need to train all layers, just the heads should do it.
|
| 203 |
+
print("Training network heads")
|
| 204 |
+
model.train(dataset_train, dataset_val,
|
| 205 |
+
learning_rate=config.LEARNING_RATE,
|
| 206 |
+
epochs=30,
|
| 207 |
+
layers='heads')
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def color_splash(image, mask):
|
| 211 |
+
"""Apply color splash effect.
|
| 212 |
+
image: RGB image [height, width, 3]
|
| 213 |
+
mask: instance segmentation mask [height, width, instance count]
|
| 214 |
+
|
| 215 |
+
Returns result image.
|
| 216 |
+
"""
|
| 217 |
+
# Make a grayscale copy of the image. The grayscale copy still
|
| 218 |
+
# has 3 RGB channels, though.
|
| 219 |
+
gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255
|
| 220 |
+
# Copy color pixels from the original color image where mask is set
|
| 221 |
+
if mask.shape[-1] > 0:
|
| 222 |
+
# We're treating all instances as one, so collapse the mask into one layer
|
| 223 |
+
mask = (np.sum(mask, -1, keepdims=True) >= 1)
|
| 224 |
+
splash = np.where(mask, image, gray).astype(np.uint8)
|
| 225 |
+
else:
|
| 226 |
+
splash = gray.astype(np.uint8)
|
| 227 |
+
return splash
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def detect_and_color_splash(model, image_path=None, video_path=None):
|
| 231 |
+
assert image_path or video_path
|
| 232 |
+
|
| 233 |
+
# Image or video?
|
| 234 |
+
if image_path:
|
| 235 |
+
# Run model detection and generate the color splash effect
|
| 236 |
+
print("Running on {}".format(args.image))
|
| 237 |
+
# Read image
|
| 238 |
+
image = skimage.io.imread(args.image)
|
| 239 |
+
# Detect objects
|
| 240 |
+
r = model.detect([image], verbose=1)[0]
|
| 241 |
+
# Color splash
|
| 242 |
+
splash = color_splash(image, r['masks'])
|
| 243 |
+
# Save output
|
| 244 |
+
file_name = "splash_{:%Y%m%dT%H%M%S}.png".format(datetime.datetime.now())
|
| 245 |
+
skimage.io.imsave(file_name, splash)
|
| 246 |
+
elif video_path:
|
| 247 |
+
import cv2
|
| 248 |
+
# Video capture
|
| 249 |
+
vcapture = cv2.VideoCapture(video_path)
|
| 250 |
+
width = int(vcapture.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 251 |
+
height = int(vcapture.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 252 |
+
fps = vcapture.get(cv2.CAP_PROP_FPS)
|
| 253 |
+
|
| 254 |
+
# Define codec and create video writer
|
| 255 |
+
file_name = "splash_{:%Y%m%dT%H%M%S}.avi".format(datetime.datetime.now())
|
| 256 |
+
vwriter = cv2.VideoWriter(file_name,
|
| 257 |
+
cv2.VideoWriter_fourcc(*'MJPG'),
|
| 258 |
+
fps, (width, height))
|
| 259 |
+
|
| 260 |
+
count = 0
|
| 261 |
+
success = True
|
| 262 |
+
while success:
|
| 263 |
+
print("frame: ", count)
|
| 264 |
+
# Read next image
|
| 265 |
+
success, image = vcapture.read()
|
| 266 |
+
if success:
|
| 267 |
+
# OpenCV returns images as BGR, convert to RGB
|
| 268 |
+
image = image[..., ::-1]
|
| 269 |
+
# Detect objects
|
| 270 |
+
r = model.detect([image], verbose=0)[0]
|
| 271 |
+
# Color splash
|
| 272 |
+
splash = color_splash(image, r['masks'])
|
| 273 |
+
# RGB -> BGR to save image to video
|
| 274 |
+
splash = splash[..., ::-1]
|
| 275 |
+
# Add image to video writer
|
| 276 |
+
vwriter.write(splash)
|
| 277 |
+
count += 1
|
| 278 |
+
vwriter.release()
|
| 279 |
+
print("Saved to ", file_name)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
############################################################
|
| 283 |
+
# Training
|
| 284 |
+
############################################################
|
| 285 |
+
|
| 286 |
+
if __name__ == '__main__':
|
| 287 |
+
import argparse
|
| 288 |
+
|
| 289 |
+
# Parse command line arguments
|
| 290 |
+
parser = argparse.ArgumentParser(
|
| 291 |
+
description='Train Mask R-CNN to detect balloons.')
|
| 292 |
+
parser.add_argument("command",
|
| 293 |
+
metavar="<command>",
|
| 294 |
+
help="'train' or 'splash'")
|
| 295 |
+
parser.add_argument('--dataset', required=False,
|
| 296 |
+
metavar="/path/to/balloon/dataset/",
|
| 297 |
+
help='Directory of the Balloon dataset')
|
| 298 |
+
parser.add_argument('--weights', required=True,
|
| 299 |
+
metavar="/path/to/weights.h5",
|
| 300 |
+
help="Path to weights .h5 file or 'coco'")
|
| 301 |
+
parser.add_argument('--logs', required=False,
|
| 302 |
+
default=DEFAULT_LOGS_DIR,
|
| 303 |
+
metavar="/path/to/logs/",
|
| 304 |
+
help='Logs and checkpoints directory (default=logs/)')
|
| 305 |
+
parser.add_argument('--image', required=False,
|
| 306 |
+
metavar="path or URL to image",
|
| 307 |
+
help='Image to apply the color splash effect on')
|
| 308 |
+
parser.add_argument('--video', required=False,
|
| 309 |
+
metavar="path or URL to video",
|
| 310 |
+
help='Video to apply the color splash effect on')
|
| 311 |
+
args = parser.parse_args()
|
| 312 |
+
|
| 313 |
+
# Validate arguments
|
| 314 |
+
if args.command == "train":
|
| 315 |
+
assert args.dataset, "Argument --dataset is required for training"
|
| 316 |
+
elif args.command == "splash":
|
| 317 |
+
assert args.image or args.video,\
|
| 318 |
+
"Provide --image or --video to apply color splash"
|
| 319 |
+
|
| 320 |
+
print("Weights: ", args.weights)
|
| 321 |
+
print("Dataset: ", args.dataset)
|
| 322 |
+
print("Logs: ", args.logs)
|
| 323 |
+
|
| 324 |
+
# Configurations
|
| 325 |
+
if args.command == "train":
|
| 326 |
+
config = BalloonConfig()
|
| 327 |
+
else:
|
| 328 |
+
class InferenceConfig(BalloonConfig):
|
| 329 |
+
# Set batch size to 1 since we'll be running inference on
|
| 330 |
+
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
|
| 331 |
+
GPU_COUNT = 1
|
| 332 |
+
IMAGES_PER_GPU = 1
|
| 333 |
+
config = InferenceConfig()
|
| 334 |
+
config.display()
|
| 335 |
+
|
| 336 |
+
# Create model
|
| 337 |
+
if args.command == "train":
|
| 338 |
+
model = modellib.MaskRCNN(mode="training", config=config,
|
| 339 |
+
model_dir=args.logs)
|
| 340 |
+
else:
|
| 341 |
+
model = modellib.MaskRCNN(mode="inference", config=config,
|
| 342 |
+
model_dir=args.logs)
|
| 343 |
+
|
| 344 |
+
# Select weights file to load
|
| 345 |
+
if args.weights.lower() == "coco":
|
| 346 |
+
weights_path = COCO_WEIGHTS_PATH
|
| 347 |
+
# Download weights file
|
| 348 |
+
if not os.path.exists(weights_path):
|
| 349 |
+
utils.download_trained_weights(weights_path)
|
| 350 |
+
elif args.weights.lower() == "last":
|
| 351 |
+
# Find last trained weights
|
| 352 |
+
weights_path = model.find_last()
|
| 353 |
+
elif args.weights.lower() == "imagenet":
|
| 354 |
+
# Start from ImageNet trained weights
|
| 355 |
+
weights_path = model.get_imagenet_weights()
|
| 356 |
+
else:
|
| 357 |
+
weights_path = args.weights
|
| 358 |
+
|
| 359 |
+
# Load weights
|
| 360 |
+
print("Loading weights ", weights_path)
|
| 361 |
+
if args.weights.lower() == "coco":
|
| 362 |
+
# Exclude the last layers because they require a matching
|
| 363 |
+
# number of classes
|
| 364 |
+
model.load_weights(weights_path, by_name=True, exclude=[
|
| 365 |
+
"mrcnn_class_logits", "mrcnn_bbox_fc",
|
| 366 |
+
"mrcnn_bbox", "mrcnn_mask"])
|
| 367 |
+
else:
|
| 368 |
+
model.load_weights(weights_path, by_name=True)
|
| 369 |
+
|
| 370 |
+
# Train or evaluate
|
| 371 |
+
if args.command == "train":
|
| 372 |
+
train(model)
|
| 373 |
+
elif args.command == "splash":
|
| 374 |
+
detect_and_color_splash(model, image_path=args.image,
|
| 375 |
+
video_path=args.video)
|
| 376 |
+
else:
|
| 377 |
+
print("'{}' is not recognized. "
|
| 378 |
+
"Use 'train' or 'splash'".format(args.command))
|
pad-files.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import pdb
|
| 6 |
+
import platform
|
| 7 |
+
# from IPython.display import display
|
| 8 |
+
from tensorflow.keras.preprocessing.image import load_img
|
| 9 |
+
from PIL import ImageOps, Image
|
| 10 |
+
from tensorflow import keras
|
| 11 |
+
import numpy as np
|
| 12 |
+
from tensorflow.keras.preprocessing.image import load_img
|
| 13 |
+
from tensorflow.keras import layers
|
| 14 |
+
from imgrender import render
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# mine sectors
|
| 18 |
+
if platform.system() == "Windows":
|
| 19 |
+
base_dir = "C:/data/"
|
| 20 |
+
else:
|
| 21 |
+
base_dir = "/home/maduschek/ssd/mine-sector-detection/"
|
| 22 |
+
|
| 23 |
+
datasets = [base_dir + "images_trainset/",
|
| 24 |
+
base_dir + "masks_trainset/",
|
| 25 |
+
base_dir + "images_testset/",
|
| 26 |
+
base_dir + "masks_testset/"]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
for dataset in datasets:
|
| 30 |
+
for img_path in glob.glob(os.path.join(dataset, "*.png")):
|
| 31 |
+
img = Image.open(img_path)
|
| 32 |
+
print(img_path)
|
| 33 |
+
|
| 34 |
+
if img.size != (256, 256):
|
| 35 |
+
print("file: ", img_path, ', size: ', str(img.size))
|
| 36 |
+
width, height = img.size
|
| 37 |
+
right = 256 - width
|
| 38 |
+
bottom = 256 - height
|
| 39 |
+
padded_img = Image.new(img.mode, (width + right, height + bottom))
|
| 40 |
+
padded_img.paste(img, (0, 0))
|
| 41 |
+
padded_img.save(img_path)
|
pytorch_seg.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torchvision.io.image import read_image
|
| 2 |
+
from torchvision.models.segmentation import fcn_resnet50, FCN_ResNet50_Weights
|
| 3 |
+
from torchvision.transforms.functional import to_pil_image
|
| 4 |
+
|
| 5 |
+
img = read_image("gallery/assets/dog1.jpg")
|
| 6 |
+
|
| 7 |
+
# Step 1: Initialize model with the best available weights
|
| 8 |
+
weights = FCN_ResNet50_Weights.DEFAULT
|
| 9 |
+
model = fcn_resnet50(weights=weights)
|
| 10 |
+
model.eval()
|
| 11 |
+
|
| 12 |
+
# Step 2: Initialize the inference transforms
|
| 13 |
+
preprocess = weights.transforms()
|
| 14 |
+
|
| 15 |
+
# Step 3: Apply inference preprocessing transforms
|
| 16 |
+
batch = preprocess(img).unsqueeze(0)
|
| 17 |
+
|
| 18 |
+
# Step 4: Use the model and visualize the prediction
|
| 19 |
+
prediction = model(batch)["out"]
|
| 20 |
+
normalized_masks = prediction.softmax(dim=1)
|
| 21 |
+
class_to_idx = {cls: idx for (idx, cls) in enumerate(weights.meta["categories"])}
|
| 22 |
+
mask = normalized_masks[0, class_to_idx["dog"]]
|
| 23 |
+
to_pil_image(mask).show()
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
imgrender==0.0.4
|
| 2 |
+
matplotlib==3.7.1
|
| 3 |
+
mrcnn==0.2
|
| 4 |
+
numpy==1.23.5
|
| 5 |
+
osgeo==0.0.1
|
| 6 |
+
packaging==23.1
|
| 7 |
+
pandas==2.0.2
|
| 8 |
+
Pillow==9.5.0
|
| 9 |
+
Pillow==9.5.0
|
| 10 |
+
scikit_learn==1.2.2
|
| 11 |
+
scikit_image
|
| 12 |
+
tensorflow==2.12.0
|
| 13 |
+
torchvision==0.15.2
|
run.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import random
|
| 4 |
+
import math
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
import numpy as np
|
| 8 |
+
import cv2
|
| 9 |
+
import matplotlib
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pdb
|
| 13 |
+
from sklearn.model_selection import train_test_split
|
| 14 |
+
import glob
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# Root directory of the project
|
| 18 |
+
ROOT_DIR = os.path.abspath("./Mask_RCNN/")
|
| 19 |
+
|
| 20 |
+
# Import Mask RCNN
|
| 21 |
+
sys.path.append(ROOT_DIR) # To find local version of the library
|
| 22 |
+
from mrcnn.config import Config
|
| 23 |
+
from mrcnn import utils
|
| 24 |
+
import mrcnn.model as modellib
|
| 25 |
+
from mrcnn import visualize
|
| 26 |
+
from mrcnn.model import log
|
| 27 |
+
|
| 28 |
+
# Directory to save logs and trained model
|
| 29 |
+
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
|
| 30 |
+
|
| 31 |
+
# Local path to trained weights file
|
| 32 |
+
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
|
| 33 |
+
|
| 34 |
+
# Download COCO trained weights from Releases if needed
|
| 35 |
+
if not os.path.exists(COCO_MODEL_PATH):
|
| 36 |
+
utils.download_trained_weights(COCO_MODEL_PATH)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class MineSectorConfig(Config):
|
| 40 |
+
"""Configuration for training on the toy shapes dataset.
|
| 41 |
+
Derives from the base Config class and overrides values specific
|
| 42 |
+
to the toy shapes dataset.
|
| 43 |
+
"""
|
| 44 |
+
# Give the configuration a recognizable name
|
| 45 |
+
NAME = "mining-sectors"
|
| 46 |
+
|
| 47 |
+
# Train on 1 GPU and 8 images per GPU. We can put multiple images on each
|
| 48 |
+
# GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
|
| 49 |
+
GPU_COUNT = 1
|
| 50 |
+
IMAGES_PER_GPU = 8
|
| 51 |
+
|
| 52 |
+
# Number of classes (including background)
|
| 53 |
+
NUM_CLASSES = 1 + 9 # background + 3 shapes
|
| 54 |
+
|
| 55 |
+
# Use small images for faster training. Set the limits of the small side
|
| 56 |
+
# the large side, and that determines the image shape.
|
| 57 |
+
IMAGE_MIN_DIM = 128
|
| 58 |
+
IMAGE_MAX_DIM = 128
|
| 59 |
+
|
| 60 |
+
# Use smaller anchors because our image and objects are small
|
| 61 |
+
RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128) # anchor side in pixels
|
| 62 |
+
|
| 63 |
+
# Reduce training ROIs per image because the images are small and have
|
| 64 |
+
# few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
|
| 65 |
+
TRAIN_ROIS_PER_IMAGE = 32
|
| 66 |
+
|
| 67 |
+
# Use a small epoch since the data is simple
|
| 68 |
+
STEPS_PER_EPOCH = 100
|
| 69 |
+
|
| 70 |
+
# use small validation steps since the epoch is small
|
| 71 |
+
VALIDATION_STEPS = 5
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
config = MineSectorConfig()
|
| 75 |
+
config.display()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class MineSectDataset(utils.Dataset):
|
| 79 |
+
|
| 80 |
+
def __init__(self, path):
|
| 81 |
+
self.path = path
|
| 82 |
+
self.mine_ids = []
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def load_mine_sectors(self):
|
| 86 |
+
"""Generate the requested number of synthetic images.
|
| 87 |
+
count: number of images to generate.
|
| 88 |
+
height, width: the size of the generated images.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
self.add_class("shapes", 1, "square")
|
| 92 |
+
self.add_class("shapes", 2, "circle")
|
| 93 |
+
self.add_class("shapes", 3, "triangle")
|
| 94 |
+
|
| 95 |
+
# Add classes
|
| 96 |
+
'''
|
| 97 |
+
self.add_class("mine_sector", 3, "lh")
|
| 98 |
+
self.add_class("mine_sector", 4, "mf")
|
| 99 |
+
self.add_class("mine_sector", 5, "op")
|
| 100 |
+
self.add_class("mine_sector", 6, "pp")
|
| 101 |
+
self.add_class("mine_sector", 7, "sy")
|
| 102 |
+
self.add_class("mine_sector", 8, "tsf")
|
| 103 |
+
self.add_class("mine_sector", 9, "wr")
|
| 104 |
+
'''
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# Add images
|
| 108 |
+
# Generate random specifications of images (i.e. color and
|
| 109 |
+
# list of shapes sizes and locations). This is more compact than
|
| 110 |
+
# actual images. Images are generated on the fly in load_image().
|
| 111 |
+
df = create_df()
|
| 112 |
+
print('Total Images: ', len(df))
|
| 113 |
+
mine_ids = np.array([])
|
| 114 |
+
|
| 115 |
+
# split mines into train, valid and test
|
| 116 |
+
|
| 117 |
+
# get unique mine ids
|
| 118 |
+
for patch in df['id'].values:
|
| 119 |
+
mine_id = int(patch.split(".")[0])
|
| 120 |
+
if mine_id not in mine_ids:
|
| 121 |
+
self.mine_ids = np.append(self.mine_ids, mine_id)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def load_image(self, filename):
|
| 125 |
+
# loads the image from a file, but
|
| 126 |
+
|
| 127 |
+
pdb.set_trace()
|
| 128 |
+
fpath = os.path.join(self.path, filename)
|
| 129 |
+
image = cv2.imread(fpath)
|
| 130 |
+
return image
|
| 131 |
+
|
| 132 |
+
def load_mask(self, filename):
|
| 133 |
+
# loads the image from a file, but
|
| 134 |
+
|
| 135 |
+
pdb.set_trace()
|
| 136 |
+
fpath = os.path.join(self.path, filename)
|
| 137 |
+
image = cv2.imread(fpath)
|
| 138 |
+
return image
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def image_reference(self, image_id):
|
| 142 |
+
"""Return the shapes data of the image."""
|
| 143 |
+
info = self.image_info[image_id]
|
| 144 |
+
if info["source"] == "shapes":
|
| 145 |
+
return info["shapes"]
|
| 146 |
+
else:
|
| 147 |
+
super(self.__class__).image_reference(self, image_id)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
IMG_PATH = 'dataset/images/'
|
| 151 |
+
MASK_PATH = 'dataset/masks/'
|
| 152 |
+
|
| 153 |
+
batch_size = 32
|
| 154 |
+
num_classes = 10
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# create dataframe to get the image name/index in order
|
| 158 |
+
def create_df():
|
| 159 |
+
name = []
|
| 160 |
+
for dir, subdir, filenames in os.walk(IMG_PATH):
|
| 161 |
+
for filename in filenames:
|
| 162 |
+
name.append(filename[:-4])
|
| 163 |
+
|
| 164 |
+
return pd.DataFrame({'id': name}, index=np.arange(0, len(name)))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
if __name__ == "__main__":
|
| 168 |
+
|
| 169 |
+
# pdb.set_trace()
|
| 170 |
+
mine_sect_ds = MineSectDataset(IMG_PATH)
|
| 171 |
+
mine_sect_ds.load_mine_sectors()
|
| 172 |
+
mine_sect_ds.load_image(mine_sect_ds.mine_ids[0])
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
MID_trainval, MID_test = train_test_split(mine_ids, test_size=0.15, random_state=42)
|
| 177 |
+
MID_train, MID_val = train_test_split(MID_trainval, test_size=0.25, random_state=42)
|
| 178 |
+
|
| 179 |
+
X_train = np.array([])
|
| 180 |
+
for id in MID_train:
|
| 181 |
+
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"))]))
|
| 182 |
+
|
| 183 |
+
X_val = np.array([])
|
| 184 |
+
for id in MID_val:
|
| 185 |
+
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"))]))
|
| 186 |
+
|
| 187 |
+
X_test = np.array([])
|
| 188 |
+
for id in MID_test:
|
| 189 |
+
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"))]))
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
print('Train Size: ', len(X_train))
|
| 193 |
+
print('Validation Size: ', len(X_val))
|
| 194 |
+
print('Test Size: ', len(X_test))
|
run_maskrcnn.sh
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
python mask-rcnn.py train --dataset "/root/host/ssd/mine-sector-detection" --weights=mask_rcnn_coco.h5
|
| 2 |
+
|
seg_stats.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import os.path
|
| 3 |
+
import platform
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# mine sectors
|
| 9 |
+
if platform.system() == "Windows":
|
| 10 |
+
base_dir = "C:/data/mine-sectors/"
|
| 11 |
+
else:
|
| 12 |
+
base_dir = "/home/maduschek/ssd/mine-sector-detection/"
|
| 13 |
+
# base_dir = "/home/maduschek/data/cats_dogs/"
|
| 14 |
+
|
| 15 |
+
input_dir_train = base_dir + "images_trainset/"
|
| 16 |
+
target_dir_train = base_dir + "masks_trainset/"
|
| 17 |
+
input_dir_test = base_dir + "images_testset/"
|
| 18 |
+
target_dir_test = base_dir + "masks_testset/"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
shape_img_list = []
|
| 22 |
+
shape_mask_list = []
|
| 23 |
+
class_instances = dict()
|
| 24 |
+
|
| 25 |
+
k = 0
|
| 26 |
+
for img_path, mask_path in zip(glob.glob(os.path.join(input_dir_train, "*.png")), glob.glob(os.path.join(target_dir_train, "*.png"))):
|
| 27 |
+
|
| 28 |
+
k += 1
|
| 29 |
+
|
| 30 |
+
# get shape of all images
|
| 31 |
+
img = Image.open(img_path)
|
| 32 |
+
if img.size not in shape_img_list:
|
| 33 |
+
shape_img_list.append(img.size)
|
| 34 |
+
print("img shape", img.size)
|
| 35 |
+
|
| 36 |
+
# get shape of all masks
|
| 37 |
+
mask = Image.open(mask_path)
|
| 38 |
+
if mask.size not in shape_mask_list:
|
| 39 |
+
shape_mask_list.append(mask.size)
|
| 40 |
+
print("mask size", mask.size)
|
| 41 |
+
|
| 42 |
+
# get all possible classes
|
| 43 |
+
vals, counts = np.unique(np.asarray(mask), return_counts=True)
|
| 44 |
+
|
| 45 |
+
for val, count in zip(vals, counts):
|
| 46 |
+
if val in class_instances:
|
| 47 |
+
class_instances[val] += count
|
| 48 |
+
else:
|
| 49 |
+
class_instances[val] = count
|
| 50 |
+
|
| 51 |
+
if k % 100 == 0:
|
| 52 |
+
os.system("clear")
|
| 53 |
+
print(k)
|
| 54 |
+
for key in class_instances.keys():
|
| 55 |
+
print("class ", key, ": ", class_instances[key])
|
| 56 |
+
|
subset.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# create a subset of files in a folder
|
| 2 |
+
import argparse
|
| 3 |
+
import glob
|
| 4 |
+
import os
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pdb
|
| 7 |
+
|
| 8 |
+
# for repeatability
|
| 9 |
+
ratio = 0.25
|
| 10 |
+
np.random.seed(42)
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
|
| 14 |
+
# get path from cmd parameter
|
| 15 |
+
|
| 16 |
+
# pdb.set_trace()
|
| 17 |
+
|
| 18 |
+
ap = argparse.ArgumentParser()
|
| 19 |
+
ap.add_argument("-i", "--pathimage", required=True, help="path to folder")
|
| 20 |
+
ap.add_argument("-t", "--pathtarget", required=True, help="path to folder")
|
| 21 |
+
args = vars(ap.parse_args())
|
| 22 |
+
|
| 23 |
+
root = args["pathimage"]
|
| 24 |
+
root2 = args["pathtarget"]
|
| 25 |
+
os.makedirs(os.path.join(root, "subset"), exist_ok=True)
|
| 26 |
+
os.makedirs(os.path.join(root2, "subset"), exist_ok=True)
|
| 27 |
+
|
| 28 |
+
man_set_ratio = int(input("set the percentage of the subset (eg. 25): "))
|
| 29 |
+
|
| 30 |
+
# set ratio if man_set_ratio is valid
|
| 31 |
+
if 100 > man_set_ratio > 0:
|
| 32 |
+
ratio = man_set_ratio/100
|
| 33 |
+
|
| 34 |
+
# get all files of certain type
|
| 35 |
+
f_types = ('*.jpg', '*.jpeg', '*.png', '*.bmp', '*.tif')
|
| 36 |
+
all_files_images = []
|
| 37 |
+
all_files_target = []
|
| 38 |
+
for f_type in f_types:
|
| 39 |
+
all_files_images.extend(sorted(glob.glob(os.path.join(root, f_type))))
|
| 40 |
+
all_files_target.extend(sorted(glob.glob(os.path.join(root2, f_type))))
|
| 41 |
+
|
| 42 |
+
# get random idx
|
| 43 |
+
randomIdx = np.random.permutation(len(all_files_images))
|
| 44 |
+
files_sel_idx = randomIdx[0:int(ratio * len(all_files_images))]
|
| 45 |
+
|
| 46 |
+
for n, idx in enumerate(files_sel_idx):
|
| 47 |
+
# os.system('cls')
|
| 48 |
+
print(int(n/len(files_sel_idx)*10000)/100)
|
| 49 |
+
os.rename(all_files_images[idx], os.path.join(root, "subset", os.path.basename(all_files_images[idx])))
|
| 50 |
+
os.rename(all_files_target[idx], os.path.join(root2, "subset", os.path.basename(all_files_target[idx])))
|
| 51 |
+
|
| 52 |
+
'''
|
| 53 |
+
# move potentially existing label file
|
| 54 |
+
if os.path.exists(all_files[idx][:-3] + "xml"):
|
| 55 |
+
os.rename(all_files[idx][:-3] + "xml", root + "\\subset\\" + os.path.basename(all_files[idx][:-3] + "xml"))
|
| 56 |
+
if os.path.exists(all_files[idx][:-3] + "json"):
|
| 57 |
+
os.rename(all_files[idx][:-3] + "json", root + "\\subset\\" + os.path.basename(all_files[idx][:-3] + "json"))
|
| 58 |
+
if os.path.exists(all_files[idx][:-3] + "txt"):
|
| 59 |
+
os.rename(all_files[idx][:-3] + "txt", root + "\\subset\\" + os.path.basename(all_files[idx][:-3] + "txt"))
|
| 60 |
+
'''
|