【HarmonyOS 7 视觉 AI 开放能力深度实战】 08 视觉 AI 统一封装与应用接入实战
文章目录
前言

一张图片进入应用后,用户可能想提取其中的文字,也可能想找出物体位置、分离主体或者放大图片。如果每增加一种功能就复制一套选图、状态提示和资源清理代码,页面很快会出现多份相似实现。后来需要修复取消处理或图片释放问题时,就要逐个检查这些入口。
我们已经分别接入了文字识别、主体分割、目标检测和图像超分。现在把四种单图处理放到同一个页面,让它们共用图片读取、任务状态和结果展示,同时保留各自的服务调用方式。用户选择功能和图片以后,就能在同一处发起处理并查看结果。
一、从共同的使用过程整理入口
四种功能的输入都是图片解码后得到的 PixelMap。页面需要先准备输入,再根据用户选择调用相应能力,等待结果返回后更新界面。选图、处理中提示、错误展示和退出清理在这些操作中反复出现,因此可以集中管理。
各项能力的输出又有所不同。文字识别需要展示文本及文字行信息,目标检测返回对象列表,主体分割和图像超分返回新的像素图。如果页面只接收一段字符串,就会丢失后续画框或展示图片需要的数据。我们定义 VisionResult,让它同时保留文字、文字行、对象列表和可选的输出图片。
每次调用只填充当前能力用到的字段。OCR 分支写入文字和行对象,目标检测写入对象数组,分割和超分把像素图放进 picture。页面拿到结果后,根据当前功能显示文字数量、对象信息或者输出图片,未使用的字段保持默认值。
例如用户先执行文字识别,再切换到目标检测时,新的结果对象会重新创建。上一轮的文字不会进入这次对象列表,页面也会在开始处理前清除旧详情。这样不同功能可以共用结果结构,同时保持每次调用的数据边界。
文档扫描和文搜图仍然有自己的操作流程。扫描页面需要接收系统控件返回的文件,文搜图需要维护图片索引并支持多次查询。它们的交互与一次像素图处理不同,所以这里的统一接口先覆盖四种单图能力。前面介绍的扫描和检索流程仍可独立接入应用。

我们把职责分成三个部分。ImageStore 负责读取和保存图片,VisionAdapter 负责调用对应的视觉接口,VisionTask 负责本次处理的状态和结果有效性。页面连接这些部分,决定用户当前看到什么,并持有仍在显示的输入与输出。
二、为不同能力保留各自的调用方式
虽然页面都从同一个入口发起处理,底层接口的使用顺序仍然需要分别遵守。文字识别和主体分割先初始化服务,完成处理后释放服务。目标检测和图像超分则先创建各自的分析器,在处理结束后销毁分析器。
VisionAdapter.process() 接收功能名称和输入像素图,再进入对应分支。每个分支只负责自己需要的调用和结果转换,结束动作放在 finally 中。这样页面无需重复编写服务清理,也不会假定四种能力使用完全相同的初始化接口。
if (kind === '目标') {
const analyzer = await objectDetection.ObjectDetector.create();
try {
const data = await analyzer.process({ inputData: { pixelMap: input } });
result.objects = data.objects;
result.text = JSON.stringify(data.objects);
return result;
} finally { await analyzer.destroy(); }
}
目标检测分支保留对象列表,也将结果整理成文字供页面查看。以后需要绘制边界框时,页面可以继续读取对象中的原始坐标,不必再从展示文字中解析。主体分割和超分分支把输出像素图交给页面,页面在显示完成之前会继续持有它。
如果传入不支持的功能名称,适配层抛出错误,由页面展示失败信息。真实业务中也可以根据错误类型提供更具体的提示,但不能把调用失败统一显示成没有识别到内容。没有检测到对象是一种处理结果,接口没有完成调用则需要用户检查输入或重试。
当前页面把四个功能按钮与各自的默认图片对应起来。选择功能后,页面先读取该功能的图片,再更新当前功能、输入和结果区域。用户也可以另外选择图片,所选图片会交给当前功能处理。不同能力的输入尺寸要求并不完全相同,选择自己的图片后仍要满足所选接口的要求。

