UNet语义分割实战:使用UNet实现对人物的抠图(1),特殊渠道拿到阿里大厂面试真题

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Python全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img



既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Python知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip1024c (备注Python)
img

正文

net = UNet(n_channels=3, n_classes=2, bilinear=True)

logging.info(f’Network:\n’

f’\t{net.n_channels} input channels\n’

f’\t{net.n_classes} output channels (classes)\n’

f’\t{“Bilinear” if net.bilinear else “Transposed conv”} upscaling’)

if args.load:

net.load_state_dict(torch.load(args.load, map_location=device))

logging.info(f’Model loaded from {args.load}')

设置UNet参数,n_channels是imgs图片的通道数,如果是rgb则是3,如果是黑白图片就是1,n_classes设置为2,在这里把背景也当做一个类别,所以有两个类。

如果设置了权重文件,则加载权重文件,加载权重文件做迁移学习可以加快训练,减少迭代次数,所以如果有还是尽量加载预训练权重。

接下来修改train_net函数的逻辑。

try:

dataset = CarvanaDataset(dir_img, dir_mask, img_scale)

except (AssertionError, RuntimeError):

dataset = BasicDataset(dir_img, dir_mask, img_scale)

2. Split into train / validation partitions

n_val = int(len(dataset) * val_percent)

n_train = len(dataset) - n_val

train_set, val_set = random_split(dataset, [n_train, n_val], generator=torch.Generator().manual_seed(0))

3. Create data loaders

loader_args = dict(batch_size=batch_size, num_workers=4, pin_memory=True)

train_loader = DataLoader(train_set, shuffle=True, **loader_args)

val_loader = DataLoader(val_set, shuffle=False, drop_last=True, **loader_args)

1、加载数据集。

2、按照比例切分训练集和验证集。

3、将训练集和验证集放入DataLoader中。

(Initialize logging)

experiment = wandb.init(project=‘U-Net’, resume=‘allow’, anonymous=‘must’)

experiment.config.update(dict(epochs=epochs, batch_size=batch_size, learning_rate=learning_rate,

val_percent=val_percent, save_checkpoint=save_checkpoint, img_scale=img_scale,

amp=amp))

设置wandb,wandb是一款非常好用的可视化工具。安装和使用方法见:https://blog.csdn.net/hhhhhhhhhhwwwwwwwwww/article/details/116124285。

4. Set up the optimizer, the loss, the learning rate scheduler and the loss scaling for AMP

optimizer = optim.RMSprop(net.parameters(), lr=learning_rate, weight_decay=1e-8, momentum=0.9)

scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, ‘max’, patience=2) # goal: maximize Dice score

grad_scaler = torch.cuda.amp.GradScaler(enabled=amp)

criterion = nn.CrossEntropyLoss()

global_step = 0

1、设置优化器optimizer为RMSprop,我也尝试了改为SGD,通常情况下SGD的表现好一些。但是在训练时发现,二者最终的结果都差不多。

2、ReduceLROnPlateau学习率调整策略,和keras的类似。本次选择用的是Dice score,所以将mode设置为max,当得分不再上升时,则降低学习率。

3、设置loss为 nn.CrossEntropyLoss()。交叉熵,多分类常用的loss。

接下来是train部分的逻辑,这里需要修改的如下:

masks_pred = net(images)

true_masks = F.one_hot(true_masks.squeeze_(1), net.n_classes).permute(0, 3, 1, 2).float()

print(masks_pred.shape)

print(true_masks.shape)

masks_pred = net(images)计算出来的结果是:[batch, 2, 400, 300],其中2代表两个类别。

true_masks.shape是[batch, 1, 400, 300],所以要对true_masks做onehot处理。如果直接对true_masks做onehot处理,你会发现处理后的shape是[batch, 1, 400, 300,2],这样就和masks_pred 对不上了,所以在做onehot之前,先将第二维(也就是1这一维度)去掉,这样onehot后的shape是[batch, 400, 300,2],然后调整顺序,和masks_pred 的维度对上。

接下来就要计算loss,loss分为两部分,一部分时交叉熵,另一部分是dice_loss,这两个loss各有优势,组合使用效果更优。dice_loss在utils/dice_sorce.py文件中,代码如下:

import torch

from torch import Tensor

def dice_coeff(input: Tensor, target: Tensor, reduce_batch_first: bool = False, epsilon=1e-6):

Average of Dice coefficient for all batches, or for a single mask

assert input.size() == target.size()

if input.dim() == 2 and reduce_batch_first:

