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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
| 语义分割原理 除了实体就是背景 实例分割原理 实体分为实体1,实体2....,以及背景
---
## 数据准备 分割图像的标记 1.下载Labelme工具 我这里想用命令行安装结果一直报错=-=,最终还是使用了dmg包安装,切换python3.9后OK 2.将需要标记的图片放到文件夹中 3.准备一个label.txt文件,写好需要标记的类别 __ignore__ _background_ cat 4.执行命令自动启动Labelme labelme --labels labels.txt --nodata 5.点击左侧OpenDir,选中图片文件夹 6.点击左侧CreatePolygons,开始标注,标注完成后需要保存(json) 7.执行代码,转化为Mask python label2voc.py cats cats_output --label label.txt 其中cats文件夹是标记的图片与json文件 cats_output是最终输出的4个文件夹 JPEGImages(训练原图) SegmentationClass SegmentationClassPNG(转换Mask) SegmentationClassVisualization label.txt是上面设置的标签信息 ## label2voc.py #!/usr/bin/env python
from __future__ import print_function
import argparse import glob import os import os.path as osp import sys
import imgviz import numpy as np
import labelme
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("input_dir", help="input annotated directory") parser.add_argument("output_dir", help="output dataset directory") parser.add_argument("--labels", help="labels file", required=True) parser.add_argument( "--noviz", help="no visualization", action="store_true" ) args = parser.parse_args()
if osp.exists(args.output_dir): print("Output directory already exists:", args.output_dir) sys.exit(1) os.makedirs(args.output_dir) os.makedirs(osp.join(args.output_dir, "JPEGImages")) os.makedirs(osp.join(args.output_dir, "SegmentationClass")) os.makedirs(osp.join(args.output_dir, "SegmentationClassPNG")) if not args.noviz: os.makedirs( osp.join(args.output_dir, "SegmentationClassVisualization") ) print("Creating dataset:", args.output_dir)
class_names = [] class_name_to_id = {} for i, line in enumerate(open(args.labels).readlines()): class_id = i - 1 # starts with -1 class_name = line.strip() class_name_to_id[class_name] = class_id if class_id == -1: assert class_name == "__ignore__" continue elif class_id == 0: assert class_name == "_background_" class_names.append(class_name) class_names = tuple(class_names) print("class_names:", class_names) out_class_names_file = osp.join(args.output_dir, "class_names.txt") with open(out_class_names_file, "w") as f: f.writelines("\n".join(class_names)) print("Saved class_names:", out_class_names_file)
for filename in glob.glob(osp.join(args.input_dir, "*.json")): print("Generating dataset from:", filename)
label_file = labelme.LabelFile(filename=filename)
base = osp.splitext(osp.basename(filename))[0] out_img_file = osp.join(args.output_dir, "JPEGImages", base + ".jpg") out_lbl_file = osp.join( args.output_dir, "SegmentationClass", base + ".npy" ) out_png_file = osp.join( args.output_dir, "SegmentationClassPNG", base + ".png" ) if not args.noviz: out_viz_file = osp.join( args.output_dir, "SegmentationClassVisualization", base + ".jpg", )
with open(out_img_file, "wb") as f: f.write(label_file.imageData) img = labelme.utils.img_data_to_arr(label_file.imageData)
lbl, _ = labelme.utils.shapes_to_label( img_shape=img.shape, shapes=label_file.shapes, label_name_to_value=class_name_to_id, ) labelme.utils.lblsave(out_png_file, lbl)
np.save(out_lbl_file, lbl)
if not args.noviz: viz = imgviz.label2rgb( lbl, imgviz.rgb2gray(img), font_size=15, label_names=class_names, loc="rb", ) imgviz.io.imsave(out_viz_file, viz)
if __name__ == "__main__": main()
---
## 数据读取 标注工作完成需要使用PyTorch将数据读入
## dataset.py import os import torch import numpy as np
from torch.utils.data import Dataset from PIL import Image
class CatSegmentationDataset(Dataset): # 模型输入是3通道数据 in_channels = 3 # 模型输出是1通道数据 out_channels = 1
def __init__( self, images_dir, image_size=32, ):
print("Reading images...") # 原图所在的位置 image_root_path = images_dir + os.sep + 'JPEGImages' # Mask所在的位置 mask_root_path = images_dir + os.sep + 'SegmentationClassPNG' # 将图片与Mask读入后,分别存在image_slices与mask_slices中 self.image_slices = [] self.mask_slices = [] for im_name in os.listdir(image_root_path): mask_name = im_name.split('.')[0] + '.png'
image_path = image_root_path + os.sep + im_name mask_path = mask_root_path + os.sep + mask_name
im = np.asarray(Image.open(image_path).resize((image_size, image_size))) mask = np.asarray(Image.open(mask_path).resize((image_size, image_size))) self.image_slices.append(im / 255.) self.mask_slices.append(mask)
def __len__(self): return len(self.image_slices)
def __getitem__(self, idx):
image = self.image_slices[idx] mask = self.mask_slices[idx]
image = image.transpose(2, 0, 1) mask = mask[np.newaxis, :, :]
image = image.astype(np.float32) mask = mask.astype(np.float32)
return image, mask
---
## 模型训练(网络结构) UNet是一个非常实用的网络.它是一个典型的 Encoder-Decoder 类型的分割网络,网络结构非常简单 ## unet.py import torch import torch.nn as nn
class Block(nn.Module):
def __init__(self, in_channels, features): super(Block, self).__init__()
self.features = features
self.conv1 = nn.Conv2d( in_channels=in_channels, out_channels=features, kernel_size=3, padding='same', ) self.conv2 = nn.Conv2d( in_channels=features, out_channels=features, kernel_size=3, padding='same', )
def forward(self, input): x = self.conv1(input) x = nn.BatchNorm2d(num_features=self.features)(x) x = nn.ReLU(inplace=True)(x) x = self.conv2(x) x = nn.BatchNorm2d(num_features=self.features)(x) x = nn.ReLU(inplace=True)(x)
return x
class UNet(nn.Module):
def __init__(self, in_channels=3, out_channels=1, init_features=32): super(UNet, self).__init__()
features = init_features self.conv_encoder_1 = Block(in_channels, features) self.conv_encoder_2 = Block(features, features * 2) self.conv_encoder_3 = Block(features * 2, features * 4) self.conv_encoder_4 = Block(features * 4, features * 8)
self.bottleneck = Block(features * 8, features * 16)
self.upconv4 = nn.ConvTranspose2d( features * 16, features * 8, kernel_size=2, stride=2 ) self.conv_decoder_4 = Block((features * 8) * 2, features * 8) self.upconv3 = nn.ConvTranspose2d( features * 8, features * 4, kernel_size=2, stride=2 ) self.conv_decoder_3 = Block((features * 4) * 2, features * 4) self.upconv2 = nn.ConvTranspose2d( features * 4, features * 2, kernel_size=2, stride=2 ) self.conv_decoder_2 = Block((features * 2) * 2, features * 2) self.upconv1 = nn.ConvTranspose2d( features * 2, features, kernel_size=2, stride=2 ) self.decoder1 = Block(features * 2, features)
self.conv = nn.Conv2d( in_channels=features, out_channels=out_channels, kernel_size=1 )
def forward(self, x): conv_encoder_1_1 = self.conv_encoder_1(x) conv_encoder_1_2 = nn.MaxPool2d(kernel_size=2, stride=2)(conv_encoder_1_1)
conv_encoder_2_1 = self.conv_encoder_2(conv_encoder_1_2) conv_encoder_2_2 = nn.MaxPool2d(kernel_size=2, stride=2)(conv_encoder_2_1)
conv_encoder_3_1 = self.conv_encoder_3(conv_encoder_2_2) conv_encoder_3_2 = nn.MaxPool2d(kernel_size=2, stride=2)(conv_encoder_3_1)
conv_encoder_4_1 = self.conv_encoder_4(conv_encoder_3_2) conv_encoder_4_2 = nn.MaxPool2d(kernel_size=2, stride=2)(conv_encoder_4_1)
bottleneck = self.bottleneck(conv_encoder_4_2)
conv_decoder_4_1 = self.upconv4(bottleneck) conv_decoder_4_2 = torch.cat((conv_decoder_4_1, conv_encoder_4_1), dim=1) conv_decoder_4_3 = self.conv_decoder_4(conv_decoder_4_2)
conv_decoder_3_1 = self.upconv3(conv_decoder_4_3) conv_decoder_3_2 = torch.cat((conv_decoder_3_1, conv_encoder_3_1), dim=1) conv_decoder_3_3 = self.conv_decoder_3(conv_decoder_3_2)
conv_decoder_2_1 = self.upconv2(conv_decoder_3_3) conv_decoder_2_2 = torch.cat((conv_decoder_2_1, conv_encoder_2_1), dim=1) conv_decoder_2_3 = self.conv_decoder_2(conv_decoder_2_2)
conv_decoder_1_1 = self.upconv1(conv_decoder_2_3) conv_decoder_1_2 = torch.cat((conv_decoder_1_1, conv_encoder_1_1), dim=1) conv_decoder_1_3 = self.decoder1(conv_decoder_1_2)
return torch.sigmoid(self.conv(conv_decoder_1_3))
## 模型训练(优化方法) Dice Loss函数 当预测值的 Mask 与 GT 越相似,损失就越小;当预测值的 Mask 与 GT 差异度越大,损失就越大 ## loss.py import torch.nn as nn
class DiceLoss(nn.Module):
def __init__(self): super(DiceLoss, self).__init__() self.smooth = 1.0
def forward(self, y_pred, y_true): assert y_pred.size() == y_true.size() y_pred = y_pred.contiguous().view(-1) y_true = y_true.contiguous().view(-1) intersection = (y_pred * y_true).sum() dsc = (2. * intersection + self.smooth) / ( y_pred.sum() + y_true.sum() + self.smooth ) return 1. - dsc
## 模型训练开始 将模型,损失函数和优化方法串起来,看下整体的训练流程 ## train.py import argparse import json import os
import numpy as np import torch import torch.optim as optim from torch.utils.data import DataLoader from tqdm import tqdm
from dataset import CatSegmentationDataset as Dataset from loss import DiceLoss from unet import UNet
def main(args): makedirs(args) device = torch.device("cpu" if not torch.cuda.is_available() else args.device)
loader_train = data_loaders(args)
unet = UNet(in_channels=Dataset.in_channels, out_channels=Dataset.out_channels) unet.to(device)
dsc_loss = DiceLoss()
optimizer = optim.Adam(unet.parameters(), lr=args.lr)
#logger = Logger(args.logs) loss_train = []
step = 0
for epoch in tqdm(range(args.epochs), total=args.epochs): unet.train()
for i, data in enumerate(loader_train): step += 1
x, y_true = data x, y_true = x.to(device), y_true.to(device)
y_pred = unet(x) optimizer.zero_grad() loss = dsc_loss(y_pred, y_true)
loss_train.append(loss.item()) loss.backward() optimizer.step()
if (step + 1) % 10 == 0: print('Step ', step, 'Loss', np.mean(loss_train)) loss_train = []
torch.save(unet, args.ckpts + '/unet_epoch_{}.pth'.format(epoch))
def data_loaders(args): dataset_train = Dataset( images_dir=args.images, image_size=args.image_size, )
loader_train = DataLoader( dataset_train, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, )
return loader_train
def makedirs(args): os.makedirs(args.ckpts, exist_ok=True) os.makedirs(args.logs, exist_ok=True)
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Training U-Net model for segmentation of Cat" ) parser.add_argument( "--batch-size", type=int, default=16, help="Batch Size (default: 16)", ) parser.add_argument( "--epochs", type=int, default=100, help="Epoch number (default: 100)", ) parser.add_argument( "--lr", type=float, default=0.0001, help="Learning rate", ) parser.add_argument( "--device", type=str, default="cuda:0", help="Device for training (default: cuda:0)", ) parser.add_argument( "--workers", type=int, default=4, help="Workers' count (default: 4)", ) parser.add_argument( "--ckpts", type=str, default="./ckpts", help="folder to save weights" ) parser.add_argument( "--logs", type=str, default="./logs", help="folder to save logs" ) parser.add_argument( "--images", type=str, default="./data", help="root folder with images" ) parser.add_argument( "--image-size", type=int, default=256, help="target input image size (default: 256)", ) args = parser.parse_args() main(args)
---
## 模型预测 使用训练生成的模型来进行语义分割,看看结果呈现效果 ## predict_single.py import torch import numpy as np
from PIL import Image
img_size = (256, 256) # 加载模型 unet = torch.load('./ckpts/unet_epoch_99.pth')
unet.eval()
# 加载并处理输入图片 ori_image = Image.open('./PyTorchLearn/data/cutting_out/JPEGImages/cat.jpg')
im = np.asarray(ori_image.resize(img_size)) im = im / 255. im = im.transpose(2, 0, 1) im = im[np.newaxis, :, :] im = im.astype('float32') # 模型预测 output = unet(torch.from_numpy(im)).detach().numpy() # 模型输出转化为Mask图片 output = np.squeeze(output) output = np.where(output>0.5, 1, 0).astype(np.uint8) mask = Image.fromarray(output, mode='P') mask.putpalette([0,0,0, 0,128,0]) mask = mask.resize(ori_image.size) mask.save('output.png')
image = ori_image.convert('RGBA') mask = mask.convert('RGBA') # 合成 image_mask = Image.blend(image, mask, 0.3) image_mask.save("output_mask.png")
|