从零跑通 HarmonyOS 图像超分:我的完整实践过程(附源码与踩坑记录)

写在前面:这是「共创稿事节」图像超分系列的第二篇。上一篇聊了接到选题时的思考,这篇全部是动手——环境准备、代码接入、一个一个填坑,直到 Demo 真正跑起来。代码以华为官方开发指南的 Index.ets 示例为骨架,中间的工程化处理(单例、压缩、加载态)是我按社区实践补的。没实测的数据我都标了出来。

一、动手前先确认三件事,少走一半弯路

写代码之前,我先花半小时把边界条件摸清楚。这三件事没确认,后面全是坑。

1. 版本与模型。 图像超分从 API 26(HarmonyOS 7)开始提供,compileSdkVersion 得≥对应版本,运行设备也得跟上。ImageSRAnalyzer.create()、process()、destroy() 这一套都是从 26.0.0 起才有。

2. 运行模型。 这套能力只在 Stage 模型下可用,系统能力是 SystemCapability.AI.Vision.VisionBase。用传统 FA 模型的老工程直接调会失败,这点要先看清楚。

3. "4 倍"的真实含义。 这是我踩的第一个认知坑。官方文档口径是:超分处理后像素总量放大四倍。换算成宽高,是在保持比例的前提下,宽高各约为原来的 2 倍——比如 512×512 的输入,像素数 262144,4 倍后是 1048576,对应 1024×1024,而不是 2048×2048。

社区里有篇文章标题问"4439×2959 的原图,为什么生成了 6400×4264?“,算下来正是这个逻辑:像素总量约 4 倍、宽高各约 2 倍(具体数值还受设备能力影响,以真机为准)。所以看到"4 倍"千万别理解成"宽高各乘 4”,那会让你选图、布局的时候全算错。

二、环境准备

  • DevEco Studio(匹配 API 26 的版本)
  • 一台 HarmonyOS 7 / API 26 及以上的真机或 simulator(超分依赖 NPU,真机效果最准)
  • 一张低分辨率测试图,用来直观对比前后效果

新建 Empty Ability 工程,语言选 ArkTS,模型选 Stage。准备就绪,开始写代码。

三、第一步:把需要的类引进来

import { imageSuperResolution, visionBase } from '@kit.CoreVisionKit'
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';

imageSuperResolution 是主角,提供分析器;visionBase 提供构造请求需要的 ImageData、Request 类型。这几个 import 一个都不能少。

四、第二步:分析器的生命周期——create 与 destroy 必须成对

这是整个接入里最关键的一段,也是我见过最多人漏掉的地方。

private analyzer: imageSuperResolution.ImageSRAnalyzer | null = null;

async aboutToAppear(): Promise<void> {
  this.analyzer = await imageSuperResolution.ImageSRAnalyzer.create();
  hilog.info(0x0000, 'ImageSRSample', 'ImageSRAnalyzer created');
}

async aboutToDisappear(): Promise<void> {
  if (this.analyzer) {
    await this.analyzer.destroy();
    hilog.info(0x0000, 'ImageSRSample', 'ImageSRAnalyzer released successfully');
  }
}

为什么要在 aboutToAppear 里 create()、在 aboutToDisappear 里 destroy()?

因为分析器实例占用的是 NPU 这类硬件资源。创建一次、全局复用、页面销毁时释放,是最稳的写法。如果每次点按钮都 create() 一次却不 destroy(),反复进出页面,内存会一路涨,最后被系统杀掉。社区里"内存持续涨"的坑,八成就是漏了这对组合。

我的建议是把它做成页面级单例:一个页面只 create 一次,所有图片共用,离开页面再 destroy。

五、第三步:选图并解码成 PixelMap

超分接口的输入是 PixelMap,不是文件路径。所以得先拉起图库选图,再把 URI 转成 PixelMap。

界面上放两个按钮:

Button('选择图片')
  .type(ButtonType.Capsule)
  .fontColor(Color.White)
  .alignSelf(ItemAlign.Center)
  .width('80%')
  .margin(10)
  .onClick(() => {
    void this.selectImage();
  })

选图与解码的实现:

private async selectImage() {
  let uri = await this.openPhoto();
  if (!uri) {
    hilog.error(0x0000, 'ImageSRSample', 'Failed to get uri.');
    return;
  }
  this.loadImage(uri);
}

