万少 · 万绍业 技术 · 创造 · 价值

鸿蒙开发技巧 鸿蒙7图像超分做老照片修复

鸿蒙7图像超分做老照片修复

你翻出一张十年前的照片,传到平板上一放大,全是马赛克 —— 相册里没有"变清晰"这个按钮。

你翻出一张十年前的照片,传到平板上一放大,全是马赛克 —— 相册里没有"变清晰"这个按钮。

你把一张聊天截图发给同事,对方说字太小看不清 —— 截图本身只有 500 多像素宽。

你想在自己应用里把这两张图救回来 —— 自己接一个超分模型,光权重就几十兆,还得管下载和推理耗时。

这三件事指向同一个能力:端侧图像超分辨率重建。从 HarmonyOS 7(API 26)开始,华为把它做进了 Core Vision Kit,三个方法就能调用,模型由系统持有,应用不打包权重、不联网、不要权限。

官方文档站「图像超分」指南页的适用场景段写的是"从26.0.0版本开始,新增支持对输入的低分辨率图像进行超分辨率重建,使图像更加清晰。适用于提升图片质量、修复老照片等场景"。左侧目录里,它和人脸检测、多目标识别、骨骼点检测同属 Core Vision Kit:

官方文档站「图像超分」指南页:适用场景段写明从 26.0.0 版本开始支持低分辨率图像超分重建、适用于修复老照片等场景,更新时间 2026-09-07

下面这个 demo 叫「老照片修复」:选图、超分、前后对比、存回相册。已经在真机上跑通,文中的截图和耗时数据都是实测的。

首页只有三块内容:一张预览卡、三个内置样张、两个按钮。没有任何图标,全是文字。

应用首页


先确认你的设备能不能用

这是整篇文章里最该先看的一段。这个能力的门槛不在代码,在设备。

条件 要求 来源
系统版本 HarmonyOS 7 / API 26,接口起始版本 26.0.0 官方 API 参考
设备类型 Phone、Tablet、PC/2in1 官方约束与限制
地区 仅中国境内(香港特别行政区、澳门特别行政区、中国台湾除外) 官方约束与限制
模拟器 不支持,本 Kit 暂不支持模拟器 官方约束与限制
模型下载 不需要,端侧系统 AI 直接提供 官方接口说明
权限 不需要定位、存储等权限声明 实测

简单说:手里没有 HarmonyOS 7 真机,这个功能就只能停在读文档阶段。官方在 Core Vision Kit 的约束页最后一行写的就是"本 Kit 暂不支持模拟器"。

本文的实测设备是一台 HUAWEI MRDI-W00 平板,HarmonyOS 7.0.0.109,分辨率 2800 x 1840,USB 连接。


先看效果和数据

官方对效果的描述只有一句:提高图像质量的同时,像素同步放大四倍。四倍是固定的,没有 2 倍 3 倍可选。

内置样张 1,400 x 500 的人像:

修复结果前后对比

上面这张图里,上半是原图 400 x 500,下半是超分后的 1600 x 2000,两张都按同样的显示宽度铺满,所以放大后细节差异是真实可见的 —— 发丝的过渡、皮肤噪点、下颌边缘的锯齿,处理后都明显收敛。

结果页支持三态切换,单独看修复后:

修复后单图

单独看原图:

原图单图

第二种输入更有意思。我从相册里选了一张低清的应用截图,505 x 768,画面里全是小字。放大到 2020 x 3072 之后,我在结果页上逐个核对了那些小字,文字边缘的重建比上面人像的皮肤纹理更好认。这条线索指向一个更实用的场景:低清截图做 OCR 之前先超分一遍。

(这张输入涉及我自己的界面和文件,截图就不放了,只保留尺寸和耗时数据。)

实测数据汇总:

输入 输入尺寸 输出尺寸 耗时 结果
内置样张 1 400 x 500 1600 x 2000 2165 ms 成功
内置样张 3 400 x 300 1600 x 1200 1467 ms 成功
相册截图 505 x 768 2020 x 3072 4499 ms 成功
相册截图(未降采样) 673 x 1024 — 约 5 s 服务超时失败

