文章目录
-
- 前言
- 视觉 AI 的能力全景
- 接入 ObjectRecognizer:认识冰箱里的食材
- 拍照 + AI 分析:串起整个链路
- 用 ImageDescriber 做语义理解
- 把视觉结果和食谱推荐串起来
- 性能表现
- 一个坑:相机权限和后台识别
- 小结
前言
智能生活助手光会聊天和调度 Agent 还不够。想象一下这个场景:用户打开冰箱,对着里面的食材拍张照,助手就能告诉你"这些够做宫保鸡丁和番茄蛋汤"。这就是今天的主角——HarmonyOS 7 的视觉 AI 能力。
视觉 AI 的能力全景

HarmonyOS 7 的视觉 AI 不是简单地封装了一个 OCR 接口。它在系统层面提供了一整套端侧图像处理管线,包括图像分类、物体检测、OCR 文字识别、语义分割、图像描述生成等。
对我们开发者来说,最值得关注的是"场景化控件"这个概念。系统预置了几种 AI 控件,直接嵌入到 ArkUI 里就能用,不用你操心模型加载和推理的底层细节:
- SmartScan:扫码、文字识别、文档矫正,一站式搞定
- ObjectRecognizer:通用物体检测,能框出物体并给出分类
- ImageDescriber:图像语义理解,能用自然语言描述图片内容
这些控件背后跑的是端侧优化的视觉模型,推理速度比上代快了接近一倍。
接入 ObjectRecognizer:认识冰箱里的食材
回到我们的实战场景。用户拍一张冰箱照片,我们要识别出里面的食材。先搞定拍照部分:
import { cameraPicker, camera } from '@kit.CameraKit';
import { image } from '@kit.ImageKit';
@Entry
@Component
struct FoodScanPage {
@State capturedImage: image.PixelMap | null = null;
@State recognitionResults: FoodItem[] = [];
@State isAnalyzing: boolean = false;
build() {
Column() {
if (this.capturedImage) {
// 显示拍到的照片
Image(this.capturedImage)
.width('100%')
.height(300)
.objectFit(ImageFit.Contain)
.borderRadius(12)
} else {
// 占位引导
Column() {
Image($r('app.media.camera_placeholder'))
.width(64).height(64)
.fillColor('#999999')
Text('打开冰箱拍一张')
.fontSize(16)
.fontColor('#666666')
.margin({ top: 12 })
}
.width('100%')
.height(300)
.justifyContent(FlexAlign.Center)
.backgroundColor('#F5F5F5')
.borderRadius(12)
}
Button(this.isAnalyzing ? '识别中…' : '拍照识别')
.width('80%')
.height(48)
.margin({ top: 20 })
.enabled(!this.isAnalyzing)
.onClick(() => this.captureAndAnalyze())
// 识别结果列表
if (this.recognitionResults.length > 0) {
this.ResultList()
}
}
.padding(16)
.width('100%')
}
@Builder
ResultList() {
List() {
ForEach(this.recognitionResults, (item: FoodItem) => {
ListItem() {
Row() {
Text(item.name)
.fontSize(16)
.fontWeight(FontWeight.Medium)
Blank()
Text(item.freshness)
.fontSize(14)
.fontColor(item.freshness === '新鲜' ? '#4CAF50' : '#FF9800')
}
.padding(12)
}
})
}
.width('100%')
.margin({ top: 16 })
}
}

拍照 + AI 分析:串起整个链路
拍照按钮点击后,先调起相机拍照,再把图片喂给视觉 AI 做识别:
interface FoodItem {
name: string;
confidence: number;
freshness: string;
bbox: number[]; // 边界框坐标
}
// 拍照并分析
async captureAndAnalyze(): Promise<void> {
this.isAnalyzing = true;
try {
// 1. 调起相机拍照
const photoUri = await this.takePhoto();
const pixelMap = await this.loadPixelMap(photoUri);
this.capturedImage = pixelMap;
// 2. 调用端侧物体识别
const results = await this.recognizeFood(pixelMap);
this.recognitionResults = results;
// 3. 根据识别结果,调用食谱推荐 Agent
if (results.length > 0) {
await this.recommendRecipes(results);
}
} catch (err) {
console.error('拍照识别流程出错:', JSON.stringify(err));
} finally {
this.isAnalyzing = false;
}
}
// 拍照
async takePhoto(): Promise<string> {
const cameraPickerResult = await cameraPicker.pick(this.context,
[cameraPicker.MediaType.PHOTO], {
photoQualityPrioritize: camera.PhotoQualityPrioritize.QUALITY,
pickerProfile: {
cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
}
}
);
return cameraPickerResult.photoUri;
}
// 视觉 AI 识别食材
async recognizeFood(pixelMap: image.PixelMap): Promise<FoodItem[]> {
const visionEngine = await visionKit.createObjectRecognizer({
// 指定识别类别为食品
categoryFilter: ['food', 'vegetable', 'fruit', 'meat', 'dairy'],
// 置信度阈值
minConfidence: 0.6,
// 返回边界框
returnBBox: true
});
const recognitionResult = await visionEngine.recognize(pixelMap);
return recognitionResult.objects.map(obj => ({
name: obj.label,
confidence: obj.confidence,
freshness: obj.attributes?.['freshness'] ?? '未知',
bbox: obj.boundingBox ?? []
}));
}