private async openPhoto(): Promise<string> {
  return new Promise<string>((resolve) => {
    let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
    photoPicker.select({
      MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
      maxSelectNumber: 1
    }).then(res => {
      resolve(res.photoUris[0]);
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'ImageSRSample',
        `Failed to get photo image uri.code: ${err.code}, message: ${err.message}`);
      resolve('');
    });
  });
}

private loadImage(name: string) {
  setTimeout(async () => {
    let imageSource: image.ImageSource | undefined = undefined;
    let fileSource = await fileIo.open(name, fileIo.OpenMode.READ_ONLY);
    imageSource = image.createImageSource(fileSource.fd);
    this.inputImage = await imageSource.createPixelMap();
    this.dataValues = '';
    this.outputImage = undefined;
    await fileIo.close(fileSource);
  }, 100);
}

这里有个小细节:loadImage 里用了 setTimeout(..., 100)。这是官方示例的写法,目的是把解码挪到下一个事件循环,避免和图库返回的时序冲突。另外记得每次换图时把 outputImage 清空,否则用户会误以为新图已经处理过了。

六、第四步:构造 Request,调用 process

核心调用就这么几行:

Button('图像超分')
  .type(ButtonType.Capsule)
  .fontColor(Color.White)
  .alignSelf(ItemAlign.Center)
  .width('80%')
  .margin(10)
  .onClick(() => {
    if (!this.inputImage || !this.analyzer) {
      hilog.error(0x0000, 'ImageSRSample', 'Failed to process image super resolution.');
      return;
    }
    let imageData: visionBase.ImageData = {
      pixelMap: this.inputImage
    }
    let request: visionBase.Request = {
      inputData: imageData
    };
    this.analyzer.process(request)
      .then((response: imageSuperResolution.ISPResponse) => {
        hilog.info(0x0000, 'ImageSRSample', 'Super resolution completed');
        this.outputImage = response.pixelMap;
      })
      .catch((error: BusinessError) => {
        hilog.error(0x0000, 'ImageSRSample',
          `Image super resolution failed. Code: ${error.code}, message: ${error.message}`);
        this.dataValues = `Error: ${error.message}`;
      });
  })

链路很长,但结构很干净:

PixelMap → ImageData{pixelMap} → Request{inputData} → analyzer.process() → ISPResponse.pixelMap

process() 返回的是 Promise<ISPResponse>,结果图就在 response.pixelMap 里,直接丢给 Image 组件显示即可。catch 一定不能省——图片格式不支持、NPU 资源被占、内存不足,都会走到这里。

七、第五步:完整页面代码

把上面几段拼起来,就是一个能跑的完整页面(在官方示例基础上补了 outputImage 清空逻辑):

import { imageSuperResolution, visionBase } from '@kit.CoreVisionKit'
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';

@Entry
@Component
struct Index {
  @State inputImage: PixelMap | undefined = undefined;
  @State outputImage: PixelMap | undefined = undefined;
  @State dataValues: string = '';
  private analyzer: imageSuperResolution.ImageSRAnalyzer | null = null;

  async aboutToAppear(): Promise<void> {
    this.analyzer = await imageSuperResolution.ImageSRAnalyzer.create();
    hilog.info(0x0000, 'ImageSRSample', 'ImageSRAnalyzer created');
  }

  async aboutToDisappear(): Promise<void> {
    if (this.analyzer) {
      await this.analyzer.destroy();
      hilog.info(0x0000, 'ImageSRSample', 'ImageSRAnalyzer released successfully');
    }
  }