三、把选图和保存纳入页面操作
一次用户操作并不只有视觉接口调用。选图时,系统选择器可能等待用户较长时间,图片解码也需要异步完成。如果此时页面又开始处理旧图片,用户看到的新选择与实际调用的输入就可能不一致。
页面使用 launch() 作为操作入口。入口在启动时设置 activeJob,并保存整项操作对应的 pagePending。选图、准备默认图片和开始处理都经过这里。前一个操作尚未结束时,新的入口不会并行执行。
private launch(action: () => Promise<void>): void {
if (this.activeJob || !this.alive) { return; }
this.activeJob = true;
// 输入、调用和保存都纳入页面任务,退出时等待最后一个使用者。
this.pagePending = action().catch((err: BusinessError) => { if (this.alive) { this.fail(err); } })
.finally(() => { this.activeJob = false; });
}
开始处理以后,分割和超分可能返回需要保存的图片。页面会等待 PNG 编码和文件写入结束,然后才结束这次页面操作。即使视觉服务已经返回,保存仍在使用输出像素图,页面入口也会继续保持忙碌,避免用户立即更换图片并释放正在使用的结果。
页面操作和视觉任务因此各自有一个忙碌状态。前者覆盖从准备输入到保存完成的整个过程,后者只覆盖视觉处理尚未结束的时间。把两者分开以后,取消按钮可以只在视觉处理期间生效,页面上的其他操作则继续等到文件保存结束。
当用户选择一张新图片时,页面在解码成功后替换旧输入,并清除旧输出与详情。选择器被关闭且没有选择文件时,页面保留已有输入。这样画面中的图片始终对应下一次处理,而一次取消选图也不会让用户丢失手头的结果。

