HarmonyOS NEXT AI基础视觉服务-背景替换

简介: 这是一个基于AI基础视觉服务的背景替换案例,通过调用设备相册选择图片并智能分割主体,支持动态更换背景颜色。主要步骤包括:1) 导入模块与定义组件;2) 实现图片选择与格式转换;3) 使用`subjectSegmentation.doSegmentation`接口完成主体分割;4) 通过随机RGB值实现背景色动态更换。代码结构清晰,功能完整,适合学习AI图像处理技术。

案例描述

这是一个基于AI基础视觉服务实现的背景替换案例,通过调用设备相册选择图片后对主体进行智能分割,并支持动态更换背景颜色。

在这里插入图片描述

实现步骤:

1. 模块导入与组件定义

import {
    photoAccessHelper } from '@kit.MediaLibraryKit'
import {
    fileIo } from '@kit.CoreFileKit'
import image from '@ohos.multimedia.image'
import {
    subjectSegmentation } from '@kit.CoreVisionKit'
import {
    promptAction } from '@kit.ArkUI'

@Entry
@ComponentV2
struct SubjectSegmentation {
   
  @Local chooseImage?: PixelMap  // 原始图片
  @Local segmentedImage?: PixelMap // 分割后图片
  @Local bgColor: ResourceColor = Color.White // 背景色状态

2. 图片选择与处理

async segmentImage() {
   
  if (canIUse('SystemCapability.AI.Vision.SubjectSegmentation')) {
   
    // 创建图片选择器
    const photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();

    // 选择单张图片
    const photoResult = await photoPicker.select({
   
      MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
      maxSelectNumber: 1
    })

    // 获取图片URI并转换为PixelMap格式
    const photoUri = photoResult.photoUris[0]
    const fileSource = await fileIo.open(photoUri, fileIo.OpenMode.READ_ONLY);
    const imageSource = image.createImageSource(fileSource.fd);
    this.chooseImage = await imageSource.createPixelMap();

3. 主题分割处理

    // 配置视觉识别参数
    const visionInfo: subjectSegmentation.VisionInfo = {
   
      pixelMap: this.chooseImage,
    };

    try {
   
      // 执行主体分割
      const result = await subjectSegmentation.doSegmentation(visionInfo, {
   
        enableSubjectForegroundImage: true
      })
      this.segmentedImage = result.fullSubject.foregroundImage
    } catch (e) {
   
      promptAction.showToast({
    message: e.message })
    }
  }
}

4. 背景替换机制

  build() {
   
    Column({
    space: 20 }) {
   
      // 原始图片展示区域
      Text('原图:')
      Image(this.chooseImage)
        .objectFit(ImageFit.Fill)
        .height('30%')

      // 分割后图片展示区域
      Text('扣除背景:')
      Image(this.segmentedImage)
        .objectFit(ImageFit.Fill)
        .height('30%')
        .backgroundColor(this.bgColor)

      // 功能操作按钮
      Button('选择图片').onClick(() => this.segmentImage())
      Button('更换背景').onClick(() => {
   
        // 生成随机RGB背景色
        const a = Math.round(Math.random() * 255)
        const b = Math.round(Math.random() * 255)
        const c = Math.round(Math.random() * 255)
        this.bgColor = `rgb(${
     a},${
     b},${
     c})`
      })
    }
    .padding(15)
    .height('100%')
    .width('100%')
  }
}

总结梳理:

核心点

  1. 多媒体库调用实现图片选择与格式转换
  2. subjectSegmentation.doSegmentation接口完成智能主体分割
  3. 动态背景色机制通过随机RGB值实现

完整代码

// 此处完整保留用户提供的原始代码
import {
    photoAccessHelper } from '@kit.MediaLibraryKit'
import {
    fileIo } from '@kit.CoreFileKit'
import image from '@ohos.multimedia.image'
import {
    subjectSegmentation } from '@kit.CoreVisionKit'
import {
    promptAction } from '@kit.ArkUI'

@Entry
@ComponentV2
struct SubjectSegmentation {
   
  @Local chooseImage?: PixelMap
  @Local segmentedImage?: PixelMap
  @Local bgColor: ResourceColor = Color.White

  async segmentImage() {
   
    if (canIUse('SystemCapability.AI.Vision.SubjectSegmentation')) {
   
      const photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
      const photoResult = await photoPicker.select({
   
        MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
        maxSelectNumber: 1
      })
      const photoUri = photoResult.photoUris[0]
      const fileSource = await fileIo.open(photoUri, fileIo.OpenMode.READ_ONLY);
      const imageSource = image.createImageSource(fileSource.fd);
      this.chooseImage = await imageSource.createPixelMap();
      const visionInfo: subjectSegmentation.VisionInfo = {
   
        pixelMap: this.chooseImage,
      };
      try {
   
        const result = await subjectSegmentation.doSegmentation(visionInfo, {
   
          enableSubjectForegroundImage: true
        })
        this.segmentedImage = result.fullSubject.foregroundImage
      } catch (e) {
   
        promptAction.showToast({
    message: e.message })
      }
    }
  }

