当前位置:   article > 正文

13 计算机视觉-代码详解_计算机视觉代码

计算机视觉代码

13.2 微调

为了防止在训练集上过拟合,有两种办法,第一种是扩大训练集数量,但是需要大量的成本;第二种就是应用迁移学习,将源数据学习到的知识迁移到目标数据集,即在把在源数据训练好的参数和模型(除去输出层)直接复制到目标数据集训练。

  1. # IPython魔法函数,可以不用执行plt .show()
  2. %matplotlib inline
  3. import os
  4. import torch
  5. import torchvision
  6. from torch import nn
  7. from d2l import torch as d2l

13.2.1 获取数据集

  1. #@save
  2. d2l.DATA_HUB['hotdog'] = (d2l.DATA_URL + 'hotdog.zip',
  3. 'fba480ffa8aa7e0febbb511d181409f899b9baa5')
  4. data_dir = d2l.download_extract('hotdog')
  5. train_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'train'))
  6. test_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'test'))
  7. hotdogs = [train_imgs[i][0] for i in range(8)]
  8. not_hotdogs = [train_imgs[-i-1][0] for i in range(8)]
  9. # 展示2行8列矩阵的图片,共16张
  10. d2l.show_images(hotdogs+not_hotdogs,2,8,scale=1.5)
  1. # 使用RGB通道的均值和标准差,以标准化每个通道
  2. normalize = torchvision.transforms.Normalize(
  3. [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
  4. # 图像增广
  5. train_augs = torchvision.transforms.Compose([
  6. torchvision.transforms.RandomResizedCrop(224),
  7. torchvision.transforms.RandomHorizontalFlip(),
  8. torchvision.transforms.ToTensor(),
  9. normalize])
  10. test_augs = torchvision.transforms.Compose([
  11. torchvision.transforms.Resize([256, 256]),
  12. torchvision.transforms.CenterCrop(224),
  13. torchvision.transforms.ToTensor(),
  14. normalize])

 13.2.2 初始化模型

  1. # 自动下载网上的训练模型
  2. finetune_net = torchvision.models.resnet18(pretrained=True)
  3. # 输入张量的形状还是源输入张量大小,输入张量大小改为2
  4. finetune_net.fc = nn.Linear(finetune_net.fc.in_features, 2)
  5. nn.init.xavier_uniform_(finetune_net.fc.weight);

13.2.3 微调模型

  1. # 如果param_group=True,输出层中的模型参数将使用十倍的学习率
  2. # 如果param_group=False,输出层中模型参数为随机值
  3. # 训练模型
  4. def train_fine_tuning(net, learning_rate, batch_size=128, num_epochs=5,
  5. param_group=True):
  6. train_iter = torch.utils.data.DataLoader(torchvision.datasets.ImageFolder(
  7. os.path.join(data_dir, 'train'), transform=train_augs),
  8. batch_size=batch_size, shuffle=True)
  9. test_iter = torch.utils.data.DataLoader(torchvision.datasets.ImageFolder(
  10. os.path.join(data_dir, 'test'), transform=test_augs),
  11. batch_size=batch_size)
  12. devices = d2l.try_all_gpus()
  13. loss = nn.CrossEntropyLoss(reduction="none")
  14. if param_group:
  15. params_1x = [param for name, param in net.named_parameters()
  16. if name not in ["fc.weight", "fc.bias"]]
  17. # params_1x的参数使用learning_rate学习率, net.fc.parameters()的参数使用0.001的学习率
  18. trainer = torch.optim.SGD([{'params': params_1x},
  19. {'params': net.fc.parameters(),
  20. 'lr': learning_rate * 10}],
  21. lr=learning_rate, weight_decay=0.001)
  22. else:
  23. trainer = torch.optim.SGD(net.parameters(), lr=learning_rate,
  24. weight_decay=0.001)
  25. d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,
  26. devices)
  27. train_fine_tuning(finetune_net, 5e-5)

13.3 目标检测和边界框

有时候不仅要识别图像的类别,还需要识别图像的位置。在计算机视觉中叫做目标识别或者目标检测。这小节是介绍目标检测的深度学习方法。

  1. %matplotlib inline
  2. import torch
  3. from d2l import torch as d2l
  4. #@save
  5. def box_corner_to_center(boxes):
  6. """从(左上,右下)转换到(中间,宽度,高度)"""
  7. x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
  8. # cx,xy,w,h的维度是n
  9. cx = (x1 + x2) / 2
  10. cy = (y1 + y2) / 2
  11. w = x2 - x1
  12. h = y2 - y1
  13. # torch.stack()沿着新维度对张量进行链接。boxes最开始维度是(n,4),axis=-1表示倒数第一个维度
  14. # torch.stack()将(cx, cy, w, h)的维度n将其沿着倒数第一个维度拼接在一起,又是(n,4)
  15. boxes = torch.stack((cx, cy, w, h), axis=-1)
  16. return boxes
  17. #@save
  18. def box_center_to_corner(boxes):
  19. """从(中间,宽度,高度)转换到(左上,右下)"""
  20. cx, cy, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
  21. x1 = cx - 0.5 * w
  22. y1 = cy - 0.5 * h
  23. x2 = cx + 0.5 * w
  24. y2 = cy + 0.5 * h
  25. boxes = torch.stack((x1, y1, x2, y2), axis=-1)
  26. return boxes

13.4 锚框

目标检测算法通常会在图像中采集大量的样本,本小节介绍其中一个采样办法:以某个像素为中心,生成多个不同缩放比和宽高比的边界框。

13.4.1 生成多个锚框

  1. %matplotlib inline
  2. import torch
  3. from d2l import torch as d2l
  4. torch.set_printoptions(2) # 精简输出精度,显示小数点后2位
  5. """
  6. 形成多个锚框
  7. params:
  8. data:图像(批量大小,通道数,高,宽)
  9. sizes:缩放比尺寸集合
  10. ratios:宽高比集合
  11. """
  12. def multibox_prior(data, sizes, ratios):
  13. # 获取data后两位的值,也就是图像的高和宽
  14. in_height, in_width = data.shape[-2:]
  15. """
  16. params:
  17. device:cpu或者gpu
  18. num_sizes:尺寸的个数n
  19. num_ratios:宽高比个数m
  20. """
  21. device, num_sizes, num_ratios = data.device, len(sizes), len(ratios)
  22. # 以同一像素为中心的锚框数量n+m-1
  23. boxes_per_pixel = (num_sizes + num_ratios - 1)
  24. size_tensor = torch.tensor(sizes, device=device)
  25. ratio_tensor = torch.tensor(ratios, device=device)
  26. # offset:为了将锚点移动到像素的中心,需要设置偏移量。
  27. # steps:归一化,将宽高规化到0-1之间,因为一个像素的高为1且宽为1,我们选择偏移我们的中心0.5
  28. offset_h, offset_w = 0.5, 0.5
  29. steps_h = 1.0 / in_height # 在y轴上缩放步长
  30. steps_w = 1.0 / in_width # 在x轴上缩放步长
  31. # 假设宽高512*216 那么torch.arange(in_height, device=device)=【0,1,2...511】,移动到中心就是[0.5,1.5...511.5]
  32. # 第一步:torch.arange(in_height, device=device) + offset_h代表移动到每个像素的中心,因为每个像素1*1大小.
  33. # 第二步:宽高进行归一化
  34. center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
  35. center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w
  36. """
  37. a = torch.tensor([1, 2, 3, 4])
  38. b = torch.tensor([4, 5, 6])
  39. x, y = torch.meshgrid(a, b,indexing='ij')
  40. print:tensor([[1, 1, 1],
  41. [2, 2, 2],
  42. [3, 3, 3],
  43. [4, 4, 4]])
  44. tensor([[4, 5, 6],
  45. [4, 5, 6],
  46. [4, 5, 6],
  47. [4, 5, 6]])
  48. x, y = torch.meshgrid(a, b,indexing='xy')
  49. print:tensor([[1, 2, 3, 4],
  50. [1, 2, 3, 4],
  51. [1, 2, 3, 4]])
  52. tensor([[4, 4, 4, 4],
  53. [5, 5, 5, 5],
  54. [6, 6, 6, 6]])
  55. """
  56. # 对比上面例子,假设center_h=tensor([0.5,1.5...511.5])(实际上是0-1的值,这里为了简单理解写成这样)
  57. # 则shift_y=tensor([0.5,0.5..],[1.5,1.5,...],...[511.5,511.5...])
  58. shift_y, shift_x = torch.meshgrid(center_h, center_w, indexing='ij')
  59. # 将shift展平成一维序列,用上述的例子则shift_y为tensor([0.5,0.5...511.5,511.5])
  60. shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)
  61. # 宽=h*s*sqrt(r)
  62. # 由于锚框只考虑s1和r1的组合,r1组合就是size_tensor * torch.sqrt(ratio_tensor[0]),s1组合就是sizes[0] * torch.sqrt(ratio_tensor[1:])
  63. # 此处要乘上in_height / in_width是因为,假设此时ratios宽高比为1,那么默认w=h,但是实际上ratios代表与原图宽高比一致,举个例子
  64. # 假设原图1000*10,那么当ratios为1时,此时w=h,而我们需要的是w/h = 1000/10,所以需要乘上in_height / in_width来与原尺寸保持一致
  65. w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
  66. sizes[0] * torch.sqrt(ratio_tensor[1:])))\
  67. * in_height / in_width # 处理矩形输入
  68. h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
  69. sizes[0] / torch.sqrt(ratio_tensor[1:])))
  70. # 除以2来获得半高和半宽
  71. # 每一行(-w, -h, w, h)对应一个锚框一个锚框的左上角偏差和右下角偏差
  72. anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(
  73. in_height * in_width, 1) / 2
  74. # 每个中心点都将有boxes_per_pixel=(n+m-1)个锚框,
  75. # 形状:(w*h*(n+m-1), 4)
  76. out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y],
  77. dim=1).repeat_interleave(boxes_per_pixel, dim=0)
  78. output = out_grid + anchor_manipulations
  79. # 添加一个维度
  80. return output.unsqueeze(0)
  81. img = d2l.plt.imread('../data/img/catdog.jpg')
  82. h, w = img.shape[:2] # (1080, 1920)
  83. X = torch.rand(size=(1, 3, h, w))
  84. Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
  85. print(Y.shape)
  1. # 即将Y变成(高,宽,以同一像素点为中心的锚框数,4)
  2. # 每个锚框有四个元素(锚框的左上角x,y坐标和锚框右下角的x,y坐标)
  3. # n+m-1=3+3-1=5
  4. boxes = Y.reshape(h, w, 5, 4)
  5. # 访问以(250,250)为中心的第一个锚框
  6. boxes[250, 250, 0, :]
  1. # 显示以某个像素点为中心的所有锚框
  2. """
  3. params:
  4. axes:图像坐标
  5. bboxes:某个像素点中心坐标
  6. labels:显示文本,例如s=0.2,r=1
  7. colors:锚框的颜色
  8. """
  9. def show_bboxes(axes, bboxes, labels=None, colors=None):
  10. """显示所有边界框"""
  11. def _make_list(obj, default_values=None):
  12. if obj is None:
  13. obj = default_values
  14. elif not isinstance(obj, (list, tuple)):
  15. obj = [obj]
  16. return obj
  17. labels = _make_list(labels)
  18. colors = _make_list(colors, ['b', 'g', 'r', 'm', 'c'])
  19. for i, bbox in enumerate(bboxes):
  20. color = colors[i % len(colors)]
  21. # bbox_to_rect将边界框(左上x,左上y,右下x,右下y)格式转换成matplotlib格式:
  22. # ((左上x,左上y),宽,高)
  23. rect = d2l.bbox_to_rect(bbox.detach().numpy(), color)
  24. axes.add_patch(rect)
  25. if labels and len(labels) > i:
  26. text_color = 'k' if color == 'w' else 'w'
  27. axes.text(rect.xy[0], rect.xy[1], labels[i],
  28. va='center', ha='center', fontsize=9, color=text_color,
  29. bbox=dict(facecolor=color, lw=0))
  30. d2l.set_figsize()
  31. bbox_scale = torch.tensor((w, h, w, h))
  32. fig = d2l.plt.imshow(img)
  33. show_bboxes(fig.axes, boxes[750, 750, :, :] * bbox_scale,
  34. ['s=0.75, r=1', 's=0.5, r=1', 's=0.25, r=1', 's=0.75, r=2',
  35. 's=0.75, r=0.5'])

