当前位置: 首页 > article >正文

鸿蒙主体分割/剔除背景

鸿蒙主体分割/剔除背景

参考文档

鸿蒙原生提供用于实现主体分割/剔除背景的API,有一些场景例如说证件照之类的应用就非常好做了。

请添加图片描述

话不多话上代码。

private async doSeg(chooseImage: PixelMap) {
  let visionInfo: subjectSegmentation.VisionInfo = {
    pixelMap: chooseImage,
  };
  let config: subjectSegmentation.SegmentationConfig = {
    maxCount: 1,
    enableSubjectDetails: true,
    enableSubjectForegroundImage: true,
  };
  subjectSegmentation.doSegmentation(visionInfo, config)
    .then((data: subjectSegmentation.SegmentationResult) => {
      let outputString = `Subject count: ${data.subjectCount}\n`;
      outputString += `Max subject count: ${config.maxCount}\n`;
      outputString += `Enable subject details: ${config.enableSubjectDetails ? 'Yes' : 'No'}\n\n`;
      let segBox : subjectSegmentation.Rectangle = data.fullSubject.subjectRectangle;
      let segBoxString = `Full subject box:\nLeft: ${segBox.left}, Top: ${segBox.top}, Width: ${segBox.width}, Height: ${segBox.height}\n\n`;
      outputString += segBoxString;

      if (config.enableSubjectDetails) {
        outputString += 'Individual subject boxes:\n';
        if (data.subjectDetails) {
          for (let i = 0; i < data.subjectDetails.length; i++) {
            let detailSegBox: subjectSegmentation.Rectangle = data.subjectDetails[i].subjectRectangle;
            outputString += `Subject ${i + 1}:\nLeft: ${detailSegBox.left}, Top: ${detailSegBox.top}, Width: ${detailSegBox.width}, Height: ${detailSegBox.height}\n\n`;
          }
        }
      }

      hilog.info(0x0000, TAG, "Segmentation result: " + outputString);

      if (data.fullSubject && data.fullSubject.foregroundImage) {
        let rect = data.fullSubject.subjectRectangle
        let tmpImage = data.fullSubject.foregroundImage
        tmpImage.crop({
          size: {
            width: rect.width,
            height: rect.height
          },
          x: rect.left,
          y: rect.top
        }).then( () => {
          hilog.warn(0x0000, TAG, "截取完毕,检测人脸");
          this.segImage = tmpImage

          this.detectFace()
        })
          .catch((error: BusinessError) => {
            hilog.warn(0x0000, TAG, `截取主体失败 ${error.code} ${error.message}`);
          })
      } else {
        hilog.warn(0x0000, TAG, "No foreground image in segmentation result");
      }
    })
    .catch((error: BusinessError) => {
      hilog.error(0x0000, TAG, `Image segmentation failed errCode: ${error.code}, errMessage: ${error.message}`);
      this.chooseImage = undefined;
    });
}

完成示例

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

const TAG: string = "index";

@Entry
@Component
struct Index {
  @State chooseImage: image.PixelMap | null = null
  @State segImage: image.PixelMap | null = null