  build() {
   
    Column({
    space: 20 }) {
   
      Text('原图:')
      Image(this.chooseImage)
        .objectFit(ImageFit.Fill)
        .height('30%')
      Text('扣除背景:')
      Image(this.segmentedImage)
        .objectFit(ImageFit.Fill)
        .height('30%')
        .backgroundColor(this.bgColor)
      Button('选择图片')
        .onClick(() => this.segmentImage())
      Button('更换背景')
        .onClick(() => {
   
          const a = Math.round(Math.random() * 255)
          const b = Math.round(Math.random() * 255)
          const c = Math.round(Math.random() * 255)
          this.bgColor = `rgb(${
     a},${
     b},${
     c})`
        })
    }
    .padding(15)
    .height('100%')
    .width('100%')
  }
}
相关文章
|
9天前
|
定位技术 UED
70. [HarmonyOS NEXT 实战案例九] 旅游景点网格布局(下)
在上一篇教程中,我们学习了如何使用GridRow和GridCol组件实现基本的旅游景点网格布局。本篇教程将在此基础上,深入探讨如何优化布局、添加交互功能,以及实现更多高级特性,打造一个功能完善的旅游景点应用。
24 1
|
9天前
|
容器
69.[HarmonyOS NEXT 实战案例九] 旅游景点网格布局(上)
本教程将详细讲解如何使用HarmonyOS NEXT中的GridRow和GridCol组件实现旅游景点网格布局。通过网格布局,我们可以以美观、规整的方式展示各种旅游景点信息,为用户提供良好的浏览体验。
22 1
|
9天前
|
UED
68.[HarmonyOS NEXT 实战案例八] 电影票务网格布局(下)
在上一篇教程中,我们学习了如何使用GridRow和GridCol组件实现基本的电影票务网格布局。本篇教程将在此基础上,深入探讨如何优化布局、添加交互功能,以及实现更多高级特性,打造一个功能完善的电影票务应用。
25 1
|
9天前
|
开发者 容器
67.[HarmonyOS NEXT 实战案例八] 电影票务网格布局(上)
在移动应用开发中,电影票务应用是一个常见的场景,用户可以通过应用查看正在热映的电影信息,并进行选座购票等操作。本教程将详细讲解如何使用HarmonyOS NEXT的GridRow和GridCol组件实现电影票务应用中的电影列表网格布局,帮助开发者掌握网格布局的基本用法和实现技巧。
23 1
|
9天前
|
UED
66.[HarmonyOS NEXT 实战案例七] 健身课程网格布局(下)
在上一篇教程中,我们学习了如何使用GridRow和GridCol组件实现基本的健身课程网格布局。本篇教程将在此基础上,深入探讨如何优化布局、添加交互功能,以及实现更多高级特性,打造一个功能完善的健身课程应用。
19 1
|
9天前
|
设计模式 UED
65. [HarmonyOS NEXT 实战案例七] 健身课程网格布局(上)
本教程将介绍如何使用HarmonyOS NEXT的GridRow和GridCol组件实现健身课程的网格布局展示。健身课程网格布局是一种常见的UI设计模式,适用于展示各种健身课程信息,包括课程名称、教练信息、课程时长、难度级别等。通过网格布局,用户可以快速浏览多个课程,并根据自己的需求选择合适的课程。
22 1
|
9天前
|
设计模式 容器
61.[HarmonyOS NEXT 实战案例五] 社交应用照片墙网格布局(上)
社交应用中的照片墙是一种常见的UI设计模式,它以网格形式展示用户的照片集合,让用户可以浏览、分享和互动。本教程将详细讲解如何使用HarmonyOS NEXT的GridRow和GridCol组件实现一个美观、灵活的社交应用照片墙网格布局。 在本教程中,我们将学习如何设计照片墙的数据结构、如何使用GridRow和GridCol组件创建网格布局、如何实现照片卡片,以及如何处理不同尺寸的照片。通过本教程,你将掌握使用GridRow和GridCol组件实现复杂网格布局的技巧。
19 1
|
9天前
64.[HarmonyOS NEXT 实战案例六] 餐饮菜单网格布局(下)
在上一篇教程中,我们学习了如何使用GridRow和GridCol组件实现基本的餐饮菜单网格布局。本篇教程将在此基础上,深入探讨如何优化布局、添加交互功能,以及实现更多高级特性,打造一个功能完善的餐饮菜单应用。
17 0
|
9天前
|
存储
63.[HarmonyOS NEXT 实战案例六] 餐饮菜单网格布局(上)
在移动应用开发中,餐饮类应用的菜单展示是一个常见的需求。一个设计良好的菜单布局不仅能够清晰地展示菜品信息,还能提升用户的点餐体验。本教程将详细讲解如何使用HarmonyOS NEXT的GridRow和GridCol组件实现一个美观实用的餐饮菜单网格布局。
24 0
|
9天前
|
UED
62. [HarmonyOS NEXT 实战案例五] 社交应用照片墙网格布局(下)
在上一篇教程中,我们学习了如何使用GridRow和GridCol组件实现基本的社交应用照片墙网格布局。本篇教程将在此基础上,深入探讨如何优化布局、添加交互功能,以及实现更多高级特性,打造一个功能完善的社交应用照片墙。
19 0