最后一行是踩出来的。官方约束写的是 16px < 边长 < 2048px,建议 1024 x 1024 以下,我就按 1024 做了上限,结果同一张图直接失败,日志里是:

AI_ISP_PUBLIC: NapiISPRunModelExec timeout or failed.

服务侧的超时是 5 秒量级,模型推理没跑完就被掐了。把输入统一压到 768 以内之后,同一张图稳定成功。所以那句"建议 1024 以下"不是性能优化建议,是硬边界,别踩。

耗时随像素量涨得很快:400 x 500 用 2 秒,505 x 768 用 4.5 秒。像素量翻一倍多,耗时也翻一倍多,基本线性。所以处理时必须给用户一个等待状态:

处理中的等待态:原来放「开始修复」按钮的位置换成一行转圈提示,输入是内置样张 1

实现就是把那个按钮整个替换掉,busy 期间用户点不到第二次,也顺带挡住了并发调用:

// pages/HomePage.ets
if (this.store.isBusy()) {
  Row({ space: 10 }) {
    LoadingProgress()
      .width(22)
      .height(22)
      .color($r('app.color.accent'))
    Text(this.store.phase === RestorePhase.PROCESSING ? '超分处理中,请稍候' : '图片解码中')
      .fontSize(14)
      .fontColor($r('app.color.secondary_text'))
  }
  .width('100%')
} else {
  Button('开始修复')
    .width('100%')
    .height(46)
    .backgroundColor($r('app.color.accent'))
    .enabled(this.store.source !== undefined)
    .onClick(() => {
      this.restore();
    })
}

接口只有三个方法

这是这个能力最舒服的地方。整个 imageSuperResolution 命名空间对外就一个类,类上三个方法,没有配置项、没有回调注册、没有初始化参数。

import { imageSuperResolution, visionBase } from '@kit.CoreVisionKit';

// 1. 创建
const analyzer = await imageSuperResolution.ImageSRAnalyzer.create();

// 2. 处理
const imageData: visionBase.ImageData = { pixelMap: inputPixelMap };
const request: visionBase.Request = { inputData: imageData };
const response: imageSuperResolution.ISPResponse = await analyzer.process(request);
const outputPixelMap = response.pixelMap;

// 3. 释放
await analyzer.destroy();

visionBase.Request 还有 scene 和 requestId 两个字段,SDK 注释里明确标了"预留,当前版本不支持",传了也不生效,不用管。

官方文档的开发步骤到这儿就结束了,剩下的都是工程问题。下面按我这个 demo 的真实代码顺序讲。


工程结构

entry/src/main/ets/
├── model/RestoreStore.ets          状态容器(@ObservedV2 + @Trace)
├── service/SuperResolutionService.ets  超分封装:analyzer 生命周期 + 尺寸校验
├── service/PhotoLoader.ets         取图与存图:rawfile / 相册 URI / 降采样 / 免权限保存
├── components/InfoRow.ets          一行"标签 + 值",为了绕开 V2 @Builder 的刷新问题
└── pages/
    ├── Index.ets                   Navigation 根容器 + @Provider
    ├── HomePage.ets                选图、预览、开始修复
    ├── ResultPage.ets              前后对比、三态切换、存相册
    └── NoticePage.ets              能力约束清单页

技术选型上有两条是固定的:状态管理用 V2,页面跳转用 Navigation。这个工程没有一处 @State / @Link,也没有 router.pushUrl。

一个 store 管住整条链路

处理阶段、输入图、输出图、尺寸、耗时、错误提示,全部收在一个 @ObservedV2 类里。@Trace 标过的字段变化才会驱动 UI 刷新,所以每个要显示的值都得单独标,不能塞进一个普通对象。

// model/RestoreStore.ets
import { image } from '@kit.ImageKit';

export enum RestorePhase {
  IDLE = 0,
  LOADING = 1,
  PROCESSING = 2,
  SUCCESS = 3,
  FAILURE = 4
}

