AI 图像裁剪助手:智能识别主体并自动裁切图片(HarmonyOS 5.0.0+)

基于 HarmonyOS 5.0.0 或以上版本

裁图,不该只是手动拖框。
你是否想自动裁出“人像区域”“产品主体”“黑板内容”?
这篇文章将教你构建一个 AI 智能裁图助手

✅ 自动识别图片中最重要的目标区域
✅ 根据坐标裁剪图片输出新图
✅ 全程本地运行,无需联网
✅ 可拓展用于人像提取、商品图剪裁、照片构图优化等


✅ 核心模块(HarmonyOS 5+)

能力模块是否支持
图像主体检测(Saliency)@ohos.ai.cv.saliency✅ 是
图片读取与写入@ohos.file.fs✅ 是
图片裁剪处理@ohos.image.image(可选)✅ 是

🎯 效果目标

  • 用户选择图片

  • 系统识别最主要的区域(人/物体)

  • 自动计算裁剪区域 → 输出新图片

  • UI 中展示前后对比效果


📦 Step1:加载图像显著性识别模块

import saliency from '@ohos.ai.cv.saliency'

let saliencyDetector: saliency.SaliencyDetector

async function initSaliency() {
  saliencyDetector = await saliency.createSaliencyDetector()
}

📦 Step2:检测图片显著区域

async function getCropRegion(path: string): Promise<saliency.BoundingBox> {
  const result = await saliencyDetector.detectSalientObject(path)
  return result.boundingBox
}

返回格式示例:

{
  x: 60,
  y: 120,
  width: 320,
  height: 420
}

📦 Step3:执行裁剪(使用图像模块)

import image from '@ohos.image.image'

async function cropImage(srcPath: string, box: saliency.BoundingBox, destPath: string) {
  const sourceImage = await image.createImagePacker().readImage(srcPath)
  const cropped = await sourceImage.crop(box.x, box.y, box.width, box.height)
  await cropped.writeToFile(destPath)
}

📦 Step4:UI 组件展示前后对比图

@Entry
@Component
struct CropDemo {
  @State originalPath: string = '/data/media/sample.jpg'
  @State croppedPath: string = ''
  @State loading: boolean = false

  async aboutToAppear() {
    await initSaliency()
    this.loading = true

    const box = await getCropRegion(this.originalPath)
    const outPath = `/data/user/cropped_${Date.now()}.jpg`
    await cropImage(this.originalPath, box, outPath)

    this.croppedPath = outPath
    this.loading = false
  }

  build() {
    Column({ space: 16 }) {
      Text('原图').fontSize(18)
      Image(this.originalPath).width('100%').height(240).objectFit(ImageFit.Contain)

      Text('裁剪后').fontSize(18)
      If(this.loading, () => Text('裁剪中...'))
      If(!this.loading && this.croppedPath, () =>
        Image(this.croppedPath).width('100%').height(240).objectFit(ImageFit.Contain)
      )
    }
    .padding(20)
  }
}

✅ 拓展能力建议

场景拓展方向
自动头像裁剪基于人脸检测或显著区域 → 裁出正方形人脸图
商品图裁剪优化拍照上传前自动裁剪商品主体区域
PPT/板书识别裁图结合 OCR → 自动框选文字区域裁剪
多目标批量裁剪调用 detectMultipleSalientObjects() 方法

⚠️ 注意事项(HarmonyOS 5+)

  • 图片建议大小 ≤ 1080px 宽,保证识别准确与效率

  • 输出路径必须具有写权限,建议写入 /data/user

  • 某些低对比度图像可能检测不到主体(返回空框)

  • 建议对裁剪区域做边界容错处理,防止裁剪出错


🧩 小结

你已实现鸿蒙下完整的AI 智能裁图系统

  • 加载图像显著性检测模型

  • 检测图片中的“重要区域”

  • 使用图像模块裁剪该区域

  • 展示裁前裁后的对比结果

这让你构建拍照上传优化、商品图自动修剪、用户上传头像裁剪等功能成为可能。


📘 下一篇预告

第8篇:离线图像识别模型部署与调用实战

我们将教你如何将自定义图像识别模型(如动物分类、车牌识别)部署到鸿蒙设备上,进行离线推理调用,实现模型级拓展。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值