上面的截图来自包含功能目录的页面。文末整理的独立页面直接提供四个功能按钮,OCR 结果显示识别文字和文字行数量,目标检测显示对象字段,分割与超分显示输出图片。结果展示方式对应各分支真正返回的数据。
四、让取消后的旧结果失效
用户点击开始处理后,服务可能需要一段时间才能返回。如果用户在等待时点击取消,页面需要避免旧结果随后覆盖界面。这里的任务层使用递增的 generation 标识:开始时记录当前标识,取消时更新标识,返回时再检查两者是否一致。
if (this.busy) { throw new Error('上一次处理仍未结束'); }
this.busy = true;
this.state = '处理中';
const token = ++this.generation;
当返回结果的标识仍然有效时,任务层把结果交给页面。如果标识已经变化,任务层丢弃这次结果。对于分割或超分产生的像素图,如果图片还没有交给页面,任务层会释放它,避免失效输出继续占用资源。
取消结果并不保证底层调用立即停止。任务层会等原来的调用结束,再恢复自己的忙碌状态。等待期间页面显示正在等待的提示,用户也不能再次发起处理。这样同一张输入图不会在服务仍然读取时被提前释放。
任务还设置了三十秒的等待计时。计时结束后,如果本次调用仍在执行,任务层会让结果失效,并继续等待底层返回。这个时间用于控制页面是否接收结果,不能用来推断算法一定在三十秒内停止。
处理抛出异常时,任务层同样检查标识。属于当前任务的错误继续交给页面,已经取消的任务结束为取消状态。无论成功、失败还是结果失效,结束路径都会清除计时器并恢复任务状态,页面也能重新接受后续操作。
五、按实际使用时间释放资源
分析器、输入图和输出图的使用时间并不相同。分析器在处理结束后由适配层释放,输入图还要留在页面中供用户查看或重试。输出图可能继续被图片组件显示,也可能正在交给编码器保存,因此不能在服务刚返回时统一释放。
用户离开页面时,页面先设置存活标记,再通知任务层让未完成结果失效。随后清理过程等待 pagePending 结束,最后释放页面持有的输入和输出。即使用户在 PNG 保存过程中离开,编码器也能先完成对像素图的读取。
如果默认图片或选图在页面离开后才完成解码,代码会释放刚得到的像素图,不再把它交给已经离开的页面。视觉处理返回的图片也有相应判断。等待异步操作结束和继续更新界面是两件事,页面可以停止接收结果,同时让资源清理按顺序完成。
这些判断也说明了输出的交接位置。结果还在任务层时,任务层负责处理失效图片。结果交给页面以后,页面负责显示、保存和最终释放。给资源确定清楚的持有方,出现图片提前失效或长期占用内存时,就能沿着交接过程排查。
再次开始处理时,页面先释放旧输出并清空详情。这样新任务失败时,旧图片不会留在结果区域,让用户误以为当前处理已经成功。输入图片则保留,用户可以检查错误后再次点击处理。
六、从现有页面接入视觉能力
现有图片页面可以先从一个明确的用户动作开始接入。例如用户打开白板照片后点击提取文字,页面把当前图片交给 OCR 分支,再展示可复制的文本。用户随后如果希望保留图片中的主体,可以切换到分割分支,查看输出并决定是否保存。
统一任务层让这些入口共享同一套状态处理,但页面仍需要按照业务决定结果如何呈现。文字适合放进编辑框继续修改,检测结果可以关联图片上的标记,前景图则可以进入贴纸或合成页面。每种输出保留自己的数据类型,后续页面才能按实际需要继续使用。
接入时还要考虑用户能否理解当前状态。处理中应让用户知道操作已经开始,取消后如果还在等待底层结束,也需要保留等待提示。失败时展示能够帮助重试的信息,用户才知道应该更换图片、检查输入还是稍后再试。
本页采用一次只执行一个操作的方式,适合用户逐张处理图片。需要批量处理时,可以在此基础上设计队列,明确每张图片的输入、结果和失败状态。直接让多个操作共用当前页面的单个输入与输出字段,会让结果归属难以判断。
队列中的每个项目还需要记录所选功能,因为同一张图片可能先后执行文字识别和主体分割。任务完成以后,应用按项目关联结果,再决定继续处理下一张还是提示用户重试。这样扩展时仍能保留当前单次调用的输入与结果关系。
总结
我们把四种单图视觉能力接入同一个页面,依次完成图片准备、功能调用、结果展示和资源清理。文档扫描与图片检索保留各自的交互流程,应用可以根据用户操作分别接入。
VisionAdapter 保留各服务原有的初始化和释放方式,VisionResult 保存不同类型的结果,VisionTask 管理处理状态和取消后的结果有效性。ImageStore 与页面共同负责图片的读取、保存和持有时间。
大家可以先将其中一种能力接入自己的图片页面,确认输入、结果和错误提示,再逐步加入其他功能。也可以尝试在处理过程中取消或离开页面,观察任务结束后界面和资源的状态。
核心关键代码
下面整理的是可独立放入工程的统一接入页面。截图来自包含功能目录的页面,下面的版本启动后直接显示四种单图能力。请在 entry/src/main/resources/rawfile 中准备 ocr.png、coffee.png、cat.png 和 low.jpg,并在页面配置中注册 pages/Index。
在 API 26 工程中,检查 entry/src/main/resources/base/profile/main_pages.json 的 src 是否包含 pages/Index,并让 entry/src/main/ets/entryability/EntryAbility.ets 中的 loadContent() 加载这个页面。缺少 services 目录时先创建,再添加以下文件。
Core Vision Kit 的视觉处理需要在支持该能力的真机上运行,模拟器暂不支持本篇调用。服务区域为中国境内,不含港澳台。
能力适配:VisionAdapter.ets
将以下代码保存为 entry/src/main/ets/services/VisionAdapter.ets。
import { image } from '@kit.ImageKit';
import { textRecognition, subjectSegmentation, objectDetection, imageSuperResolution } from '@kit.CoreVisionKit';
// 保存各能力真实返回的文字、对象和图片。
export class VisionResult {
text: string = '';
lines: textRecognition.TextLine[] = [];
objects: objectDetection.VisionObject[] = [];
picture: image.PixelMap | undefined = undefined;
}
// 扫描控件与文搜图有各自的交互和索引状态,不纳入单张图片处理接口。
export class VisionAdapter {
async process(kind: string, input: image.PixelMap): Promise<VisionResult> {
const result = new VisionResult();
// OCR 和分割分别初始化并释放各自的服务。
if (kind === 'OCR') {
try {
if (!await textRecognition.init()) { throw new Error('OCR 初始化失败'); }
const data = await textRecognition.recognizeText({ pixelMap: input }, { isDirectionDetectionSupported: true });
result.text = data.value;
data.blocks.forEach((block) => { block.lines.forEach((line) => { result.lines.push(line); }); });
return result;
} finally { await textRecognition.release(); }
}
if (kind === '分割') {
try {
if (!await subjectSegmentation.init()) { throw new Error('主体分割初始化失败'); }
const data = await subjectSegmentation.doSegmentation({ pixelMap: input }, { maxCount: 6, enableSubjectDetails: false, enableSubjectForegroundImage: true });
result.picture = data.fullSubject.foregroundImage;
result.text = '主体数量:' + data.subjectCount + '\n区域:' + JSON.stringify(data.fullSubject.subjectRectangle);
return result;
} finally { await subjectSegmentation.release(); }
}
// 目标检测与超分使用各自的分析器。
if (kind === '目标') {
const analyzer = await objectDetection.ObjectDetector.create();
try {
const data = await analyzer.process({ inputData: { pixelMap: input } });
result.objects = data.objects;
result.text = JSON.stringify(data.objects);
return result;
} finally { await analyzer.destroy(); }
}
if (kind === '超分') {
const analyzer = await imageSuperResolution.ImageSRAnalyzer.create();
try {
const data = await analyzer.process({ inputData: { pixelMap: input } });
result.picture = data.pixelMap;
const info = await data.pixelMap.getImageInfo();
result.text = '输出尺寸:' + info.size.width + ' × ' + info.size.height;
return result;
} finally { await analyzer.destroy(); }
}
throw new Error('未支持的处理功能:' + kind);
}
}
图片读取和保存:ImageStore.ets
将以下代码保存为 entry/src/main/ets/services/ImageStore.ets。
import { image } from '@kit.ImageKit';
import { common } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
export class ImageStore {
private context: common.UIAbilityContext;
constructor(context: common.UIAbilityContext) { this.context = context; }
async raw(name: string): Promise<image.PixelMap> {
const bytes = await this.context.resourceManager.getRawFileContent(name);
const source = image.createImageSource(bytes.buffer as ArrayBuffer);
try {
// 图像解码后交给视觉接口,图像源不再由页面持有。
return await source.createPixelMap({ desiredPixelFormat: image.PixelMapFormat.RGBA_8888 });
} finally { source.release(); }
}
async choose(): Promise<image.PixelMap | undefined> {
const picker = new photoAccessHelper.PhotoViewPicker();
const result = await picker.select({ MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE, maxSelectNumber: 1 });
if (result.photoUris.length === 0) { return undefined; }
const file = fileIo.openSync(result.photoUris[0], fileIo.OpenMode.READ_ONLY);
let source: image.ImageSource | undefined = undefined;
try {
source = image.createImageSource(file.fd);
return await source.createPixelMap({ desiredPixelFormat: image.PixelMapFormat.RGBA_8888 });
} finally { source?.release(); fileIo.closeSync(file); }
}
async png(pm: image.PixelMap, name: string): Promise<string> {
const packer = image.createImagePacker();
try {
// 等待编码完成,再将 PNG 数据写入应用文件目录。
const bytes = await packer.packToData(pm, { format: 'image/png', quality: 100 });
const path = this.context.filesDir + '/' + name;
const file = fileIo.openSync(path, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.TRUNC);
try { fileIo.writeSync(file.fd, bytes); } finally { fileIo.closeSync(file); }
return path;
} finally { packer.release(); }
}
}
任务管理:VisionTask.ets
将以下代码保存为 entry/src/main/ets/services/VisionTask.ets。
import { image } from '@kit.ImageKit';
import { VisionAdapter, VisionResult } from './VisionAdapter';
export class VisionTask {
busy: boolean = false;
state: string = '待处理';
private generation: number = 0;
private pending: Promise<VisionResult> | undefined = undefined;
cancel(): void {
if (!this.busy) { return; }
// 更换标识,使还在执行的任务返回后不再提交旧结果。
this.generation++;
this.state = '正在等待底层调用结束,结果将被丢弃';
}
async run(kind: string, input: image.PixelMap): Promise<VisionResult | undefined> {
if (this.busy) { throw new Error('上一次处理仍未结束'); }
this.busy = true;
this.state = '处理中';
const token = ++this.generation;
// 超时只使结果失效,仍要等待底层调用结束。
const timer = setTimeout(() => { if (this.busy && token === this.generation) { this.cancel(); } }, 30000);
try {
this.pending = new VisionAdapter().process(kind, input);
const result = await this.pending;
if (token !== this.generation) {
result.picture?.release();
this.state = '已取消,可重新处理';
return undefined;
}
this.state = '处理完成';
return result;
} catch (err) {
this.state = token === this.generation ? '处理失败,可检查输入后重试' : '已取消,可重新处理';
if (token === this.generation) { throw err as Error; }
return undefined;
} finally {
clearTimeout(timer);
this.pending = undefined;
this.busy = false;
}
}
}
页面入口:Index.ets
将以下代码保存为 entry/src/main/ets/pages/Index.ets。
import { image } from '@kit.ImageKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ImageStore } from '../services/ImageStore';
import { VisionTask } from '../services/VisionTask';
@Entry
@Component
struct Index {
@State kind: string = 'OCR';
@State input: image.PixelMap | undefined = undefined;
@State output: image.PixelMap | undefined = undefined;
@State status: string = '准备输入图片';
@State detail: string = '';
@State errorMessage: string = '';
@State busy: boolean = false;
@State processing: boolean = false;
private alive: boolean = true;
private activeJob: boolean = false;
private pagePending: Promise<void> | undefined = undefined;
private task: VisionTask = new VisionTask();
private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
private io: ImageStore = new ImageStore(this.context);
aboutToAppear(): void { this.alive = true; this.launch(() => this.prepare('OCR', 'ocr.png')); }
aboutToDisappear(): void { this.alive = false; this.dispose(); }
private launch(action: () => Promise<void>): void {
if (this.activeJob || !this.alive) { return; }
this.activeJob = true;
// 输入、调用和保存都纳入页面任务,退出时等待最后一个使用者。
this.pagePending = action().catch((err: BusinessError) => { if (this.alive) { this.fail(err); } })
.finally(() => { this.activeJob = false; });
}
private async dispose(): Promise<void> {
this.task.cancel();
try { await this.pagePending; } catch (_) { /* 错误由入口处理。 */ }
this.input?.release(); this.input = undefined;
this.output?.release(); this.output = undefined;
}
private fail(err: BusinessError): void {
if (!this.alive) { return; }
this.status = '处理失败,可检查输入后重试';
this.errorMessage = '错误码:' + (err.code ?? -1) + '\n' + err.message;
}
private async prepare(kind: string, name: string): Promise<void> {
if (this.busy || this.task.busy) { return; }
this.busy = true; this.errorMessage = '';
try {
const pm = await this.io.raw(name);
if (!this.alive) { pm.release(); return; }
// 新输入就绪后,再一起更新功能、图片与结果。
this.input?.release(); this.input = pm; this.kind = kind;
this.output?.release(); this.output = undefined; this.detail = '';
const info = await pm.getImageInfo();
if (this.alive) { this.status = '当前功能:' + kind + ',输入尺寸:' + info.size.width + ' × ' + info.size.height; }
} catch (err) { this.fail(err as BusinessError); }
finally { if (this.alive) { this.busy = false; } }
}
private async choose(): Promise<void> {
if (this.busy) { return; }
this.busy = true; this.errorMessage = '';
try {
const pm = await this.io.choose();
if (!this.alive) { pm?.release(); return; }
if (!pm) { this.status = '未选择图片,保留原输入'; return; }
this.input?.release(); this.input = pm;
this.output?.release(); this.output = undefined; this.detail = '';
const info = await pm.getImageInfo();
if (this.alive) { this.status = '当前功能:' + this.kind + ',输入尺寸:' + info.size.width + ' × ' + info.size.height; }
} catch (err) { this.fail(err as BusinessError); }
finally { if (this.alive) { this.busy = false; } }
}
private async run(): Promise<void> {
if (this.busy || !this.input) { return; }
this.busy = true; this.processing = true; this.status = '处理中'; this.detail = ''; this.errorMessage = '';
this.output?.release(); this.output = undefined;
try {
const result = await this.task.run(this.kind, this.input);
if (this.alive) { this.processing = false; }
if (!this.alive) { result?.picture?.release(); return; }
if (result) {
this.output = result.picture; this.detail = result.text;
if (this.kind === 'OCR') { this.detail += '\n文字行数量:' + result.lines.length; }
if (this.kind === '目标') { this.detail += '\n目标数量:' + result.objects.length; }
if (this.output) {
const name = this.kind === '分割' ? 'subject-result.png' : 'super-resolution.png';
const path = await this.io.png(this.output, name);
if (!this.alive) { return; }
this.detail += '\n保存到:' + path;
}
}
if (this.alive) { this.status = this.task.state; }
} catch (err) { if (this.alive) { this.fail(err as BusinessError); } }
finally { if (this.alive) { this.processing = false; this.busy = false; } }
}
build() {
Column({ space: 10 }) {
Text('视觉 AI 统一接入').fontSize(23).fontWeight(FontWeight.Bold).width('100%')
Row({ space: 6 }) {
Button('OCR').enabled(!this.busy).onClick(() => { this.launch(() => this.prepare('OCR', 'ocr.png')); })
Button('分割').enabled(!this.busy).onClick(() => { this.launch(() => this.prepare('分割', 'coffee.png')); })
Button('目标').enabled(!this.busy).onClick(() => { this.launch(() => this.prepare('目标', 'cat.png')); })
Button('超分').enabled(!this.busy).onClick(() => { this.launch(() => this.prepare('超分', 'low.jpg')); })
}
Row({ space: 8 }) {
Image(this.input).width('48%').height(200).objectFit(ImageFit.Contain)
if (this.output) { Image(this.output).width('48%').height(200).objectFit(ImageFit.Contain).backgroundColor('#DFE8F0') }
}
Row({ space: 8 }) {
Button('选择图片').enabled(!this.busy).onClick(() => { this.launch(() => this.choose()); })
Button('开始处理').enabled(!this.busy).onClick(() => { this.launch(() => this.run()); })
Button('取消结果').enabled(this.processing).onClick(() => { this.task.cancel(); this.status = this.task.state; })
}
Text(this.status).fontSize(15).width('100%')
if (this.errorMessage) { Text(this.errorMessage).fontSize(14).width('100%') }
Scroll() { Text(this.detail).fontSize(14).width('100%') }.layoutWeight(1)
}.width('100%').height('100%').padding(16).backgroundColor('#F1F4F9')
}
}
更多推荐



所有评论(0)