李沐46_语义分割和数据集——自学笔记

语义分割

语义分割将图片中的每个像素分类到对应的类别。

实例分割(目标检测的进化版本)

如果有物体,会区别同一类的不同物体。

语义分割重要数据集:Pascal VOC2012

%matplotlib inline
import os
import torch
import torchvision
from d2l import torch as d2l

下载数据集VOC,大小2GB,类型tar

d2l.DATA_HUB['voc2012'] = (d2l.DATA_URL + 'VOCtrainval_11-May-2012.tar','4e443f8a2eca6b1dac8a6c57641b67dd40621a49')voc_dir = d2l.download_extract('voc2012', 'VOCdevkit/VOC2012')
Downloading ../data/VOCtrainval_11-May-2012.tar from http://d2l-data.s3-accelerate.amazonaws.com/VOCtrainval_11-May-2012.tar...

读取输入的图像和标签

def read_voc_images(voc_dir, is_train=True):"""读取所有VOC图像并标注"""txt_fname = os.path.join(voc_dir, 'ImageSets', 'Segmentation','train.txt' if is_train else 'val.txt')mode = torchvision.io.image.ImageReadMode.RGBwith open(txt_fname, 'r') as f:images = f.read().split()features, labels = [], []for i, fname in enumerate(images):features.append(torchvision.io.read_image(os.path.join(voc_dir, 'JPEGImages', f'{fname}.jpg')))labels.append(torchvision.io.read_image(os.path.join(voc_dir, 'SegmentationClass' ,f'{fname}.png'), mode))return features, labelstrain_features, train_labels = read_voc_images(voc_dir, True)

下面我们绘制前5个输入图像及其标签。 在标签图像中,白色和黑色分别表示边框和背景,而其他颜色则对应不同的类别

n = 5
imgs = train_features[0:n] + train_labels[0:n]
imgs = [img.permute(1,2,0) for img in imgs]
d2l.show_images(imgs, 2, n);

在这里插入图片描述

列举RGB颜色值和类名


VOC_COLORMAP = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],[0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],[64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],[64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],[0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],[0, 64, 128]]VOC_CLASSES = ['background', 'aeroplane', 'bicycle', 'bird', 'boat','bottle', 'bus', 'car', 'cat', 'chair', 'cow','diningtable', 'dog', 'horse', 'motorbike', 'person','potted plant', 'sheep', 'sofa', 'train', 'tv/monitor']

定义了voc_colormap2label函数来构建从上述RGB颜色值到类别索引的映射,而voc_label_indices函数将RGB值映射到在Pascal VOC2012数据集中的类别索引


def voc_colormap2label():"""构建从RGB到VOC类别索引的映射"""colormap2label = torch.zeros(256 ** 3, dtype=torch.long)for i, colormap in enumerate(VOC_COLORMAP):colormap2label[(colormap[0] * 256 + colormap[1]) * 256 + colormap[2]] = ireturn colormap2labeldef voc_label_indices(colormap, colormap2label):"""将VOC标签中的RGB值映射到它们的类别索引"""colormap = colormap.permute(1, 2, 0).numpy().astype('int32')idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256+ colormap[:, :, 2])return colormap2label[idx]

第一张样本图像,飞机头部索引标签是1,背景索引是0

y = voc_label_indices(train_labels[0], voc_colormap2label())
y[105:115, 130:140], VOC_CLASSES[1]
(tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],[0, 0, 0, 0, 0, 1, 1, 1, 1, 1],[0, 0, 0, 0, 0, 1, 1, 1, 1, 1],[0, 0, 0, 0, 1, 1, 1, 1, 1, 1],[0, 0, 0, 0, 0, 1, 1, 1, 1, 1],[0, 0, 0, 0, 0, 1, 1, 1, 1, 1],[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],[0, 0, 0, 0, 0, 0, 0, 0, 1, 1]]),'aeroplane')

数据预处理

使用图像增广中的随机裁剪,裁剪输入图像和标签的相同区域。


def voc_rand_crop(feature, label, height, width):"""随机裁剪特征和标签图像"""rect = torchvision.transforms.RandomCrop.get_params(feature, (height, width))feature = torchvision.transforms.functional.crop(feature, *rect)label = torchvision.transforms.functional.crop(label, *rect)return feature, labelimgs = []
for _ in range(n):imgs += voc_rand_crop(train_features[0], train_labels[0], 200, 300)imgs = [img.permute(1, 2, 0) for img in imgs]
d2l.show_images(imgs[::2] + imgs[1::2], 2, n);

在这里插入图片描述

自定义语义分割数据集

通过继承高级API提供的Dataset类,自定义了一个语义分割数据集类VOCSegDataset。

通过实现__getitem__函数,我们可以任意访问数据集中索引为idx的输入图像及其每个像素的类别索引。

由于数据集中有些图像的尺寸可能小于随机裁剪所指定的输出尺寸,这些样本可以通过自定义的filter函数移除掉。

定义了normalize_image函数,从而对输入图像的RGB三个通道的值分别做标准化。