13.4.2 交并比

  1. # 衡量锚框与真实框之间或者锚框与锚框之间的相似度,即A∩B/A∪B
  2. def box_iou(boxes1, boxes2):
  3. """计算两个锚框或边界框列表中成对的交并比"""
  4. box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *
  5. (boxes[:, 3] - boxes[:, 1]))
  6. # boxes1,boxes2,areas1,areas2的形状:
  7. # boxes1:(boxes1的数量,4),
  8. # boxes2:(boxes2的数量,4),
  9. # areas1:(boxes1的数量,),
  10. # areas2:(boxes2的数量,)
  11. areas1 = box_area(boxes1)
  12. areas2 = box_area(boxes2)
  13. # inter_upperlefts,inter_lowerrights,inters的形状:
  14. # (boxes1的数量,boxes2的数量,2)
  15. inter_upperlefts = torch.max(boxes1[:, None, :2], boxes2[:, :2])
  16. inter_lowerrights = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])
  17. inters = (inter_lowerrights - inter_upperlefts).clamp(min=0)
  18. # inter_areasandunion_areas的形状:(boxes1的数量,boxes2的数量)
  19. inter_areas = inters[:, :, 0] * inters[:, :, 1]
  20. union_areas = areas1[:, None] + areas2 - inter_areas
  21. return inter_areas / union_areas

