目录

Skeleton Detection

Use Cases

Skeleton detection detects skeleton keypoints on the human body to describe skeletal information. It is primarily used in applications such as intelligent video surveillance, patient monitoring systems, human-computer interaction, virtual reality, human animation, smart home, intelligent security, and athlete training assistance.

The supported 17 keypoints include the nose, left and right eyes, left and right ears, left and right shoulders, left and right elbows, left and right wrists, left and right hips, left and right knees, and left and right ankles.

The following figure shows an example.

Development Procedure

  1. Add the classes for implementing skeleton detection to a project.

    import { image } from '@kit.ImageKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    import { fileIo } from '@kit.CoreFileKit';
    import { skeletonDetection, visionBase } from '@kit.CoreVisionKit';
    import { photoAccessHelper } from '@kit.MediaLibraryKit';
  2. Call photoAccessHelper.PhotoViewPicker to start the gallery to select an image, and use the fileIo and image modules to convert the URI to a PixelMap to prepare input data for the detection API.

    Button('Select image')
      .type(ButtonType.Capsule)
      .fontColor(Color.White)
      .alignSelf(ItemAlign.Center)
      .width('80%')
      .margin(10)
      .onClick(() => {
        // Bring up the gallery to obtain images.
        void this.selectImage();
      })

    The method for selecting and decoding images is implemented as follows:

    private async selectImage() {
      let uri = await this.openPhoto();
      if (!uri) {
        hilog.error(0x0000, 'skeletonDetectSample', 'Failed to define uri.');
        return;
      }
      this.loadImage(uri);
    }
    
    private async openPhoto(): Promise<string> {
      return new Promise<string>((resolve, reject) => {
        let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
        photoPicker.select({
          MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
          maxSelectNumber: 1
        }).then(res => {
          resolve(res.photoUris[0]);
        }).catch((err: BusinessError) => {
          hilog.error(0x0000, 'skeletonDetectSample', `Failed to get photo image uri. code: ${err.code}, message: ${err.message}`);
          reject(err);
        });
      });
    }
    
    private loadImage(name: string) {
      setTimeout(async () => {
        let fileSource = await fileIo.open(name, fileIo.OpenMode.READ_ONLY);
        this.imageSource = image.createImageSource(fileSource.fd);
        this.chooseImage = await this.imageSource.createPixelMap();
        await fileIo.close(fileSource);
      }, 100);
    }
  3. Instantiate the visionBase.Request object and encapsulate PixelMap as an input parameter. Call SkeletonDetector.create() to create a detector instance, call its process method to obtain the 17 key points of the human body in the image, and display the result on the GUI.

    Button('Start skeleton detection')
      .type(ButtonType.Capsule)
      .fontColor(Color.White)
      .alignSelf(ItemAlign.Center)
      .width('80%')
      .margin(10)
      .onClick(() => {
        // Call the encapsulated asynchronous processing function.
        void this.handleSkeletonDetection();
      })

    The skeleton detection method is implemented as follows:

    private async handleSkeletonDetection() {
      try {
        if (!this.chooseImage) {
          hilog.error(0x0000, 'skeletonDetectSample', 'Failed to choose image.');
          return;
        }
        // Call the skeleton detection API.
        let request: visionBase.Request = {
          inputData: { pixelMap: this.chooseImage }
        };
        let detector = await skeletonDetection.SkeletonDetector.create();
        let data: skeletonDetection.SkeletonDetectionResponse = await detector.process(request);
        await detector.destroy();
        let poseJson = JSON.stringify(data);
        hilog.info(0x0000, 'skeletonDetectSample', `Succeeded in skeleton detection: ${poseJson}`);
        this.dataValues = poseJson;
      } catch (err) {
        const error = err as BusinessError;
        hilog.error(0x0000, 'skeletonDetectSample', `Skeleton detection error. Code: ${error.code}, message: ${error.message}`);
      }
    }

Development Example

[h2]Index.ets

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

@Entry
@Component
struct Index {
  private imageSource: image.ImageSource | undefined = undefined;
  @State chooseImage: PixelMap | undefined = undefined;
  @State dataValues: string = '';

  build() {
    Column() {
      Image(this.chooseImage)
        .objectFit(ImageFit.Fill)
        .height('60%')

      Text(this.dataValues)
        .copyOption(CopyOptions.LocalDevice)
        .height('15%')
        .margin(10)
        .width('60%')

      Button('Select image')
        .type(ButtonType.Capsule)
        .fontColor(Color.White)
        .alignSelf(ItemAlign.Center)
        .width('80%')
        .margin(10)
        .onClick(() => {
          // Start Gallery.
          void this.selectImage();
        })

      Button('Start skeleton detection')
        .type(ButtonType.Capsule)
        .fontColor(Color.White)
        .alignSelf(ItemAlign.Center)
        .width('80%')
        .margin(10)
        .onClick(() => {
          // Call the encapsulated asynchronous processing function.
          void this.handleSkeletonDetection();
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

  // Encapsulate the asynchronous logic for skeleton detection.
  private async handleSkeletonDetection() {
    try {
      if (!this.chooseImage) {
        hilog.error(0x0000, 'skeletonDetectSample', 'Failed to choose image.');
        return;
      }
      // Call the skeleton detection API.
      let request: visionBase.Request = {
        inputData: { pixelMap: this.chooseImage }
      };
      let detector = await skeletonDetection.SkeletonDetector.create();
      let data: skeletonDetection.SkeletonDetectionResponse = await detector.process(request);
      await detector.destroy();
      if (!data) {
        hilog.error(0x0000, 'skeletonDetectSample', 'Invalid skeleton detection result');
        return;
      }
      let poseJson = JSON.stringify(data);
      hilog.info(0x0000, 'skeletonDetectSample', `Succeeded in skeleton detection: ${poseJson}`);
      this.dataValues = poseJson;
    } catch (err) {
      const error = err as BusinessError;
      hilog.error(0x0000, 'skeletonDetectSample', `Skeleton detection error. Code: ${error.code}, message: ${error.message}`);
    }
  }

  private async selectImage() {
    let uri = await this.openPhoto();
    if (!uri) {
      hilog.error(0x0000, 'skeletonDetectSample', 'Failed to define uri.');
      return;
    }
    this.loadImage(uri);
  }

  private async openPhoto(): Promise<string> {
    return new Promise<string>((resolve, reject) => {
      let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
      photoPicker.select({
        MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
        maxSelectNumber: 1
      }).then(res => {
        resolve(res.photoUris[0]);
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'skeletonDetectSample', `Failed to get photo image uri. code: ${err.code}, message: ${err.message}`);
        reject(err);
      });
    });
  }

  private loadImage(name: string) {
    setTimeout(async () => {
      let fileSource = await fileIo.open(name, fileIo.OpenMode.READ_ONLY);
      this.imageSource = image.createImageSource(fileSource.fd);
      this.chooseImage = await this.imageSource.createPixelMap();
      await fileIo.close(fileSource);
    }, 100);
  }
}