class VOCSegDataset(torch.utils.data.Dataset):"""一个用于加载VOC数据集的自定义数据集"""def __init__(self, is_train, crop_size, voc_dir):self.transform = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])self.crop_size = crop_sizefeatures, labels = read_voc_images(voc_dir, is_train=is_train)self.features = [self.normalize_image(feature)for feature in self.filter(features)]self.labels = self.filter(labels)self.colormap2label = voc_colormap2label()print('read ' + str(len(self.features)) + ' examples')def normalize_image(self, img):return self.transform(img.float() / 255)def filter(self, imgs):return [img for img in imgs if (img.shape[1] >= self.crop_size[0] andimg.shape[2] >= self.crop_size[1])]def __getitem__(self, idx):feature, label = voc_rand_crop(self.features[idx], self.labels[idx],*self.crop_size)return (feature, voc_label_indices(label, self.colormap2label))def __len__(self):return len(self.features)

读取数据集

自定义的VOCSegDataset类来分别创建训练集和测试集的实例。 假设我们指定随机裁剪的输出图像的形状为320X480, 下面我们可以查看训练集和测试集所保留的样本个数。

crop_size = (320, 480)
voc_train = VOCSegDataset(True, crop_size, voc_dir)
voc_test = VOCSegDataset(False, crop_size, voc_dir)
read 1114 examples
read 1078 examples

设批量大小为64,我们定义训练集的迭代器。 打印第一个小批量的形状会发现:与图像分类或目标检测不同,这里的标签是一个三维数组。