@ObservedV2
export class RestoreStore {
  @Trace phase: RestorePhase = RestorePhase.IDLE;
  @Trace source: image.PixelMap | undefined = undefined;
  @Trace result: image.PixelMap | undefined = undefined;
  @Trace sourceName: string = '';
  @Trace sourceWidth: number = 0;
  @Trace sourceHeight: number = 0;
  @Trace resultWidth: number = 0;
  @Trace resultHeight: number = 0;
  @Trace elapsedMs: number = 0;
  @Trace notice: string = '';

  isBusy(): boolean {
    return this.phase === RestorePhase.LOADING || this.phase === RestorePhase.PROCESSING;
  }

  reset(): void {
    this.source?.release();
    this.result?.release();
    this.source = undefined;
    this.result = undefined;
    // ...其余字段清零,phase 回 IDLE
  }
}

reset() 里那两行 release() 不是可选的。超分输出是 2020 x 3072 这种量级的 PixelMap,一张的内存就是十几兆到几十兆,不主动释放,来回选几张图内存就上去了。

根容器用 Navigation,页面用 NavDestination

Index.ets 只做三件事:挂 Navigation、注册路由表、用 @Provider 把 store 和服务实例发下去。

// pages/Index.ets
import { AppStorageV2 } from '@kit.ArkUI';

@Entry
@ComponentV2
struct Index {
  @Provider('store') store: RestoreStore =
    AppStorageV2.connect(RestoreStore, 'restoreStore', () => new RestoreStore())!;
  @Provider('service') service: SuperResolutionService = new SuperResolutionService();
  @Provider('pathStack') pathStack: NavPathStack = new NavPathStack();

  @Builder
  pageMap(name: string) {
    if (name === 'result') {
      ResultPage()
    } else if (name === 'notice') {
      NoticePage()
    }
  }

  aboutToDisappear(): void {
    this.service.release();
    this.store.reset();
  }

  build() {
    Navigation(this.pathStack) {
      HomePage()
    }
    .navDestination(this.pageMap)
    .mode(NavigationMode.Stack)
    .title('老照片修复')
    .width('100%')
    .height('100%')
  }
}

两个细节值得说。

AppStorageV2.connect 而不是直接 new。这样页面被系统回收重建时,已经处理好的 PixelMap 还在,用户从结果页返回不会看到空白。

aboutToDisappear 里同时释放 analyzer 和 PixelMap。官方文档就是建议 create() 放 aboutToAppear、destroy() 放 aboutToDisappear,成对出现。

跳转只有一行:

this.pathStack.pushPath({ name: 'result' });
this.pathStack.pushPath({ name: 'notice' });

ResultPage / NoticePage 内部把根节点包在 NavDestination 里,标题和返回行为挂在它上面:

@ComponentV2
export struct ResultPage {
  @Consumer('store') store: RestoreStore = new RestoreStore();
  @Consumer('pathStack') pathStack: NavPathStack = new NavPathStack();
  @Local viewMode: number = 0;

  build() {
    NavDestination() {
      // ...内容
    }
    .title('修复结果')
    .onBackPressed(() => {
      this.pathStack.pop();
      return true;
    })
  }
}

analyzer 要复用,不要每张图都 create

官方示例是页面级 aboutToAppear 创建一次。工程里我把它包进一个服务类,第一次用时创建,之后复用,退出时统一销毁:

// service/SuperResolutionService.ets
import { imageSuperResolution, visionBase } from '@kit.CoreVisionKit';
import { image } from '@kit.ImageKit';

const MIN_EDGE: number = 16;
const MAX_EDGE: number = 768;   // 官方建议 1024,实测 1024 会超时,见前文

export class SizeUtil {
  static fits(pixelMap: image.PixelMap): boolean {
    const info = pixelMap.getImageInfoSync();
    return Math.max(info.size.width, info.size.height) <= MAX_EDGE
      && Math.min(info.size.width, info.size.height) > MIN_EDGE;
  }
}

export class SuperResolutionService {
  private analyzer: imageSuperResolution.ImageSRAnalyzer | undefined = undefined;