raise ValueError(f’Dice: asked to reduce batch but got tensor without batch dimension (shape {input.shape})')

if input.dim() == 2 or reduce_batch_first:

inter = torch.dot(input.reshape(-1), target.reshape(-1))

sets_sum = torch.sum(input) + torch.sum(target)

if sets_sum.item() == 0:

sets_sum = 2 * inter

return (2 * inter + epsilon) / (sets_sum + epsilon)

else:

compute and average metric for each batch element

dice = 0

for i in range(input.shape[0]):

dice += dice_coeff(input[i, …], target[i, …])

return dice / input.shape[0]

def dice_coeff_1(pred, target):

smooth = 1.

num = pred.size(0)

m1 = pred.view(num, -1) # Flatten

m2 = target.view(num, -1) # Flatten

intersection = (m1 * m2).sum()

return 1 - (2. * intersection + smooth) / (m1.sum() + m2.sum() + smooth)

def multiclass_dice_coeff(input: Tensor, target: Tensor, reduce_batch_first: bool = False, epsilon=1e-6):

Average of Dice coefficient for all classes

assert input.size() == target.size()

dice = 0

for channel in range(input.shape[1]):

dice += dice_coeff(input[:, channel, …], target[:, channel, …], reduce_batch_first, epsilon)

return dice / input.shape[1]

def dice_loss(input: Tensor, target: Tensor, multiclass: bool = False):

Dice loss (objective to minimize) between 0 and 1

assert input.size() == target.size()

fn = multiclass_dice_coeff if multiclass else dice_coeff

return 1 - fn(input, target, reduce_batch_first=True)

导入到train.py中,然后和交叉熵组合作为本项目的loss。

loss = criterion(masks_pred, true_masks) \

  • dice_loss(F.softmax(masks_pred, dim=1).float(),

true_masks,

multiclass=True)

接下来是对evaluate函数的逻辑做修改。

mask_true = mask_true.to(device=device, dtype=torch.long)

mask_true = F.one_hot(mask_true.squeeze_(1), net.n_classes).permute(0, 3, 1, 2).float()

增加对mask_trued的onehot逻辑。

修改完上面的逻辑就可以开始训练了。

image-20220406111550682

测试

=============================================================

完成训练后就可以测试了。打开predict.py,修改全局参数:

def get_args():

parser = argparse.ArgumentParser(description=‘Predict masks from input images’)

parser.add_argument(‘–model’, ‘-m’, default=‘checkpoints/checkpoint_epoch7.pth’, metavar=‘FILE’,

help=‘Specify the file in which the model is stored’)

parser.add_argument(‘–input’, ‘-i’, metavar=‘INPUT’,default=‘test/00002.png’, nargs=‘+’, help=‘Filenames of input images’)

parser.add_argument(‘–output’, ‘-o’, metavar=‘INPUT’,default=‘00001.png’, nargs=‘+’, help=‘Filenames of output images’)

parser.add_argument(‘–viz’, ‘-v’, action=‘store_true’,

help=‘Visualize the images as they are processed’)

parser.add_argument(‘–no-save’, ‘-n’, action=‘store_true’,default=False, help=‘Do not save the output masks’)

parser.add_argument(‘–mask-threshold’, ‘-t’, type=float, default=0.5,

help=‘Minimum probability value to consider a mask pixel white’)

parser.add_argument(‘–scale’, ‘-s’, type=float, default=0.5,

help=‘Scale factor for the input images’)

model:设置权重文件路径。这里修改为自己训练的权重文件。

scale:0.5,和训练的参数对应上。

其他的参数,通过命令输入。

def mask_to_image(mask: np.ndarray):

if mask.ndim == 2:

return Image.fromarray((mask * 255).astype(np.uint8))

elif mask.ndim == 3:

img_np=(np.argmax(mask, axis=0) * 255 / (mask.shape[0]-1)).astype(np.uint8)

print(img_np.shape)

print(np.max(img_np))

return Image.fromarray(img_np)

img_np=(np.argmax(mask, axis=0) * 255 / (mask.shape[0]-1)).astype(np.uint8)这里的逻辑需要修改。

源代码:

return Image.fromarray((np.argmax(mask, axis=0) * 255 / mask.shape[0]).astype(np.uint8))

我们增加了一类背景,所以mask.shape[0]为2,需要减去背景。

展示结果的方法也需要修改;

def plot_img_and_mask(img, mask):

print(mask.shape)

classes = mask.shape[0] if len(mask.shape) > 2 else 1

fig, ax = plt.subplots(1, classes + 1)

ax[0].set_title(‘Input image’)

ax[0].imshow(img)

if classes > 1:

for i in range(classes):

ax[i + 1].set_title(f’Output mask (class {i + 1})')

ax[i + 1].imshow(mask[i, :, :])

else:

ax[1].set_title(f’Output mask’)

ax[1].imshow(mask)

plt.xticks([]), plt.yticks([])

plt.show()

将原来的ax[i + 1].imshow(mask[:, :, i])改为:ax[i + 1].imshow(mask[i, :, :])。

执行命令:

python predict.py -i test/00002.png -o output.png -v

输出结果:

image-20220406124311843

到这里我们已经实现将人物从背景图片中完整的抠出来了!

总结

=============================================================

本文实现了用Unet对图像做分割,通过本文,你可以学习到:

文末有福利领取哦~

👉一、Python所有方向的学习路线

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。img

👉二、Python必备开发工具

img
👉三、Python视频合集

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
img

👉 四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。(文末领读者福利)
img

👉五、Python练习题

检查学习结果。
img

👉六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
img

img

👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024c (备注python)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
img

img

👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024c (备注python)
[外链图片转存中…(img-tXuquZJG-1713393663442)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 18
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值