  build() {
    Column() {
      Text('Input Image').fontSize(16).margin(5)
      Image(this.inputImage).objectFit(ImageFit.Fill).height('25%')
      Text('Output Image').fontSize(16).margin(5)
      Image(this.outputImage).objectFit(ImageFit.Fill).height('25%')
      Text(this.dataValues)
        .copyOption(CopyOptions.LocalDevice)
        .height('10%').margin(10).width('60%')

      Button('选择图片').type(ButtonType.Capsule).fontColor(Color.White)
        .alignSelf(ItemAlign.Center).width('80%').margin(10)
        .onClick(() => { void this.selectImage(); })

      Button('图像超分').type(ButtonType.Capsule).fontColor(Color.White)
        .alignSelf(ItemAlign.Center).width('80%').margin(10)
        .onClick(() => {
          if (!this.inputImage || !this.analyzer) {
            hilog.error(0x0000, 'ImageSRSample', 'Failed to process image super resolution.');
            return;
          }
          let imageData: visionBase.ImageData = { pixelMap: this.inputImage }
          let request: visionBase.Request = { inputData: imageData };
          this.analyzer.process(request)
            .then((response: imageSuperResolution.ISPResponse) => {
              hilog.info(0x0000, 'ImageSRSample', 'Super resolution completed');
              this.outputImage = response.pixelMap;
            })
            .catch((error: BusinessError) => {
              hilog.error(0x0000, 'ImageSRSample',
                `Image super resolution failed. Code: ${error.code}, message: ${error.message}`);
              this.dataValues = `Error: ${error.message}`;
            });
        })
    }
    .width('100%').height('100%')
    .justifyContent(FlexAlign.Center)
  }

  // ... selectImage / openPhoto / loadImage 见上文
}

八、跑通之后,我填的三个坑

官方 Demo 能跑,但离"能用"还有距离。下面是我在工程化时补的三处。

坑一:大图直接喂进去会失败。 社区实践普遍提到输入有尺寸上限(常见说法是 2048×2048),相册原图动辄四五千像素,必须先等比压缩。我加了一个压缩函数:

async compressToMax(src: image.PixelMap, maxSize: number): Promise<image.PixelMap> {
  const info = await src.getImageInfo();
  if (info.size.height <= maxSize && info.size.width <= maxSize) {
    return src;
  }
  const ratio = maxSize / Math.max(info.size.width, info.size.height);
  return src.scale(ratio, ratio);
}

说明:这个 2048 上限来自社区实践文章,官方 API 文档未在此页面明确给出,具体阈值请以你使用的 API 版本和真机表现为准。

坑二:处理不是瞬时的,得给用户反馈。 process() 是异步的,中端机型上处理一张图可能需要 1~2 秒(社区实测口径,未做本地复测)。不加 loading,用户会以为卡死了。我的做法是点按钮后先显示"处理中…",then 里再收敛状态。

坑三:别在滚动列表里批量超分。 process() 每次只吃一张图,NPU 资源有限。信息流里每条都自动超分,一定会扛不住。正确姿势是用户主动触发——点开放大、点"保存高清图"时才跑。

九、怎么确认真的超分了

光看"图变大"不算数,因为插值也能放大。我用两个办法验证:

  1. 看尺寸:用 getImageInfo() 打印输入输出的宽高,确认像素总量约 4 倍关系。
  2. 看细节:找一张有明显纹理(头发丝、织物、文字边缘)的低清图,放大前后对比边缘是否更干净。

这两步做完,基本能确认能力生效。至于耗时、画质提升的量化数据,我在这里诚实地说:没有在目标真机上做完整测量,不给出具体数字,留给第三篇"探索"里作为后续方向。

小结

从环境准备到跑通 Demo,整条链路可以浓缩成四步:

  1. 引依赖——@kit.CoreVisionKit 一把梭;
  2. 管生命周期——create() 单例复用,destroy() 成对释放;
  3. 备输入——选图、解码、超限先压缩,转成 PixelMap;
  4. 调接口——构造 Request 调 process(),结果从 ISPResponse.pixelMap 取。

真正决定能不能上线的,是官方示例之外那几个工程化细节:单例、压缩、loading、异常兜底。把这些补齐,一个能用的图像超分功能就算落地了。

下一篇,我会聊跑通之后往下探索的部分:性能怎么优化、还能落到哪些场景、端侧和云端到底怎么选。


本文技术内容依据:

  • 华为开发者官网《图像超分》开发指南(官方 Index.ets 示例与开发步骤)
  • Core Vision Kit imageSuperResolution API 参考
  • 社区实践文章(尺寸上限、耗时、批量处理等,均已标注"社区口径")

文中标注"社区口径""需以真机为准"的数据未做本地实测,请以实际设备验证为准。

#鸿蒙 #HarmonyOS #图像超分 #CoreVisionKit #ArkTS #端侧AI #共创稿事节

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