batch_size = 64
train_iter = torch.utils.data.DataLoader(voc_train, batch_size, shuffle=True,drop_last=True,num_workers=d2l.get_dataloader_workers())
for X, Y in train_iter:print(X.shape)print(Y.shape)break
/usr/local/lib/python3.10/dist-packages/torch/utils/data/dataloader.py:558: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.warnings.warn(_create_warning_msg(
/usr/lib/python3.10/multiprocessing/popen_fork.py:66: RuntimeWarning: os.fork() was called. os.fork() is incompatible with multithreaded code, and JAX is multithreaded, so this will likely lead to a deadlock.self.pid = os.fork()torch.Size([64, 3, 320, 480])
torch.Size([64, 320, 480])

整合所有组件

定义以下load_data_voc函数来下载并读取Pascal VOC2012语义分割数据集。 它返回训练集和测试集的数据迭代器

def load_data_voc(batch_size, crop_size):"""加载VOC语义分割数据集"""voc_dir = d2l.download_extract('voc2012', os.path.join('VOCdevkit', 'VOC2012'))num_workers = d2l.get_dataloader_workers()train_iter = torch.utils.data.DataLoader(VOCSegDataset(True, crop_size, voc_dir), batch_size,shuffle=True, drop_last=True, num_workers=num_workers)test_iter = torch.utils.data.DataLoader(VOCSegDataset(False, crop_size, voc_dir), batch_size,drop_last=True, num_workers=num_workers)return train_iter, test_iter

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/823345.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java -- (part12)

一.权限修饰符 1.属性:用private ->封装思想 2.成员方法public ->便于调用 3.构造public ->便于new对象 二.final关键字 1.修饰类 a.格式 -- public final class 类名 b.特点:不能被继承 2.修饰方法 a.格式:修饰符 final 返回值类型 方法名(形参){} b.特点…

C++内存管理——new/delete、operator new/operator delete

内存管理 int globalVar 1; static int staticGlobalVar 1; void Test() {static int staticVar 1;int localVar 1;int num1[10] { 1, 2, 3, 4 };char char2[] "abcd";const char* pChar3 "abcd";int* ptr1 (int*)malloc(sizeof(int) * 4);int* pt…

c++ lambda表达式的使用方法

c lambda表达式的使用方法 C11引入了lambda表达式,它是一种轻量级的匿名函数,允许我们在需要函数的地方直接定义函数,而无需专门声明函数。lambda表达式的语法简洁,并且非常灵活,可以捕获外部变量,具有与普…

Mapper 编写的常用方式

第一种&#xff1a;接口实现类继承 SqlSessionDaoSupport&#xff1a; 使用此种方法需要编写mapper 接口&#xff0c;mapper 接口实现类、mapper.xml 文件。 1&#xff1a; 在 sqlMapConfig.xml 中配置 mapper.xml 的位置 <mappers><mapper resource"mapper.x…

技术速递|.NET 智能组件简介 – AI 驱动的 UI 控件

作者&#xff1a;Daniel Roth 排版&#xff1a;Alan Wang AI 的最新进展有望彻底改变我们与软件交互和使用软件的方式。然而&#xff0c;将 AI 功能集成到现有软件中可能面临一些挑战。因此&#xff0c;我们开发了新的 .NET 智能组件&#xff0c;这是一组真正有用的 AI 支持的 …

OCP-数据库中的小米SU7

oracle ocp ​数据库中的SU7 ​好看又好用 需要找工作和落户的快来

帮助中心最核心的内容,你都知道吗?

帮助中心&#xff0c;其实就是个解决问题的“百事通”。当你在使用某产品时&#xff0c;遇到了一些问题&#xff0c;就可以到帮助中心去查询相关的信息以解决问题。很多公司都会搭建帮助中心&#xff0c;那么&#xff0c;帮助中心的核心内容都有哪些呢&#xff1f;这就是今天我…

Chrome 中安装 Vue 插件 vue-devtools 的简易教程

Vue.js 是一种流行的 JavaScript 框架&#xff0c;用于构建交互式的用户界面。它提供了丰富的开发工具和插件&#xff0c;其中一个非常有用的插件就是 vue-devtools。vue-devtools 可以让开发者在 Chrome 浏览器中轻松调试和检查 Vue 组件的状态、事件和数据流。本篇教程将向你…

损失函数:Cross Entropy Loss (交叉熵损失函数)

损失函数&#xff1a;Cross Entropy Loss &#xff08;交叉熵损失函数&#xff09; 前言相关介绍Softmax函数代码实例 Cross Entropy Loss &#xff08;交叉熵损失函数&#xff09;Cross Entropy Loss与BCE loss区别代码实例 前言 由于本人水平有限&#xff0c;难免出现错漏&am…

【yolo数据集合并方法】

yolo数据集合并方法 1.数据集容2.数据集合并 1.数据集容 包含训练集、验证集和测试集。 每一个数据集中包含图像文件夹和标签文件夹。 yaml文件中定义了配置参数&#xff0c;包括目标识别的class类别&#xff1a; 2.数据集合并 需要修改labels文件夹下txt文件class信息&…

记录shell编程中$1,$@等符号的含义

笔者最近老是遇到shell中的$相关的题目&#xff0c;于是打算写篇文章记录一下。考虑到并没有特别多需要解释的内容&#xff0c;所以并不会进行介绍&#xff0c;上图上表上代码&#xff0c;让机器说话&#xff0c;machine always right test.sh #/bin/bash echo $# $# echo …

gcc原理和使用

gcc gcc是什么 GCC&#xff0c;全称 GNU Compiler Collection&#xff08;GNU 编译器套件&#xff09;&#xff0c;是一套功能强大的编程语言编译器&#xff0c;由自由软件基金会&#xff08;Free Software Foundation, FSF&#xff09;作为GNU项目的一部分开发和维护。它最初…

宝塔使用笔记

1.配置ssl 验证方式&#xff1a;文件验证和dns验证都试一下 参考&#xff1a; https://app.applebyme.cn/cloud/https/23050.html

自定义类型: 联合体和枚举

本文索引 1. 联合体1.1 联合体类型的声明1.2 联合体的特点1.3 相同成员的结构体和联合体对比1.4 联合体大小的计算 2. 枚举类型2.1 枚举类型的声明2.2 枚举类型的优点2.3 枚举类型的使用 前言 : 书接上文, 下面我将继续详解C语言的剩下两个自定义类型: 联合体和枚举 个人主页…

【Linux】tcpdump P2 - 捕获和查看网络数据包

文章目录 7. 选项 -r8. 主机选项9. 逻辑运算符10. 关键字 net11. 关键字 ether12. 关键字 ip6总结 本文主要介绍了如何使用tcpdump来捕获和查看网络数据包。 7. 选项 -r 如果你已经走到了这一步并且写入了一个.pcap文件&#xff0c;你知道你不能使用简单的文本编辑器来读取文…

Linux命令学习—DNS 服务器

1.1、DNS 服务器介绍 DNS domain name system 域名系统 1、网络中&#xff0c;计算机通过 IP 地址来通信 IP 地址记忆困难&#xff0c;为计算机起个好名字 域名概念的提出 DNS 服务&#xff1a;为主机建立 IP 地址与域名之间的映射关系&#xff0c;使用域名来唯一标识网络…

当面试问你接口测试时,不要再说不会了!

很多人会谈论接口测试。到底什么是接口测试&#xff1f;如何进行接口测试&#xff1f;这篇文章会帮到你。 01 前端和后端 在谈论接口测试之前&#xff0c;让我们先明确前端和后端这两个概念。 前端是我们在网页或移动应用程序中看到的页面&#xff0c;它由 HTML 和 CSS 编写…

第十五届蓝桥杯复盘python大学A组——试题B 召唤数学精灵

按照正常思路解决&#xff0c;由于累乘消耗大量时间&#xff0c;因此这不是一个明智的解决方案。 这段代码执行速度非常慢的原因在于它试图计算非常大的数的阶乘&#xff08;累乘&#xff09;&#xff0c;并且对于每一个i的值都执行这个计算。阶乘的增长是极其迅速的&#xff…

SQL数据库管理开发工具:DataGrip 2024(win/mac)激活版

JetBrains DataGrip是一款专业的SQL数据库管理开发工具。DataGrip允许您以不同的方式发展模式以及执行信息查询&#xff0c;并提供服务本地文化历史问题记录&#xff0c;可以提高跟踪您的所有学生活动并保护如果您不选择丢失您的工作。DataGrip允许您通过建立相应的操作按名称就…