钢筋计数模型训练教学与实践 以下是对教学内容的任务解析: 任务一:环境与数据准备 1、将本实践中所需要的钢筋数据集下载 输入: import os if not os.path.exists('./rebarcount'): print('Downloading code and datasets...') os.system("wget N nv os.system("unzip rebarcount.zip;") if os.path.exists('./rebarcount'): print('Download code and datasets success') else: print('Download code and datasets failed, please check the download url is valid or not.') else: print('./rebarcount already exists') 2、加载需要的python模块 输入: import os import sys import cv2 import time import random import torch import numpy as np from PIL import Image, ImageDraw import xml.etree.ElementTree as ET from datetime import datetime from collections import OrderedDict import torch.optim as optim import torch.utils.data as data import torch.backends.cudnn as cudnn sys.path.insert(0, './rebarcount/src') from rebarcount.src.data import VOCroot, VOCConfig, AnnotationTransform, VOCDetection, detectioncollate, BaseTransform, preproc from models.RFBNetvgg import buildnet from layers.modules import MultiBoxLoss from layers.functions import Detect, PriorBox from utils.visualize import from utils.nmswrapper import nms from utils.timer import Timer import matplotlib.pyplot as plt %matplotlib inline ROOTDIR os.getcwd() seed 0 cudnn.benchmark False cudnn.deterministic True torch.manualseed(seed) 为CPU设置随机种子 torch.cuda.manualseedall(seed) 为所有GPU设置随机种子 random.seed(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] str(seed) 设置hash随机种子 任务二:查看训练数据样例 1.查看训练数据样例 输入: def readxml(xmlpath): '''读取xml标签''' tree ET.parse(xmlpath) root tree.getroot() boxes [] labels [] for element in root.findall('object'): label element.find('name').text if label 'steel': bndbox element.find('bndbox') xmin bndbox.find('xmin').text ymin bndbox.find('ymin').text xmax bndbox.find('xmax').text ymax bndbox.find('ymax').text boxes.append([xmin, ymin, xmax, ymax]) labels.append(label) return np.array(boxes, dtypenp.float64), labels 2.显示原图和标注框 输入: trainimgdir './rebarcount/datasets/VOC2007/JPEGImages' trainxmldir './rebarcount/datasets/VOC2007/Annotations' files os.listdir(trainimgdir) files.sort() for index, filename in enumerate(files[:2]): imgpath os.path.join(trainimgdir, filename) xmlpath os.path.join(trainxmldir, filename.split('.jpg')[0] + '.xml') boxes, labels readxml(xmlpath) img Image.open(imgpath) resizescale 2048.0 / max(img.size) img img.resize((int(img.size[0] resizescale), int(img.size[1] resizescale))) boxes resizescale plt.figure(figsize(img.size[0]/100.0, img.size[1]/100.0)) plt.subplot(2,1,1) plt.imshow(img) img img.convert('RGB') img np.array(img) img img.copy() for box in boxes: xmin, ymin, xmax, ymax box.astype(int) cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 255, 0), thickness3) plt.subplot(2,1,2) plt.imshow(img) plt.show() 输出: