实训报告–具身智能工业视觉分析与物联监护应用演练

摘要:本实训基于昇腾 Atlas 200I DK A2 与 Windows 环境,围绕具身智能与工业视觉展开应用演练。通过 Python 虚拟环境实现 OCR 文字识别、人脸及人体检测,并借助华为云 IoTDA 构建温湿度计与吸顶灯的物联监护场景,最后使用 CodeArts 完成智慧路灯应用的快速构建与部署,形成从视觉感知到云端联动的完整闭环。

本报告完整呈现了从环境搭建、编码实现到云端部署的全流程:以 Python + OpenCV/PaddleOCR 构建视觉识别能力,以华为云 IoTDA 完成设备建模与物联联动,最终通过 CodeArts 实现智慧路灯应用的自动化构建与部署,为具身智能与工业视觉的工程化落地提供了可复用的实践参考。

1 工效组合展示

在这里插入图片描述

2 具身智能工业视觉获取与分析应用

2.1 工具软件安装

image1

image2

image3

2.2 工业视觉环境构建与应用

image4

2.3 昇腾工业视觉终端应用展现

image5

image6

image7

3 具身智能工业视觉识别快速编码实现

3.1 IMA-DS借力

需求描述:给出 PYTHON 虚拟环境 OCR 文字识别的编码及其运行过程,包括汉字,WINDOWS 环境,CPU 运行,非 Conda,使用本机 USB 连接的海康工业相机,编码用一个完整文件。

image8

这是 Windows 平台 CPU 版 EasyOCR + 海康 USB 相机方案;如果你要移植到昇腾 Atlas200I DK A2 板子上(aarch64 欧拉系统),有两点改动:

Windows 的虚拟环境命令不再适用,改用板子的 python -m venv;

easyocr ARM 版本需要确认是否可以 pip 直接安装,不行就要离线下载 aarch64 的 whl 包。

昇腾板端移植指南

下面基于上述两点改动,给出在昇腾 Atlas 200I DK A2(aarch64 欧拉系统)上完整移植的步骤。

1. 创建 Python 虚拟环境

板端欧拉系统自带 Python 3,直接使用系统 Python 创建虚拟环境即可:

# 创建虚拟环境
python3 -m venv ocr-cam-env
# 激活虚拟环境(Linux)
source ocr-cam-env/bin/activate
# 升级 pip
pip install --upgrade pip

2. 安装 EasyOCR 离线 whl 包

若板端无法直接联网安装 EasyOCR,需在 x86 机器上下载 aarch64 的 whl 包后拷贝到板端安装:

# 在 x86 机器上执行(下载 aarch64 版本)
pip download easyocr --platform manylinux2014_aarch64 --only-binary=:all: -d ./easyocr_whl