  async prepare(): Promise<void> {
    if (this.analyzer === undefined) {
      this.analyzer = await imageSuperResolution.ImageSRAnalyzer.create();
    }
  }

  async restore(pixelMap: image.PixelMap): Promise<image.PixelMap> {
    await this.prepare();
    const analyzer = this.analyzer;
    if (analyzer === undefined) {
      throw new Error('analyzer unavailable');
    }
    const imageData: visionBase.ImageData = { pixelMap: pixelMap };
    const request: visionBase.Request = { inputData: imageData };
    const response = await analyzer.process(request);
    return response.pixelMap;
  }

  async release(): Promise<void> {
    if (this.analyzer !== undefined) {
      await this.analyzer.destroy();
      this.analyzer = undefined;
    }
  }
}

注意 SizeUtil.fits 这个校验。process() 对超范围输入不会给你一个"参数非法"的清晰错误,而是走服务异常,用户看到的是一句看不懂的超时。在调用前挡掉,比在 catch 里解释划算得多。

还有一条:visionBase.Request 的 inputData 类型是 ImageData | ImageData[],看着像支持批量。实际不行 —— API 参考里明写"图片超分接口仅支持传入一张图片,不支持传入多张图片"。数组形态是 Core Vision Kit 其他能力共用的,超分这条只认单张。

输入准备:在解码阶段就压到限制以内

不要先解出全尺寸 PixelMap 再想怎么缩小。相册里的原图动辄四千万像素,全解出来内存先炸一次。用 DecodingOptions.desiredSize 让解码器直接按比例出小图:

// service/PhotoLoader.ets
private static async decode(source: image.ImageSource): Promise<image.PixelMap> {
  const info = await source.getImageInfo();
  const width = info.size.width;
  const height = info.size.height;
  const maxEdge = Math.max(width, height);
  if (maxEdge > MAX_EDGE) {
    const ratio = MAX_EDGE / maxEdge;
    const size: image.Size = {
      width: Math.round(width * ratio),
      height: Math.round(height * ratio)
    };
    const options: image.DecodingOptions = { desiredSize: size };
    return await source.createPixelMap(options);
  }
  return await source.createPixelMap();
}

图片来源有两条路,都收敛到上面这个 decode:

static async fromRawFile(context: common.Context, fileName: string): Promise<image.PixelMap> {
  const bytes: Uint8Array = await context.resourceManager.getRawFileContent(fileName);
  const source = image.createImageSource(bytes.buffer as ArrayBuffer);
  const pixelMap = await PhotoLoader.decode(source);
  await source.release();
  return pixelMap;
}

static async fromUri(uri: string): Promise<image.PixelMap> {
  const file = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  const source = image.createImageSource(file.fd);
  const pixelMap = await PhotoLoader.decode(source);
  await source.release();
  await fileIo.close(file);
  return pixelMap;
}

common.Context 这个类型别写成 common.BaseContext。BaseContext 上没有 resourceManager 和 filesDir,写错了编译直接报属性不存在。取法:

private uiContext(): common.Context {
  return this.getUIContext().getHostContext() as common.Context;
}

选图用 PhotoViewPicker,免权限,用户选哪张你才能读哪张:

static async pickFromGallery(context: common.Context): Promise<string> {
  const options = new photoAccessHelper.PhotoSelectOptions();
  options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  options.maxSelectNumber = 1;
  const picker = new photoAccessHelper.PhotoViewPicker();
  const result = await picker.select(options);
  return result.photoUris.length > 0 ? result.photoUris[0] : '';
}

