使用HarmonyOS 的主体分割分割出来的图片是黑色背景

使用主体分割,文档地址如下:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/core-vision-subjectsegmentation-api-V5

保存到沙箱文件中,保存的是png格式,图片背景是黑色的,不是透明背景,保存代码如下:

async savePhoto(pixmap: image.PixelMap): Promise<string> {
  return new Promise(async (resolve, reject) => {

  let context = getContext(this);
  let cacheDir = context.cacheDir;
  let imagePackerApi: image.ImagePacker = image.createImagePacker()
  let packOpts: image.PackingOption = {
    format: "image/jpeg", quality: 98
  };
  // 通过PixelMap进行编码。compressedImageData为打包获取到的图片文件流。
  let compressedImageData: ArrayBuffer = await imagePackerApi.packing(pixmap, packOpts);
  let file = fs.openSync(cacheDir + '/' + new Date().getTime() + 'imageeditor.png',
    fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  let packOpts1: image.PackingOption = { format: "image/png", quality: 98 };
  let imagePackerApi1: image.ImagePacker = image.createImagePacker()
  const imageSourceApi: image.ImageSource = image.createImageSource(compressedImageData);
  imagePackerApi1.packToFile(imageSourceApi, file.fd, packOpts1).then(() => {
  // 直接打包进文件
  // fs.closeSync(file);
  resolve(file.path)
  // this.processValue = 70
  // resolve(file.path)
}).catch((error: BusinessError) => {
  console.error('Failed to pack the image. And the error is: ' + error);
})
})
}

主体分割代码如下:

export default class SegUtils {
  async subjectSegmentationTest(): Promise<subjectSegmentation.SubjectResult> {
    const TAG: string = "ImageSegmentationSample";
    let chooseImage: image.PixelMap | undefined = undefined;
    let maxNum: string = '1';

    // Select an image from the gallery
    let PhotoSelectOptions = new picker.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new picker.PhotoViewPicker();
    let PhotoSelectResult = await photoPicker.select(PhotoSelectOptions);
    let uris = PhotoSelectResult.photoUris;

    if (uris.length !== 1) {
      hilog.info(0x0000, TAG, "Selected uris length is not 1");
      // return ;
    }

    // Convert the selected image to PixelMap
    let fileSource = await fileIo.open(uris[0], fileIo.OpenMode.READ_ONLY);
    let imageSource = image.createImageSource(fileSource.fd);
    chooseImage = await imageSource.createPixelMap();

    hilog.info(0x0000, TAG, `chooseImage=${chooseImage}`);

    if (!chooseImage) {
      hilog.info(0x0000, TAG, "chooseImage is undefined");
      // return;
    }

    // Call the image segmentation interface
    let visionInfo: subjectSegmentation.VisionInfo = {
      pixelMap: chooseImage,
    };
    let config: subjectSegmentation.SegmentationConfig = {
      maxCount: parseInt(maxNum),
      enableSubjectDetails: true,
      enableSubjectForegroundImage: true,
    };
    let data: subjectSegmentation.SegmentationResult = await subjectSegmentation.doSegmentation(visionInfo, config);
    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);
    return data.fullSubject
  }
}
HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

可以尝试png图片解码后生成pixelmap方式,参考链接:

https://developer.huawei.com/consumer/cn/doc/atomic-guides-V5/atomic-image-decoding-V5

全局单例示例参考:

import { image } from '@kit.ImageKit';

/*export default class Photourlparams {
  photourl:image.PixelMap;

  constructor(photourl:image.PixelMap) {
    this.photourl=photourl
  }
}*/

export class GlobalVariable {
  private static instance: GlobalVariable;
  //private audioRoutingManager: audio.AudioRoutingManager = audio.getAudioManager().getRoutingManager();

  private photourl:image.PixelMap;

  private constructor(photourl:image.PixelMap) {
    this.photourl = photourl;
  }

  public static getInstance(photourl:image.PixelMap): GlobalVariable {
    if (!GlobalVariable.instance) {
      GlobalVariable.instance = new GlobalVariable(photourl);
    }
    return GlobalVariable.instance;
  }

  public getPPP(): image.PixelMap {
    return this.photourl;
  }
}
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS Grid如何设置分割线
59浏览 • 1回复 待解决
关于字符串分割和重组处理
4551浏览 • 1回复 待解决
HarmonyOS 如何实现分割线拖拽?
30浏览 • 1回复 待解决
List如何设置分割线左右边距?
540浏览 • 1回复 待解决
如何设置TabBar和TabContent分割线样式
2376浏览 • 1回复 待解决
Divider组件如何设置分割线宽度
2912浏览 • 1回复 待解决
如果让分割线垂直起来
5935浏览 • 1回复 待解决
HarmonyOS 怎样变更账号主体
119浏览 • 1回复 待解决