# 将 easyocr_whl 目录拷贝到板端后,在板端虚拟环境中安装
pip install ./easyocr_whl/*.whl

若 EasyOCR 依赖的 torch 等包也需要离线安装,可一并下载:

pip download torch torchvision --platform manylinux2014_aarch64 --only-binary=:all: -d ./torch_whl
pip install ./torch_whl/*.whl

3. PaddleOCR 在昇腾 NPU 上的推理迁移思路

昇腾 Atlas 200I DK A2 自带 NPU,可将 PaddleOCR 推理从 CPU 迁移到 NPU 以显著提升性能。核心思路是使用昇腾提供的 paddle-custom-npu 插件,让 PaddlePaddle 在 NPU 上执行算子。

# 安装昇腾 NPU 版 PaddlePaddle 插件(在板端虚拟环境中)
# pip install paddle-custom-npu

import paddle
# 设置 NPU 设备
paddle.set_device("npu:0")

from paddleocr import PaddleOCR

# 初始化时指定 device="npu"
ocr = PaddleOCR(
    lang="ch",
    use_textline_orientation=True,
    use_doc_orientation_classify=False,
    use_doc_unwarping=False,
    device="npu",          # 关键:指定 NPU 推理
    enable_mkldnn=False,   # NPU 下无需开启 MKLDNN
)

若 paddle-custom-npu 与当前 PaddlePaddle 版本不兼容,可改用昇腾 CANN 工具链将 PaddleOCR 模型转换为 OM 格式,再通过 MindSpore Lite 或 ACL 接口加载推理:

# 使用 atc 工具将 PaddleOCR 检测模型转换为 OM 格式(示例)
atc --model=ch_PP-OCRv4_det_infer --framework=1 \
    --output=ch_PP-OCRv4_det --soc_version=Ascend310B4 \
    --input_shape="x:1,3,736,1280"

迁移到 NPU 后,原代码中的 OCR_INTERVAL、OCR_RESIZE 等优化参数可适当放宽,因为 NPU 推理速度远快于 CPU。

3.2 运行环境构造

# 创建虚拟环境
python -m venv ocr-cam-env
# 激活虚拟环境(Windows)
ocr-cam-env\Scripts\activate
#安装依赖包
pip install easyocr opencv-python pillow numpy

3.3 编码实现

import argparse
import sys
import time
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
except Exception:
pass
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
# ===================== 配置区 =====================
CAMERA_INDEX = 0 # 默认摄像头编号:笔记本内置=0,外接 USB 常为 1
LANG = "ch" # 文字识别语言:ch=中英文混合
USE_ANGLE_CLS = True # 文字方向分类
USE_GPU = False # 是否用 GPU
OCR_INTERVAL = 0.5 # 两次文字识别间隔(秒)
OCR_RESIZE = 1280 # 文字识别前等比缩放宽度(加速)
SHOW_SCORE = True # 是否显示文字置信度
ENABLE_OCR = True # 是否开启文字识别
ENABLE_FACE = True # 是否开启人脸检测
ENABLE_PERSON = True # 是否开启人体检测
FONT_PATH = r"C:\Windows\Fonts\simhei.ttf" # 中文字体
# =================================================
def draw_chinese_text(img_bgr, text, pos, font_path=FONT_PATH, font_size=18,
color=(0, 255, 0)):
"""在 OpenCV BGR 图像上绘制中文(cv2.putText 不支持中文,用 PIL)。"""
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(img_rgb)
draw = ImageDraw.Draw(pil_img)
try:
font = ImageFont.truetype(font_path, font_size)
except Exception:
font = ImageFont.load_default()
draw.text(pos, text, font=font, fill=(color[2], color[1], color[0]))
return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
class OCREngine:
"""文字识别(PaddleOCR),兼容 2.x / 3.x。"""
def __init__(self, lang=LANG, use_angle_cls=USE_ANGLE_CLS, use_gpu=USE_GPU):
try:
from paddleocr import PaddleOCR
except ImportError as e:
print("[错误] 未安装 PaddleOCR,请先运行 setup_usb.bat")
raise e
self.use_angle_cls = use_angle_cls
attempts = []
# PaddleOCR 3.x(GPU 用 device,CPU 不传)
p3 = dict(lang=lang,
use_textline_orientation=use_angle_cls,
use_doc_orientation_classify=False,
use_doc_unwarping=False,
enable_mkldnn=False) # 修复 PaddlePaddle 3.3.x CPU 推理崩溃
if use_gpu:
p3["device"] = "gpu"
attempts.append(p3)
# PaddleOCR 2.x
attempts.append(dict(lang=lang, use_angle_cls=use_angle_cls,
use_gpu=use_gpu, show_log=False))
# 兜底
attempts.append(dict(lang=lang))
last_err = None
for params in attempts:
try:
self.engine = PaddleOCR(**params)
break
except (TypeError, ValueError) as e:
last_err = e
else:
raise last_err
self.is_v3 = hasattr(self.engine, "predict")
def recognize(self, img_bgr):
"""识别一帧,返回 [(box, text, score), ...]。"""
items = []
result = self.engine.predict(img_bgr) if self.is_v3 \
else self.engine.ocr(img_bgr, cls=self.use_angle_cls)
if result is None:
return items
if isinstance(result, dict):
result = [result]
for page in result:
if page is None:
continue
try: # 3.x:rec_texts / rec_boxes / rec_scores
for box, text, score in zip(page["rec_boxes"],
page["rec_texts"],
page["rec_scores"]):
items.append((box, text, float(score)))
continue
except (KeyError, TypeError):
pass
for line in page: # 2.x:[[box, (text, score)], ...]
try:
box, (text, score) = line[0], line[1]
items.append((box, text, float(score)))
except Exception:
continue
return items
def draw(self, frame_bgr, items, show_score=SHOW_SCORE):
for box, text, score in items:
pts = np.array(box, dtype=np.int32).reshape((-1, 1, 2))
cv2.polylines(frame_bgr, [pts], True, (0, 255, 0), 2)
x, y = int(pts[0][0][0]), int(pts[0][0][1])
label = f"{text} {score:.2f}" if show_score else text
frame_bgr = draw_chinese_text(frame_bgr, label, (x, max(0, y - 26)),
font_size=18, color=(0, 255, 0))
return frame_bgr
class FaceDetector:
"""人脸检测(OpenCV Haar 级联,无需额外模型)。"""
def __init__(self):
path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
self.cascade = cv2.CascadeClassifier(path)
def detect(self, gray):
faces = self.cascade.detectMultiScale(
gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
return faces # [(x, y, w, h), ...]
class PersonDetector:
"""人体/行人检测(OpenCV HOG + SVM,无需额外模型)。"""
def __init__(self):
self.hog = cv2.HOGDescriptor()
self.hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
def detect(self, frame):
rects, _ = self.hog.detectMultiScale(
frame, winStride=(8, 8), padding=(16, 16), scale=1.05)
return rects # [(x, y, w, h), ...]
def open_camera(index):
"""打开摄像头,多后端尝试并读帧验证。"""
backends = [cv2.CAP_DSHOW, getattr(cv2, "CAP_MSMF", cv2.CAP_ANY), cv2.CAP_ANY]
for backend in backends:
try:
cap = cv2.VideoCapture(index, backend)
if cap.isOpened():
ok, _ = cap.read()
if ok:
return cap
cap.release()
except Exception:
pass
return None
def find_camera(prefer=CAMERA_INDEX, max_index=5):
if prefer >= 0:
cap = open_camera(prefer)
if cap is not None:
return cap, prefer
for i in range(max_index + 1):
if i == prefer:
continue
cap = open_camera(i)
if cap is not None:
return cap, i
return None, -1
def list_cameras():
print("[信息] 正在检测摄像头(编号 0~5)...")
found = []
for i in range(6):
cap = open_camera(i)
if cap is not None:
found.append(i)
cap.release()
if found:
for i in found:
print(f" 编号 {i} 可用")
print(f" 建议:python ocr_usb.py --camera {found[0]}")
else:
print("[提示] 未检测到摄像头,请检查连接/驱动/是否被占用")
def run(index, enable_ocr=ENABLE_OCR, enable_face=ENABLE_FACE,
enable_person=ENABLE_PERSON):
cap, used = find_camera(index)
if cap is None:
print("[错误] 未找到可用摄像头,请依次检查:")
print(" 1) USB 摄像头是否插入、指示灯是否亮")
print(" 2) Windows 设置 → 隐私 → 相机 是否允许访问")
print(" 3) 关闭占用摄像头的程序(浏览器/微信/会议等)")
print(" 4) 设备管理器 → 照相机 里是否能看到设备")
return
engine = OCREngine() if enable_ocr else None
face_det = FaceDetector() if enable_face else None
person_det = PersonDetector() if enable_person else None
last_items = []
last_ocr_time = 0.0
frame_count = 0
print(f"[信息] 已打开摄像头编号 {used}")
if enable_ocr:
print("[信息] 首次文字识别会自动下载中文模型,请耐心等待 ...")
print("[信息] 按键:q/ESC 退出;s 保存画面和结果")
while True:
ok, frame = cap.read()
if not ok:
print("[警告] 读取画面失败")
time.sleep(1.0)
continue
frame_count += 1
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# ---- 人脸检测(每帧)----
faces = []
if face_det is not None:
try:
faces = face_det.detect(gray)
except Exception as e:
print(f"[错误] 人脸检测失败:{e}")
# ---- 人体检测(每隔 2 帧)----
persons = []
if person_det is not None and frame_count % 2 == 0:
try:
persons = person_det.detect(frame)
except Exception as e:
print(f"[错误] 人体检测失败:{e}")
# ---- 文字识别(按间隔)----
if engine is not None and time.time() - last_ocr_time >= OCR_INTERVAL:
last_ocr_time = time.time()
img = frame
if OCR_RESIZE and frame.shape[1] > OCR_RESIZE:
scale = OCR_RESIZE / frame.shape[1]
img = cv2.resize(frame, None, fx=scale, fy=scale,
interpolation=cv2.INTER_AREA)
try:
last_items = engine.recognize(img)
if last_items:
print("-" * 40)
for box, text, score in last_items:
print(f" 文字:{text} (置信度 {score:.2f})")
except Exception as e:
print(f"[错误] 文字识别失败:{e}")
# ---- 绘制结果 ----
display = frame.copy()
if engine is not None:
display = engine.draw(display, last_items)
for (x, y, w, h) in faces:
cv2.rectangle(display, (x, y), (x + w, y + h), (255, 0, 0), 2)
display = draw_chinese_text(display, "人脸", (x, max(0, y - 24)),
font_size=18, color=(255, 0, 0))
for (x, y, w, h) in persons:
cv2.rectangle(display, (x, y), (x + w, y + h), (0, 0, 255), 2)
display = draw_chinese_text(display, "人物", (x, max(0, y - 24)),
font_size=18, color=(0, 0, 255))
tip = (f"文字 {len(last_items)} | 人脸 {len(faces)} | 人体 {len(persons)}"
" | q 退出 / s 保存")
display = draw_chinese_text(display, tip, (10, 10),
font_size=16, color=(0, 200, 255))
cv2.imshow("USB Camera - 文字/人脸/人体识别", display)
key = cv2.waitKey(1) & 0xFF
if key in (ord("q"), 27):
break
elif key == ord("s"):
stamp = time.strftime("%Y%m%d_%H%M%S")
jpg_path = f"snapshot_{stamp}.jpg"
txt_path = f"snapshot_{stamp}.txt"
cv2.imwrite(jpg_path, display)
lines = [f"文字\t{text}\t{score:.4f}"
for _, text, score in last_items]
lines += [f"人脸\t{x},{y},{w},{h}" for (x, y, w, h) in faces]
lines += [f"人体\t{x},{y},{w},{h}" for (x, y, w, h) in persons]
with open(txt_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
print(f"[信息] 已保存:{jpg_path} 和 {txt_path}")
cap.release()
cv2.destroyAllWindows()
def main():
parser = argparse.ArgumentParser(description="USB 摄像头 文字/人脸/人体识别")
parser.add_argument("--camera", type=int, default=CAMERA_INDEX)
parser.add_argument("--list", action="store_true", help="列出可用摄像头")
parser.add_argument("--lang", default=LANG)
parser.add_argument("--gpu", action="store_true")
parser.add_argument("--no-ocr", action="store_true", help="关闭文字识别")
parser.add_argument("--no-face", action="store_true", help="关闭人脸检测")
parser.add_argument("--no-person", action="store_true", help="关闭人体检测")
args = parser.parse_args()
if args.list:
list_cameras()
else:
run(args.camera,
enable_ocr=not args.no_ocr,
enable_face=not args.no_face,
enable_person=not args.no_person)
if __name__ == "__main__":
main()

3.4 运行测试

image9

3.5 常见问题与排查

3.5.1 摄像头无法打开

现象:运行脚本后提示 [错误] 未找到可用摄像头,或 cv2.VideoCapture 返回 False。

排查步骤:

  1. 确认 USB 摄像头已插入且指示灯亮起,换一个 USB 口重试;
  2. 检查 Windows 设置 → 隐私 → 相机,确认「允许桌面应用访问相机」已开启;
  3. 关闭占用摄像头的程序(浏览器、微信、腾讯会议等);
  4. 打开设备管理器 → 照相机,确认设备存在且驱动正常(无黄色感叹号);
  5. 运行 python ocr_usb.py --list 查看可用摄像头编号,若外接相机不是 0,改用 --camera 1 指定。

代码调整建议:若默认编号不对,可在配置区修改 CAMERA_INDEX = 1,或运行时加参数:

python ocr_usb.py --camera 1
3.5.2 PaddleOCR 模型下载失败

现象:首次运行文字识别时长时间卡在「正在下载中文模型」,或提示网络超时、ConnectionError。

解决方案:

  1. 检查网络能否访问外网,必要时配置代理;
  2. 手动下载模型并放到本地缓存目录(~/.paddleocr/),避免运行时联网;
  3. 若公司内网受限,可先在有外网的机器上下载模型,再拷贝到目标机器对应目录。

代码调整建议:在 OCREngine.__init__ 中增加离线模式,模型已存在时不再联网:

# 在 OCREngine.__init__ 中,PaddleOCR 初始化前加入:
import os
os.environ.setdefault("PADDLE_PDX_MODEL_SOURCE", "local")  # 优先使用本地模型
3.5.3 中文显示乱码

现象:画面上的中文标签显示为方框或乱码。

原因:cv2.putText 不支持中文,代码已改用 PIL 绘制,但若系统缺少 simhei.ttf 字体,会回退到默认字体导致乱码。

解决方案:

  1. 确认 C:\Windows\Fonts\simhei.ttf 存在;若没有,可改用 msyh.ttc(微软雅黑);
  2. 修改配置区字体路径:
FONT_PATH = r"C:\Windows\Fonts\msyh.ttc"  # 微软雅黑
  1. 若仍乱码,可在 draw_chinese_text 中打印字体加载是否成功,便于定位。
3.5.4 CPU 推理慢

现象:文字识别一帧耗时较长,画面明显卡顿。

原因:PaddleOCR 在 CPU 上推理较慢,尤其当输入分辨率较高时。

优化建议:

  1. 调大识别间隔,减少每秒钟的推理次数:
OCR_INTERVAL = 1.0   # 从 0.5 改为 1.0,每秒识别一次
  1. 进一步缩小识别前缩放宽度,降低计算量:
OCR_RESIZE = 960     # 从 1280 改为 960
  1. 关闭不必要的检测功能,只保留需要的:
python ocr_usb.py --no-face --no-person   # 只做文字识别
  1. 若机器支持,可尝试开启 GPU 推理(需安装 GPU 版 PaddlePaddle):
python ocr_usb.py --gpu

4 IoTDA中转空间构建

4.0 IoTDA构造

image10

image11

image12

4.1 产品及其模型构建

image13

4.1.1 温湿度计

image14

产品信息

产品名称:温湿度计

协议类型:MQTT

数据格式:JSON

所属行业:智能家居

服务列表详情(服务 ID:T&H)

属性名称:temperature,数据类型:decimal,访问权限:可读可写,取值范围:-100 ~ 100

属性名称:humidity,数据类型:decimal,访问权限:可读可写,取值范围:0 ~ 100

4.1.2 吸顶灯

image15

产品信息

产品名称:智能吸顶灯 协议类型:MQTT 数据格式:JSON 所属行业:智能家居

服务列表定义

服务 ID:Light

属性名称:光照强度 (luminance),数据类型:decimal,访问权限:可读可写,取值范围:0 ~ 5000

属性名称:功率 (power),数据类型:decimal,访问权限:可读可写,取值范围:010000

命令名称:Light   下发参数名称:turn,数据类型:string,长度:10   下发参数名称:power,数据类型:string,取值范围:010000

服务 ID:Color

属性名称:crtColor(灯光颜色),数据类型:string,长度:10

命令名称:setColor,数据类型:string,长度:10

4.2 设备实例化应用

image16

4.2.1 温湿度计设备注册及模拟测试

image17

image18

image19

4.2.2 吸顶灯设备注册及模拟测试

image20

image21

image22

5 CodeArts智慧路灯快速构建与部署

5.1 应用项目创建

image23

image24

5.2 代码托管操作

image25

5.3 构建任务设立

image26

image27

5.4 项目构建实现

image28

5.5 项目部署运行

image29

image30

image31

6 实验总结与心得

本次实训围绕具身智能工业视觉分析与物联监护展开,完整走通了从视觉感知到云端联动的全流程。在工业视觉识别模块,基于昇腾 Atlas 200I DK A2 与 Windows 环境,通过 Python 虚拟环境实现了 PaddleOCR 文字识别、人脸及人体检测,掌握了 CPU 推理优化技巧(如调整识别间隔、缩放输入分辨率、按需关闭检测功能),并解决了中文乱码、模型下载失败等实际问题。在 IoTDA 物联监护模块,完成了温湿度计与吸顶灯的产品建模、设备注册与模拟测试,深入理解了 MQTT 协议、JSON 数据格式及设备属性/命令的定义方法。在 CodeArts 智慧路灯部署模块,体验了从项目创建、代码托管、构建任务设立到自动化部署的完整链路,体会到持续集成与持续部署(CI/CD)对工程效率的提升。

本次实训最大的收获是将视觉识别、物联网与云原生部署三大技术栈串联成完整方案,提升了工程化落地能力。可改进方向包括:将 PaddleOCR 推理迁移至昇腾 NPU 以提升性能,引入更多传感器丰富物联场景,并进一步优化 CodeArts 流水线实现更细粒度的自动化发布。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