基于 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篇:离线图像识别模型部署与调用实战
我们将教你如何将自定义图像识别模型(如动物分类、车牌识别)部署到鸿蒙设备上,进行离线推理调用,实现模型级拓展。