活动

天翼云最新优惠活动,涵盖免费试用,产品折扣等,助您降本增效!
热门活动
  • 618智算钜惠季 爆款云主机2核4G限时秒杀,88元/年起!
  • 免费体验DeepSeek,上天翼云息壤 NEW 新老用户均可免费体验2500万Tokens,限时两周
  • 云上钜惠 HOT 爆款云主机全场特惠,更有万元锦鲤券等你来领!
  • 算力套餐 HOT 让算力触手可及
  • 天翼云脑AOne NEW 连接、保护、办公,All-in-One!
  • 中小企业应用上云专场 产品组合下单即享折上9折起,助力企业快速上云
  • 息壤高校钜惠活动 NEW 天翼云息壤杯高校AI大赛,数款产品享受线上订购超值特惠
  • 天翼云电脑专场 HOT 移动办公新选择,爆款4核8G畅享1年3.5折起,快来抢购!
  • 天翼云奖励推广计划 加入成为云推官,推荐新用户注册下单得现金奖励
免费活动
  • 免费试用中心 HOT 多款云产品免费试用,快来开启云上之旅
  • 天翼云用户体验官 NEW 您的洞察,重塑科技边界

智算服务

打造统一的产品能力,实现算网调度、训练推理、技术架构、资源管理一体化智算服务
智算云(DeepSeek专区)
科研助手
  • 算力商城
  • 应用商城
  • 开发机
  • 并行计算
算力互联调度平台
  • 应用市场
  • 算力市场
  • 算力调度推荐
一站式智算服务平台
  • 模型广场
  • 体验中心
  • 服务接入
智算一体机
  • 智算一体机
大模型
  • DeepSeek-R1-昇腾版(671B)
  • DeepSeek-R1-英伟达版(671B)
  • DeepSeek-V3-昇腾版(671B)
  • DeepSeek-R1-Distill-Llama-70B
  • DeepSeek-R1-Distill-Qwen-32B
  • Qwen2-72B-Instruct
  • StableDiffusion-V2.1
  • TeleChat-12B

应用商城

天翼云精选行业优秀合作伙伴及千余款商品,提供一站式云上应用服务
进入甄选商城进入云市场创新解决方案
办公协同
  • WPS云文档
  • 安全邮箱
  • EMM手机管家
  • 智能商业平台
财务管理
  • 工资条
  • 税务风控云
企业应用
  • 翼信息化运维服务
  • 翼视频云归档解决方案
工业能源
  • 智慧工厂_生产流程管理解决方案
  • 智慧工地
建站工具
  • SSL证书
  • 新域名服务
网络工具
  • 翼云加速
灾备迁移
  • 云管家2.0
  • 翼备份
资源管理
  • 全栈混合云敏捷版(软件)
  • 全栈混合云敏捷版(一体机)
行业应用
  • 翼电子教室
  • 翼智慧显示一体化解决方案

合作伙伴

天翼云携手合作伙伴,共创云上生态,合作共赢
天翼云生态合作中心
  • 天翼云生态合作中心
天翼云渠道合作伙伴
  • 天翼云代理渠道合作伙伴
天翼云服务合作伙伴
  • 天翼云集成商交付能力认证
天翼云应用合作伙伴
  • 天翼云云市场合作伙伴
  • 天翼云甄选商城合作伙伴
天翼云技术合作伙伴
  • 天翼云OpenAPI中心
  • 天翼云EasyCoding平台
天翼云培训认证
  • 天翼云学堂
  • 天翼云市场商学院
天翼云合作计划
  • 云汇计划
天翼云东升计划
  • 适配中心
  • 东升计划
  • 适配互认证

开发者

开发者相关功能入口汇聚
技术社区
  • 专栏文章
  • 互动问答
  • 技术视频
资源与工具
  • OpenAPI中心
开放能力
  • EasyCoding敏捷开发平台
培训与认证
  • 天翼云学堂
  • 天翼云认证
魔乐社区
  • 魔乐社区

支持与服务

为您提供全方位支持与服务,全流程技术保障,助您轻松上云,安全无忧
文档与工具
  • 文档中心
  • 新手上云
  • 自助服务
  • OpenAPI中心
定价
  • 价格计算器
  • 定价策略
基础服务
  • 售前咨询
  • 在线支持
  • 在线支持
  • 工单服务
  • 建议与反馈
  • 用户体验官
  • 服务保障
  • 客户公告
  • 会员中心
增值服务
  • 红心服务
  • 首保服务
  • 客户支持计划
  • 专家技术服务
  • 备案管家