categoryFilter 这个参数很实用。默认情况下物体检测会返回所有类别的物体,图片里东西一多结果就很杂。指定 food 相关的类别后,只会返回食材相关的识别结果,精度也更高。
用 ImageDescriber 做语义理解
有时候你需要的不只是"这是什么物体",而是"这张图在说什么"。比如用户拍了一张菜品的照片,想知道菜名和大致做法。这时候 ObjectRecognizer 就不够用了,得上 ImageDescriber:
// 语义级图像理解
async describeImage(pixelMap: image.PixelMap): Promise<ImageDescription> {
const describer = await visionKit.createImageDescriber({
// 输出语言
language: 'zh-CN',
// 描述粒度:brief=一句话, detailed=详细描述
detailLevel: visionKit.DetailLevel.DETAILED,
// 是否生成结构化信息
structuredOutput: true
});
const description = await describer.describe(pixelMap);
// description 包含:
// – summary: "一道宫保鸡丁,色泽红亮,配有花生和葱段"
// – objects: 检测到的物体列表
// – scene: "中餐"
// – attributes: { cuisine: "川菜", cooking_method: "炒" }
return {
summary: description.summary,
cuisine: description.attributes?.['cuisine'] ?? '未知',
cookingMethod: description.attributes?.['cooking_method'] ?? '未知',
detectedIngredients: description.objects.map(o => o.label)
};
}
ImageDescriber 跟 openPangu 2.0 的图像理解能力是打通的。你甚至可以把图像描述结果直接喂给大模型,让它基于视觉信息生成更丰富的回复。
把视觉结果和食谱推荐串起来
识别出食材之后,最自然的下一步就是推荐食谱。这里我们结合 A2A 协议调用推荐 Agent,再用 openPangu 生成最终回复:
async recommendRecipes(foodItems: FoodItem[]): Promise<void> {
// 提取食材名称列表
const ingredients = foodItems.map(item => item.name);
// 通过 A2A 调用食谱推荐 Agent
const recipeResult = await agentManager.sendTask({
targetAgentId: 'com.example.smartlife.recipe',
capabilityId: 'search_recipes',
input: {
ingredients: ingredients,
matchMode: 'fuzzy', // 模糊匹配,不必所有食材都有
maxResults: 3
}
});
// 拿到候选食谱后,让大模型生成个性化推荐
const llmResponse = await llmSession!.generate({
prompt: `用户冰箱里有这些食材:${ingredients.join('、')}。
可做的菜品有:${JSON.stringify(recipeResult.output.recipes)}。
请推荐最适合的一两道菜,简单说明理由,并给出关键步骤。
语气亲切自然,像朋友推荐一样。`,
maxTokens: 512,
temperature: 0.8
});
AppStorage.setOrCreate('recipeRecommendation', llmResponse.text);
}
整个链路是:拍照 → 视觉 AI 识别食材 → A2A 调用食谱 Agent → openPangu 生成推荐文案。用户看到的是一段自然语言的食谱推荐,背后是三个模块在协作。
性能表现
端侧视觉 AI 的速度让我比较惊喜。ObjectRecognizer 在麒麟 9030 上识别一张 1080p 的图片大概 150-200ms,ImageDescriber 稍慢一点,大概 500-800ms。对于拍照识别这种场景,这个延迟完全可以接受。
不过要注意内存。如果你同时加载视觉模型和 openPangu 2.0,内存占用能到 1.5GB 以上。建议在视觉识别完成、结果拿到后,及时释放视觉模型的会话:
// 用完就释放,给大模型腾内存
await visionEngine.release();
一个坑:相机权限和后台识别
视觉 AI 涉及相机权限,别忘了在 module.json5 声明。另外如果你想做后台持续识别(比如用户开着相机实时识别),需要额外申请 CAMERA_BACKGROUND 权限,审核比较严格,场景说明要写清楚。
还有个容易忽略的点:PixelMap 的格式。ObjectRecognizer 要求输入 NV21 或 RGBA_8888 格式,如果你从相机拿到的 PixelMap 是 JPEG 编码的,得先做一次解码转换,不然识别会报错。
小结
视觉 AI 让智能生活助手从"能听能说"进化到了"能看"。结合端侧物体识别、语义理解、A2A 调度和大模型生成,一条完整的"拍照→识别→推荐"链路就跑通了。
实际开发中我发现,视觉 AI 最难的点不在接入,而在怎么设计好用户交互——什么时候提示用户拍照、识别结果怎么展示、置信度低的要不要过滤,这些细节决定了用户体验。代码能跑通只是第一步,打磨交互才是真功夫。
下一篇来聊空间音频引擎——让我们的语音助手不只是一个文字对话框,而是真正能"听到声音"的交互体验。

![[人工智能]啥是大模型?一篇文章看懂火遍全网的“AI大模型”_ai大模型 人工智能技术层-171主机测评](https://www.171host.com/wp-content/uploads/2026/09/20260907140726-6a9ec51e1639d-220x150.jpg)
![[人工智能]啥是大模型?一篇文章看懂火遍全网的“AI大模型”_ai大模型 人工智能技术层-171主机测评](https://www.171host.com/wp-content/uploads/2026/09/20260907140149-6a9ec3cd14c98-220x150.jpg)