  private openPhoto(): Promise<Array<string>> {
    return new Promise<Array<string>>((resolve, reject) => {
      let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
      PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
      PhotoSelectOptions.maxSelectNumber = 1;
      let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
      hilog.info(0x0000, TAG, 'PhotoViewPicker.select successfully, PhotoSelectResult uri: ');
      photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
        hilog.info(0x0000, TAG, `PhotoViewPicker.select successfully, PhotoSelectResult uri: ${PhotoSelectResult.photoUris}`);
        resolve(PhotoSelectResult.photoUris)
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, TAG, `PhotoViewPicker.select failed with errCode: ${err.code}, errMessage: ${err.message}`);
        reject();
      });
    })
  }

  private async loadImage(path: string) {
    let imageSource: image.ImageSource | undefined = undefined
    let fileSource = await fileIo.open(path, fileIo.OpenMode.READ_ONLY)
    imageSource = image.createImageSource(fileSource.fd)
    this.chooseImage = await imageSource.createPixelMap()
    hilog.info(0x0000, TAG, `this.chooseImage===${this.chooseImage}`);
  }

  private async doSeg(chooseImage: PixelMap) {
    let visionInfo: subjectSegmentation.VisionInfo = {
      pixelMap: chooseImage,
    };
    let config: subjectSegmentation.SegmentationConfig = {
      maxCount: 1,
      enableSubjectDetails: true,
      enableSubjectForegroundImage: true,
    };
    subjectSegmentation.doSegmentation(visionInfo, config)
      .then((data: subjectSegmentation.SegmentationResult) => {
        let outputString = `Subject count: ${data.subjectCount}\n`;
        outputString += `Max subject count: ${config.maxCount}\n`;
        outputString += `Enable subject details: ${config.enableSubjectDetails ? 'Yes' : 'No'}\n\n`;
        let segBox : subjectSegmentation.Rectangle = data.fullSubject.subjectRectangle;
        let segBoxString = `Full subject box:\nLeft: ${segBox.left}, Top: ${segBox.top}, Width: ${segBox.width}, Height: ${segBox.height}\n\n`;
        outputString += segBoxString;

        if (config.enableSubjectDetails) {
          outputString += 'Individual subject boxes:\n';
          if (data.subjectDetails) {
            for (let i = 0; i < data.subjectDetails.length; i++) {
              let detailSegBox: subjectSegmentation.Rectangle = data.subjectDetails[i].subjectRectangle;
              outputString += `Subject ${i + 1}:\nLeft: ${detailSegBox.left}, Top: ${detailSegBox.top}, Width: ${detailSegBox.width}, Height: ${detailSegBox.height}\n\n`;
            }
          }
        }

        hilog.info(0x0000, TAG, "Segmentation result: " + outputString);

        if (data.fullSubject && data.fullSubject.foregroundImage) {
          let rect = data.fullSubject.subjectRectangle
          let tmpImage = data.fullSubject.foregroundImage
          tmpImage.crop({
            size: {
              width: rect.width,
              height: rect.height
            },
            x: rect.left,
            y: rect.top
          }).then( () => {
            hilog.warn(0x0000, TAG, "截取完毕,检测人脸");
            this.segImage = tmpImage
          })
            .catch((error: BusinessError) => {
              hilog.warn(0x0000, TAG, `截取主体失败 ${error.code} ${error.message}`);
            })
        } else {
          hilog.warn(0x0000, TAG, "No foreground image in segmentation result");
        }
      })
      .catch((error: BusinessError) => {
        hilog.error(0x0000, TAG, `Image segmentation failed errCode: ${error.code}, errMessage: ${error.message}`);
        this.segImage = null;
      });
  }

  build() {
    Column() {
      Image(this.chooseImage)
        .objectFit(ImageFit.Contain)
        .width('100%')
        .height('40%')

      Row() {
        Image(this.segImage)
          .objectFit(ImageFit.Contain)
          .width('100%')
          .height('100%')
      }
      .width('100%')
      .height('40%')

      Blank()

      Row() {
        Text('选择图片')
          .height(50)
          .width(140)
          .borderRadius(25)
          .textAlign(TextAlign.Center)
          .backgroundColor(Color.Orange)
          .onClick(async () => {
            let urls = await this.openPhoto()
            if (urls.length > 0) {
              let url = urls[0]
              this.loadImage(url)
            }
          })

        Text('分割图片')
          .height(50)
          .width(140)
          .borderRadius(25)
          .textAlign(TextAlign.Center)
          .backgroundColor(Color.Orange)
          .onClick(async () => {
            if (this.chooseImage) {
              this.doSeg(this.chooseImage)
            }
          })
      }
    }
    .height('100%')
    .width('100%')
  }
}

后记

最近利用这些知识上架了两个应用

小鱼证件照,免费便捷的证件照生成工具。

请添加图片描述

小鱼抽签。出门之前占卜吉凶,总会有好事发生。

第1签 锤离成道

天开地辟结良缘,日吉时良万事全,若得此签非小可,人行中正帝王宜

上上签

子宫

此卦盘古初开天地之象,诸事皆吉也

快使用鸿蒙next版本扫一扫体验一下吧~

请添加图片描述


http://www.kler.cn/a/452962.html

相关文章:

  • 记录一次前端绘画海报的过程及遇到的几个问题
  • 散斑/横向剪切/迈克尔逊/干涉条纹仿真技术分析
  • 机器学习之KNN算法预测数据和数据可视化
  • c# RSA加解密工具,.netRSA加解密工具
  • 编码转换(实例)
  • 黑盒测试/白盒测试知识总结
  • 任务三数据库加固
  • 【每日学点鸿蒙知识】数据迁移、大量图片存放、原生自定义键盘调用、APP包安装到测试机、photoPicker顶部高度
  • (八)循环神经网络_门控循环单元GRU
  • 从汽车企业案例看仓网规划的关键步骤(视频版)
  • 项目文档-代码检查报告
  • 无人机巡检大疆智图测绘技术详解
  • ubuntu 轻松安装Conda
  • 【DSVW】攻防实战全记录
  • 2024年度个人总结
  • 题海拾贝:力扣 88.合并两个有序数组
  • Python3 爬虫 开发Scrapy下载器中间件
  • 开源轻量级IM框架MobileIMSDK的鸿蒙NEXT客户端库已发布
  • Python基础学习的资料
  • 每天40分玩转Django:Django类视图
  • Oracle、ACCSEE与TDMS的区别
  • 华为OD E卷(100分)31-敏感字段加密
  • github如何给本机绑定 ssh密钥(MACOS)
  • React图标库: 使用React Icons实现定制化图标效果
  • 利用Java爬虫获取速卖通(AliExpress)商品详情的详细指南
  • Xshell 和 Xftp 更新提示问题的解决方法及分析