了解天翼云

天翼云秉承央企使命,致力于成为数字经济主力军,投身科技强国伟大事业,为用户提供安全、普惠云服务
品牌介绍
  • 关于天翼云
  • 智算云
  • 天翼云4.0
  • 新闻资讯
  • 天翼云APP
基础设施
  • 全球基础设施
  • 信任中心
最佳实践
  • 精选案例
  • 超级探访
  • 云杂志
  • 分析师和白皮书
  • 天翼云·创新直播间
市场活动
  • 2025智能云生态大会
  • 2024智算云生态大会
  • 2023云生态大会
  • 2022云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心
      文档中心

      天翼云息壤一体化智算服务平台

      天翼云息壤一体化智算服务平台

        • 产品介绍
        • 产品定义
        • 产品优势
        • 功能特性
        • 应用场景
        • 使用限制
        • 计费说明
        • 计费说明
        • 快速入门
        • 算力互联调度平台入门指引
        • 一站式智算服务平台入门指引
        • 一体化计算加速平台入门指引
        • 智算容器
        • 异构计算
        • 算力互联调度平台用户指南
        • 智能计算
        • 通用计算
        • 超级计算
        • 一站式智算服务平台用户指南
        • 模型介绍
        • 操作说明
        • API参考
        • 一体化计算加速平台用户指南
        • 智算容器
        • 异构计算
        • 常见问题
        • 算力互联调度平台常见问题
        • 一站式智算服务平台常见问题
        • 一体化计算加速平台常见问题
        • 智算容器
        • 异构计算
        • 最佳实践
        • 算力互联调度平台最佳实践
        • 使用 Notebook 完成钢材图像识别
        • 一站式智算服务平台最佳实践
        • 模型训练微调及调用
        • 一体化计算加速平台最佳实践
        • 智算容器
        • 异构计算
        • 相关协议
        • 算力互联调度平台协议
        • 一站式智算服务平台协议
        • 一体化计算加速平台协议
          无相关产品

          本页目录

          帮助中心天翼云息壤一体化智算服务平台最佳实践算力互联调度平台最佳实践使用 Notebook 完成钢材图像识别
          使用 Notebook 完成钢材图像识别
          更新时间 2025-02-06 21:42:00
          • 新浪微博
          • 微信
            扫码分享
          • 复制链接
          最近更新时间: 2025-02-06 21:42:00
          分享文章
          • 新浪微博
          • 微信
            扫码分享
          • 复制链接
          本节介绍使用算力互联调度平台使用Notebook 完成钢材图像识别实践。

          操作步骤

          步骤1:准备工作

          步骤2:基础配置

          步骤3:确认订单

          步骤4:模型开发

          步骤1:准备工作

          进入算力导购页面

          1. 注册天翼云账号,完成实名认证并确保余额充足。
          2. 登录算力互联调度平台的控制台。
          3. 进入算力任务页面,选择智能计算,点击【购买算力】按钮。

          步骤2:基础配置

          需求输入

          1. 任务名称:配置notebook-test。
          2. 业务场景:选择【模型开发】。
          3. 付费类型:选择【包年包月】。
          4. 时长:根据需求选择时长。
          5. 算力需求:GPU选择NVIDIA-A10。
          6. 点击按钮【下一步:算网评估】。

          image.png

           算网评估

          1. 编排调度策略选择:【成本最优】。
          2. 点击按钮【下一步:部署配置】。

          image.png

          部署配置

          1. 配置实例名称。
          2. 镜像选择:pytorch-jupyter:cuda11.1-torch1.9.0-cudnn8。
          3. 点击【下一步:确认订单】。
          image.png

          步骤3:确认订单

          1. 核对订单信息,提交信息。

          image.png
          2. 核对订单金额,然后点击【支付订单】。

          步骤4:模型开发

          算网任务创建完成后,进入【智能计算控制台】-【开发机】,可在列表中查看已创建的模型开发实例,点击【打开】按钮,进入创建好的开发环境。

          打开实例

          新建开发脚本

          点击左上角【+】按钮,选择Notebook-Python3 。

          image.png

          提交代码

          1.数钢筋案例开始 - 下载代码和数据集

          import os
          if not os.path.exists('./rebar_count'):
             print('Downloading code and datasets...')
             os.system("wget -N -nv  https://modelarts-labs-bj4-v2.obs.cn-north-4.myhuaweicloud.com/notebook/DL_rebar_count/rebar_count_code.zip")
             os.system("wget -N -nv https://cnnorth4-modelhub-datasets-obsfs-sfnua.obs.cn-north-4.myhuaweicloud.com/content/c2c1853f-d6a6-4c9d-ac0e-203d4c304c88/NkxX5K/dataset/rebar_count_datasets.zip")
             os.system("unzip rebar_count_code.zip; rm rebar_count_code.zip")
             os.system("unzip -q rebar_count_datasets.zip; rm rebar_count_datasets.zip")
             os.system("mv rebar_count_code rebar_count; mv rebar_count_datasets rebar_count/datasets")
             if os.path.exists('./rebar_count'):
                 print('Download code and datasets success')
             else:
                 print('Download code and datasets failed, please check the download url is valid or not.')
          else:
             print('./rebar_count 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, '/app/rebar_count/src')
          from rebar_count.src.data import VOCroot, VOC_Config, AnnotationTransform, VOCDetection, detection_collate, BaseTransform, preproc
          from models.RFB_Net_vgg import build_net
          from layers.modules import MultiBoxLoss
          from layers.functions import Detect, PriorBox
          from utils.visualize import *
          from utils.nms_wrapper import nms
          from utils.timer import Timer
          import matplotlib.pyplot as plt
          %matplotlib inline
          ROOT_DIR = os.getcwd()
          
          seed = 0
          cudnn.benchmark = False
          cudnn.deterministic = True
          torch.manual_seed(seed)            # 为CPU设置随机种子
          torch.cuda.manual_seed_all(seed)   # 为所有GPU设置随机种子
          random.seed(seed)
          np.random.seed(seed)

           3.查看训练数据样例

          def read_xml(xml_path):
             '''读取xml标签'''
             tree = ET.parse(xml_path)
             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, dtype=np.float64), labels

           4.显示原图和标注框

          train_img_dir = './rebar_count/datasets/VOC2007/JPEGImages'
          train_xml_dir = './rebar_count/datasets/VOC2007/Annotations'
          files = os.listdir(train_img_dir)
          files.sort()
          for index, file_name in enumerate(files[:2]):
             img_path = os.path.join(train_img_dir, file_name)
             xml_path = os.path.join(train_xml_dir, file_name.split('.jpg')[0] + '.xml')
             boxes, labels = read_xml(xml_path)
             img = Image.open(img_path)
           
             resize_scale = 2048.0 / max(img.size)
             img = img.resize((int(img.size[0] * resize_scale), int(img.size[1] * resize_scale)))
             boxes *= resize_scale
           
             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(np.int)
                 cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 255, 0), thickness=3)
           
             plt.subplot(2,1,2)
             plt.imshow(img)
          plt.show()

           5.定义训练超参,模型、日志保存路径

          # 定义训练超参
          num_classes = 2  # 数据集中只有 steel 一个标签,加上背景,所以总共有2个类
          max_epoch = 25  # 默认值为1,调整为大于20的值,训练效果更佳
          batch_size = 4
          ngpu = 1
          initial_lr = 0.01
          img_dim = 416  # 模型输入图片大小
          train_sets = [('2007', 'trainval')]  # 指定训练集
          cfg = VOC_Config
          rgb_means = (104, 117, 123)  # ImageNet数据集的RGB均值
          
          save_folder = './rebar_count/model_snapshots'  # 指定训练模型保存路径
          if not os.path.exists(save_folder):
             os.mkdir(save_folder)
           
          log_path = os.path.join('./rebar_count/logs', datetime.now().isoformat())  # 指定日志保存路径
          if not os.path.exists(log_path):
             os.makedirs(log_path)
          

           6.构建模型,定义优化器及损失函数

          net = build_net('train', img_dim, num_classes=num_classes)
          
          if ngpu > 1:
             net = torch.nn.DataParallel(net)
          
          net.cuda()  # 本案例代码只能在GPU上训练
          cudnn.benchmark = True
          
          optimizer = optim.SGD(net.parameters(), lr=initial_lr,
                               momentum=0.9, weight_decay=0)  # 定义优化器
          
          criterion = MultiBoxLoss(num_classes,
                                  overlap_thresh=0.4,
                                  prior_for_matching=True,
                                  bkg_label=0,
                                  neg_mining=True,
                                  neg_pos=3,
                                  neg_overlap=0.3,
                                  encode_target=False)  # 定义损失函数
          
          priorbox = PriorBox(cfg)
          with torch.no_grad():
             priors = priorbox.forward()
             priors = priors.cuda()

          7.定义自适应学习率函数

          def adjust_learning_rate(optimizer, gamma, epoch, step_index, iteration, epoch_size):
             """
             自适应学习率
             """
             if epoch < 11:
                 lr = 1e-8 + (initial_lr-1e-8) * iteration / (epoch_size * 10)
             else:
                 lr = initial_lr * (gamma ** (step_index))
             for param_group in optimizer.param_groups:
                 param_group['lr'] = lr
             return lr

           8.定义训练函数

          def train():
             """
             模型训练函数,每10次迭代打印一次日志,20个epoch之后,每个epoch保存一次模型
             """
             net.train()
          
             loc_loss = 0
             conf_loss = 0
             epoch = 0
             print('Loading dataset...')
          
             dataset = VOCDetection(VOCroot, train_sets, preproc(img_dim, rgb_means, p=0.0), AnnotationTransform())
          
             epoch_size = len(dataset) // batch_size
             max_iter = max_epoch * epoch_size
          
             stepvalues = (25 * epoch_size, 35 * epoch_size)
             step_index = 0
             start_iter = 0
          
             lr = initial_lr
             for iteration in range(start_iter, max_iter):
                 if iteration % epoch_size == 0:
                     if epoch > 20:
                         torch.save(net.state_dict(), os.path.join(save_folder, 'epoch_' +
                                    repr(epoch).zfill(3) + '_loss_'+ '%.4f' % loss.item() + '.pth'))
          
                     batch_iterator = iter(data.DataLoader(dataset, batch_size,
                                                           shuffle=True, num_workers=1, collate_fn=detection_collate))
                     loc_loss = 0
                     conf_loss = 0
                     epoch += 1
          
                 load_t0 = time.time()
                 if iteration in stepvalues:
                     step_index += 1
                 lr = adjust_learning_rate(optimizer, 0.2, epoch, step_index, iteration, epoch_size)
          
          
                 images, targets = next(batch_iterator)
          
                 images = Variable(images.cuda())
                 targets = [Variable(anno.cuda()) for anno in targets]
          
                 # forward
                 t0 = time.time()
                 out = net(images)
                 # backprop
                 optimizer.zero_grad()
                 loss_l, loss_c = criterion(out, priors, targets)
                 loss = loss_l + loss_c
                 loss.backward()
                 optimizer.step()
                 t1 = time.time()
                 loc_loss += loss_l.item()
                 conf_loss += loss_c.item()
                 load_t1 = time.time()
          
                 if iteration % 10 == 0:
                     print('Epoch:' + repr(epoch) + ' || epochiter: ' + repr(iteration % epoch_size) + '/' + repr(epoch_size)
                           + '|| Totel iter ' +
                           repr(iteration) + ' || L: %.4f C: %.4f||' % (
                         loss_l.item(),loss_c.item()) +
                         'Batch time: %.4f sec. ||' % (load_t1 - load_t0) + 'LR: %.8f' % (lr))
          
             torch.save(net.state_dict(), os.path.join(save_folder, 'epoch_' +
                        repr(epoch).zfill(3) + '_loss_'+ '%.4f' % loss.item() + '.pth'))

           9.开始训练,每个epoch训练耗时约60秒

          t1 = time.time()
          print('开始训练,本次训练总共需%d个epoch,每个epoch训练耗时约60秒' % max_epoch)
          train()
          print('training cost %.2f s' % (time.time() - t1))
          10.已完成训练,下面开始测试模型,首先需定义目标检测类 
          class ObjectDetector:
              """
              定义目标检测类
              """
              def __init__(self, net, detection, transform, num_classes=num_classes, thresh=0.01, cuda=True):
                  self.net = net
                  self.detection = detection
                  self.transform = transform
                  self.num_classes = num_classes
                  self.thresh = thresh
                  self.cuda = torch.cuda.is_available()
          
              def predict(self, img):
                  _t = {'im_detect': Timer(), 'misc': Timer()}
                  scale = torch.Tensor([img.shape[1], img.shape[0],
                                        img.shape[1], img.shape[0]])
          
                  with torch.no_grad():
                      x = self.transform(img).unsqueeze(0)
                      if self.cuda:
                          x = x.cuda()
                          scale = scale.cuda()
          
                  _t['im_detect'].tic()
                  out = net(x)  # forward pass
                  boxes, scores = self.detection.forward(out, priors)
                  detect_time = _t['im_detect'].toc()
                  boxes = boxes[0]
                  scores = scores[0]
          
                  # scale each detection back up to the image
                  boxes *= scale
                  boxes = boxes.cpu().numpy()
                  scores = scores.cpu().numpy()
                  _t['misc'].tic()
                  all_boxes = [[] for _ in range(num_classes)]
          
                  for j in range(1, num_classes):
                      inds = np.where(scores[:, j] > self.thresh)[0]
                      if len(inds) == 0:
                          all_boxes[j] = np.zeros([0, 5], dtype=np.float32)
                          continue
                      c_bboxes = boxes[inds]
                      c_scores = scores[inds, j]
                      c_dets = np.hstack((c_bboxes, c_scores[:, np.newaxis])).astype(
                          np.float32, copy=False)
          
                      keep = nms(c_dets, 0.2, force_cpu=False)
                      c_dets = c_dets[keep, :]
                      all_boxes[j] = c_dets
          
                  nms_time = _t['misc'].toc()
                  total_time = detect_time + nms_time
          
                  return all_boxes, total_time

          11.定义推理网络,并加载前面训练的loss最低的模型

          trained_models = os.listdir(os.path.join(ROOT_DIR, './rebar_count/model_snapshots'))  # 模型文件所在目录
          lowest_loss = 9999
          best_model_name = ''
          for model_name in trained_models:
             if not model_name.endswith('pth'):
                 continue
             loss = float(model_name.split('_loss_')[1].split('.pth')[0])
             if loss < lowest_loss:
                 lowest_loss = loss
                 best_model_name = model_name
          best_model_path = os.path.join(ROOT_DIR, './rebar_count/model_snapshots', best_model_name)
          
          print('loading model from', best_model_path)
          net = build_net('test', img_dim, num_classes)  # 加载模型
          state_dict = torch.load(best_model_path)
          new_state_dict = OrderedDict()
          for k, v in state_dict.items():
             head = k[:7]
             if head == 'module.':
                 name = k[7:]
             else:
                 name = k
             new_state_dict[name] = v
          net.load_state_dict(new_state_dict)
          net.eval()
          print('Finish load model!')
          
          if torch.cuda.is_available():
             net = net.cuda()
             cudnn.benchmark = True
          else:
             net = net.cpu()
          
          detector = Detect(num_classes, 0, cfg)
          transform = BaseTransform(img_dim, rgb_means, (2, 0, 1))
          object_detector = ObjectDetector(net, detector, transform)

           12.测试图片,输出每条钢筋的位置和图片中钢筋总条数

          test_img_dir = r'./rebar_count/datasets/test_dataset'  # 待预测的图片目录
          files = os.listdir(test_img_dir)
          files.sort()
          for i, file_name in enumerate(files[:2]):
             image_src = cv2.imread(os.path.join(test_img_dir, file_name))
             detect_bboxes, tim = object_detector.predict(image_src)
             image_draw = image_src.copy()
             rebar_count = 0
             for class_id, class_collection in enumerate(detect_bboxes):
                 if len(class_collection) > 0:
                     for i in range(class_collection.shape[0]):
                         if class_collection[i, -1] > 0.6:
                             pt = class_collection[i]
                             cv2.circle(image_draw, (int((pt[0] + pt[2]) * 0.5), int((pt[1] + pt[3]) * 0.5)), int((pt[2] - pt[0]) * 0.5 * 0.6), (255, 0, 0), -1)
                             rebar_count += 1
             cv2.putText(image_draw, 'rebar_count: %d' % rebar_count, (25, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 3)
             plt.figure(i, figsize=(30, 20))
             plt.imshow(image_draw)
             plt.show()

          分段执行,可以呈现钢材位置并标记钢材的数量信息。

          image.png
          文档反馈

          建议您登录后反馈,可在建议与反馈里查看问题处理进度

          鼠标选中文档,精准反馈问题

          选中存在疑惑的内容,即可快速反馈问题,我们会跟进处理

          知道了

          上一篇 :  算力互联调度平台最佳实践
          下一篇 :  一站式智算服务平台最佳实践
          搜索 关闭
          ©2025 天翼云科技有限公司版权所有 增值电信业务经营许可证A2.B1.B2-20090001
          公司地址:北京市东城区青龙胡同甲1号、3号2幢2层205-32室
          备案 京公网安备11010802043424号 京ICP备 2021034386号
          ©2025天翼云科技有限公司版权所有
          京ICP备 2021034386号
          备案 京公网安备11010802043424号
          增值电信业务经营许可证A2.B1.B2-20090001
          用户协议 隐私政策 法律声明