内置样张是从 picsum 拉的 400 像素级灰度图(https://picsum.photos/id/<id>/400/500?grayscale)。灰度 + 低分辨率天然像老照片,又正好落在超分输入范围内,做演示素材比精修图合适。

选完图之后,预览卡会把来源和尺寸都摊开,"预期输出"直接按 4 倍算给用户看,省得他猜结果有多大:

选中内置样张后的预览卡

调用与计时

restore() 是主流程,校验、置状态、计时、跳转四步:

// pages/HomePage.ets
private async restore(): Promise<void> {
  const source = this.store.source;
  if (source === undefined) {
    this.store.notice = '请先选择一张低清图片';
    return;
  }
  if (!SizeUtil.fits(source)) {
    this.store.notice = '输入尺寸超出建议范围,请换一张图片';
    return;
  }
  this.store.phase = RestorePhase.PROCESSING;
  this.store.notice = '';
  const start = Date.now();
  try {
    const output = await this.service.restore(source);
    const info = output.getImageInfoSync();
    this.store.result = output;
    this.store.resultWidth = info.size.width;
    this.store.resultHeight = info.size.height;
    this.store.elapsedMs = Date.now() - start;
    this.store.phase = RestorePhase.SUCCESS;
    this.pathStack.pushPath({ name: 'result' });
  } catch (error) {
    const err = error as BusinessError;
    hilog.error(DOMAIN, TAG, 'restore failed: code=%{public}d message=%{public}s',
      err.code, err.message);
    this.store.phase = RestorePhase.FAILURE;
    this.store.notice = describeError(err);
  }
}

elapsedMs 是端到端时间,含解码之外的调用与等待,比纯推理耗时更贴近用户感受 —— 界面上显示的就是这个数字。

错误描述单独抽一个函数,把那个最难懂的码翻译成人话:

export function describeError(err: BusinessError): string {
  if (err.code === 1018700001) {
    return '超分服务异常(1018700001),请确认设备支持 Core Vision Kit 且未被并发调用';
  }
  return `调用失败 code=${err.code}, message=${err.message}`;
}

结果页三态

一个 @Local viewMode 切"对比 / 修复后 / 原图"。对比态上下两张图都用同样显示宽度,差异一眼能看出来:

@Local viewMode: number = 0;

// build() 内,模式切换按钮见后文 modeButton
if (this.viewMode === 0) {
  Text(`原图 ${SizeUtil.describe(this.store.sourceWidth, this.store.sourceHeight)}`)
  Image(this.store.source).width('100%').height(200).objectFit(ImageFit.Contain)
  Text(`修复后 ${SizeUtil.describe(this.store.resultWidth, this.store.resultHeight)}`)
  Image(this.store.result).width('100%').height(200).objectFit(ImageFit.Contain)
} else if (this.viewMode === 1) {
  Image(this.store.result).width('100%').height(360).objectFit(ImageFit.Contain)
} else {
  Image(this.store.source).width('100%').height(360).objectFit(ImageFit.Contain)
}

另一张样张的结果页

免权限存回相册

写系统相册 traditionally 要申请权限,现在用 showAssetsCreationDialog 可以免权限:先把超分结果编码落到应用沙箱,再拉起系统弹窗让用户确认,确认后拿到目标 URI 写进去。

static async saveToAlbum(context: common.Context, pixelMap: image.PixelMap,
  fileName: string): Promise<boolean> {
  const packer = image.createImagePacker();
  const packingOption: image.PackingOption = { format: 'image/jpeg', quality: 100 };
  const bytes: ArrayBuffer = await packer.packToData(pixelMap, packingOption);
  await packer.release();

  const sandboxPath = `${context.filesDir}/${fileName}.jpg`;
  const tmpFile = await fileIo.open(sandboxPath,
    fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.TRUNC);
  await fileIo.write(tmpFile.fd, bytes);
  await fileIo.close(tmpFile);

  const helper = photoAccessHelper.getPhotoAccessHelper(context);
  const config: photoAccessHelper.PhotoCreationConfig = {
    title: fileName,
    fileNameExtension: 'jpg',
    photoType: photoAccessHelper.PhotoType.IMAGE,
    subtype: photoAccessHelper.PhotoSubtype.DEFAULT
  };
  const destUris = await helper.showAssetsCreationDialog(
    [fileUri.getUriFromPath(sandboxPath)], [config]);
  if (destUris.length === 0) {
    return false;   // 用户点了"禁止"
  }
  const destFile = await fileIo.open(destUris[0], fileIo.OpenMode.READ_WRITE);
  await fileIo.write(destFile.fd, bytes);
  await fileIo.close(destFile);
  await fileIo.unlink(sandboxPath);
  return true;
}

系统弹窗长这样,预览图就是即将写入的那张 1600 x 2000:

保存到相册的系统授权弹窗

保存成功提示

V2 的 @Builder 不刷新,改成子组件

这个坑花的时间最多,也最值得单独记。

首页选完图之后,预览图换了,但下面"来源 / 输入尺寸 / 预期输出"三行还停在上一张图的值。最初的写法是这样(工程里现在已经改掉):

// 错误写法
@Builder
metaRow(label: string, value: string) {
  Row() {
    Text(label)
    Blank()
    Text(value)
  }
}

this.metaRow('输入尺寸', SizeUtil.describe(this.store.sourceWidth, this.store.sourceHeight))

Image(this.store.source) 正常更新,因为它是直接把 @Trace 字段绑给组件属性。metaRow 不更新,因为传进去的第二个参数是一个表达式,V2 的 @Builder 只在构建时对它求值一次,之后 @Trace 变了也不会重新求值。

改成子组件,用 @Param 接收,问题消失:

// components/InfoRow.ets
@ComponentV2
export struct InfoRow {
  @Param label: string = '';
  @Param value: string = '';
  @Param valueColor: ResourceColor = $r('app.color.primary_text');

  build() {
    Row() {
      Text(this.label).fontSize(14).fontColor($r('app.color.secondary_text'))
      Blank()
      Text(this.value).fontSize(14).fontWeight(FontWeight.Medium).fontColor(this.valueColor)
    }
    .width('100%')
  }
}
InfoRow({ label: '来源', value: this.store.sourceName })
InfoRow({ label: '输入尺寸',
  value: SizeUtil.describe(this.store.sourceWidth, this.store.sourceHeight) })

规则可以记成一句:V2 的 @Builder 参数表达式只在构建时求值一次,不要把状态值当参数传进去。

对照结果页的三个模式按钮,它们用的是同一个 @Builder,却工作正常:

@Builder
modeButton(label: string, mode: number) {
  Button(label)
    .backgroundColor(this.viewMode === mode ? $r('app.color.accent') : $r('app.color.page_background'))
    .fontColor(this.viewMode === mode ? Color.White : $r('app.color.primary_text'))
    .onClick(() => {
      this.viewMode = mode;
    })
}

Row({ space: 10 }) {
  this.modeButton('对比', 0)
  this.modeButton('修复后', 1)
  this.modeButton('原图', 2)
}

差别在于传进去的 '对比'、0 都是编译期常量,真正会变的状态 this.viewMode 是在 Builder 函数体内部直接读的。这种写法刷新没问题,点一下高亮立刻跟着换。

出问题的写法是把状态值算好再当参数传:

this.metaRow('输入尺寸', SizeUtil.describe(this.store.sourceWidth, this.store.sourceHeight))

所以口径更准确的说法是:Builder 体内读状态会建立依赖,Builder 的参数不会。 参数本身确实是动态值时(像这个"标签 + 值"两列布局,首页和结果页都要用),就别用 Builder,换成子组件 + @Param。


把约束写进应用里

约束这么多,用户记不住,开发者也容易忘。我在首页底部放了个「能力约束与限制」入口,点进去是一个 NavDestination 页面,十条清单直接列出来:

能力约束页

const LIMITS: string[] = [
  '接口起始版本 26.0.0,仅 Stage 模型,需 HarmonyOS 7 真机或对应版本设备',
  'Core Vision Kit 不支持模拟器:模拟器无 NPU,AI 推理无法执行',
  '输入约束:16px < 边长 < 2048px,官方建议不超过 1024 x 1024,否则可能处理超时',
  '输出固定放大 4 倍,没有 2 倍 / 3 倍可选参数',
  '一次仅支持一张图片,不支持多张图片批量输入',
  'scene、requestId 为预留字段,当前版本不生效',
  '同一进程重复调用会返回系统繁忙,需串行使用',
  '能力仅在中国境内可用(港澳台除外),海外设备调用会失败',
  '开发者无需自行下载或加载模型,端侧系统 AI 直接提供能力',
  '错误码 1018700001 表示服务异常'
];

这类页面在演示和排障时都省事:现场有人问"为什么我这台跑不了",让他打开这一页对着看就行。


完整 API 描述

归属与版本

项 值
Kit Core Vision Kit(基础视觉服务)
导入模块 @kit.CoreVisionKit
命名空间 imageSuperResolution(底层实现 @hms.ai.vision.imageSuperResolution)
系统能力 SystemCapability.AI.Vision.VisionBase
模型约束 仅 Stage 模型
接口起始版本 26.0.0(visionBase 基类自 5.0.0(12) 起提供)
支持设备 phone / tablet / 2in1,均自 26.0.0 起
并发 不支持同一用户并发调用同一特性,重复调用返回系统繁忙
地区 仅中国境内(港澳台除外)
模拟器 不支持

类与方法

成员 签名 说明
ImageSRAnalyzer class ImageSRAnalyzer extends visionBase.Analyzer 超分分析器;构造函数为 private,不能 new
create static create(): Promise<ImageSRAnalyzer> 创建分析器实例
process process(request: visionBase.Request): Promise<ISPResponse> 执行超分,仅接受一张图
destroy destroy(): Promise<void> 释放分析器(继承自 visionBase.Analyzer)
ISPResponse class ISPResponse extends visionBase.Response 处理结果
ISPResponse.pixelMap image.PixelMap 超分后的图,像素同步放大 4 倍

入参结构

类型 字段 必填 说明
visionBase.Request inputData 是 ImageData | ImageData[],超分只认单张
scene 否 SceneMode.FOREGROUND(1) / BACKGROUND(2),预留字段,当前版本不生效
requestId 否 请求追踪 ID,预留字段,当前版本不生效
visionBase.ImageData pixelMap 是 待处理的 image.PixelMap

错误码

错误码 官方描述 触发说明
1018700001 Service exception 官方只给了这一个码,所有服务侧异常都归到它。实测输入尺寸过大导致推理超时也落在这里,日志是 NapiISPRunModelExec timeout or failed.

超时这一条要特别说明:它不会给你一个专门的"超时"码,仍然落在 1018700001 里,只能从 message 判断。所以尺寸校验必须前置,别指望 catch 里区分。

官方确认 vs 实测补充

结论 依据
输入 16px < 边长 < 2048px,高宽比无特殊要求 官方约束与限制
建议 1024 x 1024 以下 官方约束与限制
输出固定 4 倍 官方 ISPResponse.pixelMap 说明
仅单张输入 官方 process 参数说明
不支持并发、不支持模拟器、仅境内可用 官方约束与限制
实际安全上限约 768px,1024 级别会超时 实测补充
400 x 500 约 2.2 s,505 x 768 约 4.5 s,与像素量近似线性 实测补充
输出 PixelMap 要主动 release(),换图前释放旧图 工程实践补充

还能往哪些场景走

老照片修复只是最容易演示的一个。这个能力的通用价值在于:把任何"来源不可控的低清图"变成"可读、可看、可再处理"的图。

  • OCR 前置增强。 低清截图、扫描件、拍糊的证件,先超分再喂给 textRecognition,两者同属 Core Vision Kit,接入成本几乎为零。前面那次 505 x 768 应用截图的实测已经说明趋势:小字边缘确实被重建得更干净。
  • 相册批量整理。 用户导入的老图、微信压缩过的图,做一次批量重建。注意串行调用,做成队列,别并发。
  • 商品图救急。 商家上传的主图分辨率不足,直接放大到 4 倍再套模板出图。
  • 大屏适配。 平板和 2in1 上,历史资源按 1 倍图铺满会糊,超分一次比重新切图省事。
  • 视频关键帧增强。 单帧走超分可行,但一次一张、不支持并发、还有超时风险,做实时不现实,离线逐帧处理要控输入尺寸。

官方文档

留言讨论

正在加载评论…