13.4.3 在训练数据中标注锚框

  1. %matplotlib inline
  2. import torch
  3. from d2l import torch as d2l
  4. torch.set_printoptions(2) # 精简输出精度,显示小数点后2位
  5. """
  6. 形成多个锚框
  7. params:
  8. data:图像(批量大小,通道数,高,宽)
  9. sizes:缩放比尺寸集合
  10. ratios:宽高比集合
  11. """
  12. def multibox_prior(data, sizes, ratios):
  13. # 获取data后两位的值,也就是图像的高和宽
  14. in_height, in_width = data.shape[-2:]
  15. """
  16. params:
  17. device:cpu或者gpu
  18. num_sizes:尺寸的个数n
  19. num_ratios:宽高比个数m
  20. """
  21. device, num_sizes, num_ratios = data.device, len(sizes), len(ratios)
  22. # 以同一像素为中心的锚框数量n+m-1
  23. boxes_per_pixel = (num_sizes + num_ratios - 1)
  24. size_tensor = torch.tensor(sizes, device=device)
  25. ratio_tensor = torch.tensor(ratios, device=device)
  26. # offset:为了将锚点移动到像素的中心,需要设置偏移量。
  27. # steps:归一化,将宽高规化到0-1之间,因为一个像素的高为1且宽为1,我们选择偏移我们的中心0.5
  28. offset_h, offset_w = 0.5, 0.5
  29. steps_h = 1.0 / in_height # 在y轴上缩放步长
  30. steps_w = 1.0 / in_width # 在x轴上缩放步长
  31. # 假设宽高512*216 那么torch.arange(in_height, device=device)=【0,1,2...511】,移动到中心就是[0.5,1.5...511.5]
  32. # 第一步:torch.arange(in_height, device=device) + offset_h代表移动到每个像素的中心,因为每个像素1*1大小.
  33. # 第二步:宽高进行归一化
  34. center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
  35. center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w
  36. """
  37. a = torch.tensor([1, 2, 3, 4])
  38. b = torch.tensor([4, 5, 6])
  39. x, y = torch.meshgrid(a, b,indexing='ij')
  40. print:tensor([[1, 1, 1],
  41. [2, 2, 2],
  42. [3, 3, 3],
  43. [4, 4, 4]])
  44. tensor([[4, 5, 6],
  45. [4, 5, 6],
  46. [4, 5, 6],
  47. [4, 5, 6]])
  48. x, y = torch.meshgrid(a, b,indexing='xy')
  49. print:tensor([[1, 2, 3, 4],
  50. [1, 2, 3, 4],
  51. [1, 2, 3, 4]])
  52. tensor([[4, 4, 4, 4],
  53. [5, 5, 5, 5],
  54. [6, 6, 6, 6]])
  55. """
  56. # 对比上面例子,假设center_h=tensor([0.5,1.5...511.5])(实际上是0-1的值,这里为了简单理解写成这样)
  57. # 则shift_y=tensor([0.5,0.5..],[1.5,1.5,...],...[511.5,511.5...])
  58. shift_y, shift_x = torch.meshgrid(center_h, center_w, indexing='ij')
  59. # 将shift展平成一维序列,用上述的例子则shift_y为tensor([0.5,0.5...511.5,511.5])
  60. shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)
  61. # 宽=h*s*sqrt(r)
  62. # 由于锚框只考虑s1和r1的组合,r1组合就是size_tensor * torch.sqrt(ratio_tensor[0]),s1组合就是sizes[0] * torch.sqrt(ratio_tensor[1:])
  63. # 此处要乘上in_height / in_width是因为,假设此时ratios宽高比为1,那么默认w=h,但是实际上ratios代表与原图宽高比一致,举个例子
  64. # 假设原图1000*10,那么当ratios为1时,此时w=h,而我们需要的是w/h = 1000/10,所以需要乘上in_height / in_width来与原尺寸保持一致
  65. w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
  66. sizes[0] * torch.sqrt(ratio_tensor[1:])))\
  67. * in_height / in_width # 处理矩形输入
  68. h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
  69. sizes[0] / torch.sqrt(ratio_tensor[1:])))
  70. # 除以2来获得半高和半宽
  71. # 每一行(-w, -h, w, h)对应一个锚框一个锚框的左上角偏差和右下角偏差
  72. anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(
  73. in_height * in_width, 1) / 2
  74. # 每个中心点都将有boxes_per_pixel=(n+m-1)个锚框,
  75. # 形状:(w*h*(n+m-1), 4)
  76. out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y],
  77. dim=1).repeat_interleave(boxes_per_pixel, dim=0)
  78. output = out_grid + anchor_manipulations
  79. # 添加一个维度
  80. return output.unsqueeze(0)
  81. img = d2l.plt.imread('../data/img/catdog.jpg')
  82. h, w = img.shape[:2] # (1080, 1920)
  83. X = torch.rand(size=(1, 3, h, w))
  84. Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
  85. print(Y.shape)
  1. # 即将Y变成(高,宽,以同一像素点为中心的锚框数,4)
  2. # 每个锚框有四个元素(锚框的左上角x,y坐标和锚框右下角的x,y坐标)
  3. # n+m-1=3+3-1=5
  4. boxes = Y.reshape(h, w, 5, 4)
  5. # 访问以(250,250)为中心的第一个锚框
  6. boxes[250, 250, 0, :]
  1. # 显示以某个像素点为中心的所有锚框
  2. """
  3. params:
  4. axes:图像坐标
  5. bboxes:某个像素点中心坐标
  6. labels:显示文本,例如s=0.2,r=1
  7. colors:锚框的颜色
  8. """
  9. def show_bboxes(axes, bboxes, labels=None, colors=None):
  10. """显示所有边界框"""
  11. def _make_list(obj, default_values=None):
  12. if obj is None:
  13. obj = default_values
  14. elif not isinstance(obj, (list, tuple)):
  15. obj = [obj]
  16. return obj
  17. labels = _make_list(labels)
  18. colors = _make_list(colors, ['b', 'g', 'r', 'm', 'c'])
  19. for i, bbox in enumerate(bboxes):
  20. color = colors[i % len(colors)]
  21. # bbox_to_rect将边界框(左上x,左上y,右下x,右下y)格式转换成matplotlib格式:
  22. # ((左上x,左上y),宽,高)
  23. rect = d2l.bbox_to_rect(bbox.detach().numpy(), color)
  24. axes.add_patch(rect)
  25. if labels and len(labels) > i:
  26. text_color = 'k' if color == 'w' else 'w'
  27. axes.text(rect.xy[0], rect.xy[1], labels[i],
  28. va='center', ha='center', fontsize=9, color=text_color,
  29. bbox=dict(facecolor=color, lw=0))
  30. d2l.set_figsize()
  31. bbox_scale = torch.tensor((w, h, w, h))
  32. fig = d2l.plt.imshow(img)
  33. show_bboxes(fig.axes, boxes[750, 750, :, :] * bbox_scale,
  34. ['s=0.75, r=1', 's=0.5, r=1', 's=0.25, r=1', 's=0.75, r=2',
  35. 's=0.75, r=0.5'])
  1. # 衡量锚框与真实框之间或者锚框与锚框之间的相似度,即A∩B/A∪B
  2. def box_iou(boxes1, boxes2):
  3. """计算两个锚框或边界框列表中成对的交并比"""
  4. box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *
  5. (boxes[:, 3] - boxes[:, 1]))
  6. # boxes1,boxes2,areas1,areas2的形状:
  7. # boxes1:(boxes1的数量,4),
  8. # boxes2:(boxes2的数量,4),
  9. # areas1:(boxes1的数量,),
  10. # areas2:(boxes2的数量,)
  11. areas1 = box_area(boxes1)
  12. areas2 = box_area(boxes2)
  13. # inter_upperlefts,inter_lowerrights,inters的形状:
  14. # (boxes1的数量,boxes2的数量,2)
  15. inter_upperlefts = torch.max(boxes1[:, None, :2], boxes2[:, :2])
  16. inter_lowerrights = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])
  17. inters = (inter_lowerrights - inter_upperlefts).clamp(min=0)
  18. # inter_areasandunion_areas的形状:(boxes1的数量,boxes2的数量)
  19. inter_areas = inters[:, :, 0] * inters[:, :, 1]
  20. union_areas = areas1[:, None] + areas2 - inter_areas
  21. return inter_areas / union_areas
  22. # 将最接近的真实边界框分配给锚框
  23. # iou_threshold:阈值
  24. def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):
  25. # num_anchors=na num_gt_boxes=nb
  26. num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]
  27. # 位于第i行和第j列的元素x_ij是锚框i和真实边界框j的IoU
  28. jaccard = box_iou(anchors, ground_truth)
  29. # 对于每个锚框,分配的真实边界框的张量,初始值为-1
  30. anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long,
  31. device=device)
  32. # 找到每一行中最大交并比的ground_truth和anchors索引号
  33. max_ious, indices = torch.max(jaccard, dim=1)
  34. # 找到剩余交并比大于阈值的索引号
  35. anc_i = torch.nonzero(max_ious >= iou_threshold).reshape(-1)
  36. box_j = indices[max_ious >= iou_threshold]
  37. anchors_bbox_map[anc_i] = box_j
  38. # 删去这些索引行和列
  39. col_discard = torch.full((num_anchors,), -1)
  40. row_discard = torch.full((num_gt_boxes,), -1)
  41. for _ in range(num_gt_boxes):
  42. max_idx = torch.argmax(jaccard)
  43. box_idx = (max_idx % num_gt_boxes).long()
  44. anc_idx = (max_idx / num_gt_boxes).long()
  45. anchors_bbox_map[anc_idx] = box_idx
  46. jaccard[:, box_idx] = col_discard
  47. jaccard[anc_idx, :] = row_discard
  48. return anchors_bbox_map
  49. #@save
  50. def offset_boxes(anchors, assigned_bb, eps=1e-6):
  51. """对锚框偏移量的转换"""
  52. c_anc = d2l.box_corner_to_center(anchors)
  53. c_assigned_bb = d2l.box_corner_to_center(assigned_bb)
  54. offset_xy = 10 * (c_assigned_bb[:, :2] - c_anc[:, :2]) / c_anc[:, 2:]
  55. offset_wh = 5 * torch.log(eps + c_assigned_bb[:, 2:] / c_anc[:, 2:])
  56. offset = torch.cat([offset_xy, offset_wh], axis=1)
  57. return offset
  58. #@save
  59. def multibox_target(anchors, labels):
  60. """使用真实边界框标记锚框"""
  61. batch_size, anchors = labels.shape[0], anchors.squeeze(0)
  62. batch_offset, batch_mask, batch_class_labels = [], [], []
  63. device, num_anchors = anchors.device, anchors.shape[0]
  64. for i in range(batch_size):
  65. label = labels[i, :, :]
  66. anchors_bbox_map = assign_anchor_to_bbox(
  67. label[:, 1:], anchors, device)
  68. bbox_mask = ((anchors_bbox_map >= 0).float().unsqueeze(-1)).repeat(
  69. 1, 4)
  70. # 将类标签和分配的边界框坐标初始化为零
  71. class_labels = torch.zeros(num_anchors, dtype=torch.long,
  72. device=device)
  73. assigned_bb = torch.zeros((num_anchors, 4), dtype=torch.float32,
  74. device=device)
  75. # 使用真实边界框来标记锚框的类别。
  76. # 如果一个锚框没有被分配,标记其为背景(值为零)
  77. indices_true = torch.nonzero(anchors_bbox_map >= 0)
  78. bb_idx = anchors_bbox_map[indices_true]
  79. class_labels[indices_true] = label[bb_idx, 0].long() + 1
  80. assigned_bb[indices_true] = label[bb_idx, 1:]
  81. # 偏移量转换
  82. offset = offset_boxes(anchors, assigned_bb) * bbox_mask
  83. batch_offset.append(offset.reshape(-1))
  84. batch_mask.append(bbox_mask.reshape(-1))
  85. batch_class_labels.append(class_labels)
  86. bbox_offset = torch.stack(batch_offset)
  87. bbox_mask = torch.stack(batch_mask)
  88. class_labels = torch.stack(batch_class_labels)
  89. return (bbox_offset, bbox_mask, class_labels)
  90. ground_truth = torch.tensor([[0, 0.1, 0.08, 0.52, 0.92],
  91. [1, 0.55, 0.2, 0.9, 0.88]])
  92. anchors = torch.tensor([[0, 0.1, 0.2, 0.3], [0.15, 0.2, 0.4, 0.4],
  93. [0.63, 0.05, 0.88, 0.98], [0.66, 0.45, 0.8, 0.8],
  94. [0.57, 0.3, 0.92, 0.9]])

13.5 多尺度目标检测

首先锚框是在图像的每个像素点设立n+m-1个锚框,如果图像尺寸很大的话,会造成数据爆炸。这个小节介绍了在输入图像中均匀采样一小部分像素点。

用卷积层的输出即特征图来设立锚框,设立特征图的每个像素点为锚框中心,对任意图像的特征图(w,h)中的像素进行采样,以这些均匀采样的像素为中心。

  1. def display_anchors(fmap_w, fmap_h, s):
  2. d2l.set_figsize()
  3. # 前两个维度上的值不影响输出
  4. fmap = torch.zeros((10, 100, fmap_h, fmap_w))
  5. anchors = d2l.multibox_prior(fmap, sizes=s, ratios=[1, 2, 0.5])
  6. bbox_scale = torch.tensor((w, h, w, h))
  7. d2l.show_bboxes(d2l.plt.imshow(img).axes,
  8. anchors[0] * bbox_scale)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/648976
推荐阅读
相关标签
  

闽ICP备14008679号