We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All
ReferencesAICore Vision KitArkTS APIobjectDetection (Multi-object Detection)

objectDetection (Multi-object Detection)

Phone5.0.0(12)+PC/2in15.0.1(13)+Tablet5.0.0(12)+

The multi-object detection service identifies multiple objects from an image. This service converts images in various scenarios into digital image information through optical input methods such as photographing and video recording. It then uses AI technologies to analyze the images, locate, and identify multiple objects of interest, such as faces, animals, and plants. This enables users to extract information such as the object category, bounding box position, and confidence level.

Currently, this service can recognize the following types of objects: landscapes, animals, plants, buildings, faces, tables, texts, human heads, cat heads, dog heads, food, cars, human bodies, documents, and cards.

Since: 5.0.0(12)

Modules to Import

Collapse
Word wrap
Dark theme
Copy code
  1. import { visionBase, objectDetection } from '@kit.CoreVisionKit';

VisionObject

Phone5.0.0(12)+PC/2in15.0.1(13)+Tablet5.0.0(12)+

Visual information object.

System capability: SystemCapability.AI.Vision.ObjectDetection

Model restriction: This API can be used only in the stage model.

Since: 5.0.0(12)

Expand
Name Type Read-Only Optional Description
boundingBox visionBase.BoundingBox No No Bounding box of visionObject.
score number No No Confidence score of visionObject. The value range is (0,1). The value 0 indicates the lowest confidence, and the value 1 indicates the highest confidence. A higher confidence score indicates a more reliable location of an object.
labels Array<number> No No

Object label, which indicates the type of an object.

0: landscape

1: animal

2: plant

3: building

5: face

6: form

7: text

8: human head

9: cat head

10: dog head

11: food

12: vehicle

13: human body

21: document

22: card

id number No No Unique identifier of visionObject. The ID is an integer starting from 0 and incrementing sequentially.

ObjectDetectionResponse

Phone5.0.0(12)+PC/2in15.0.1(13)+Tablet5.0.0(12)+

Multi-object detection result class. It inherits from Response of the base class visionBase.

System capability: SystemCapability.AI.Vision.ObjectDetection

Model restriction: This API can be used only in the stage model.

Since: 5.0.0(12)

Expand
Name Type Read-Only Optional Description
objects Array<VisionObject> No No Multi-object detection result. The value can be an object or an array of objects.

ObjectDetector

Phone5.0.0(12)+PC/2in15.0.1(13)+Tablet5.0.0(12)+

Defines the APIs and basic structures of multi-object detection. It inherits from the visionBase.Analyzer class. It has the following functions:

  • constructor(): Private constructor. You cannot directly instantiate ObjectDetector using the new keyword. Instead, you must use the create() static method to create an instance.

  • create(): Promise<ObjectDetector&gt: static method, which is used to create an instance of ObjectDetector. This API returns the result asynchronously through a promise.

  • process(request: visionBase.Request): Promise<ObjectDetectionResponse&gt: instance method, which is used to process multi-target recognition requests. This API returns the result asynchronously through a promise.

  • destroy(): Promise<void&gt: instance method, which is used to destroy the multi-target recognition process. This API returns the result asynchronously through a promise.

System capability: SystemCapability.AI.Vision.ObjectDetection

Model restriction: This API can be used only in the stage model.

Since: 5.0.0(12)

create

Phone5.0.0(12)+PC/2in15.0.1(13)+Tablet5.0.0(12)+

static create(): Promise<ObjectDetector>

API for initializing multi-object detection. This API returns the result asynchronously through a promise.

System capability: SystemCapability.AI.Vision.ObjectDetection

Model restriction: This API can be used only in the stage model.

Since: 5.0.0(12)

Returns:

Expand
Type Description
Promise<ObjectDetector> Promise object, which returns an object detector instance for executing multiple target recognition tasks.

Error codes:

For details about the error codes, please refer to Core Vision Kit Error Codes.

Expand
Error Code Error Message
1011000001 Failed to run, please try again.
1011000002 The service is abnormal.

Example:

Collapse
Word wrap
Dark theme
Copy code
  1. import { objectDetection } from '@kit.CoreVisionKit';
  2. import { hilog } from '@kit.PerformanceAnalysisKit';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. async function createAndDestroyDetector() {
  5. try {
  6. const detector = await objectDetection.ObjectDetector.create();
  7. if (detector) {
  8. hilog.info(0x0000, 'objectDetectionSample', 'Object detector created successfully');
  9. } else {
  10. hilog.error(0x0000, 'objectDetectionSample', 'Failed to create object detector');
  11. return;
  12. }
  13. // Use the detector to perform some operations.
  14. // ...
  15. // Destroy the detector.
  16. if (detector) {
  17. await detector.destroy();
  18. hilog.info(0x0000, 'objectDetectionSample', 'Object detector destroyed successfully');
  19. } else {
  20. hilog.error(0x0000, 'objectDetectionSample', 'Failed to destroy object detector');
  21. }
  22. } catch (err) {
  23. const error = err as BusinessError;
  24. hilog.error(0x0000, 'objectDetectionSample', `Object detector error. Code: ${error.code}, message: ${error.message}`);
  25. }
  26. }
  27. @Entry
  28. @Component
  29. struct Page {
  30. build() {
  31. Column(){
  32. Button('createAndDestroyDetector').onClick(() => {
  33. void createAndDestroyDetector();
  34. })
  35. }
  36. }
  37. }

destroy

Phone5.0.0(12)+PC/2in15.0.1(13)+Tablet5.0.0(12)+

destroy(): Promise<void>

Destroys a multi-object detection process. This API returns the result asynchronously through a promise.

System capability: SystemCapability.AI.Vision.ObjectDetection

Model restriction: This API can be used only in the stage model.

Since: 5.0.0(12)

Returns:

Expand
Type Description
Promise<void> Promise that returns no value.

Example:

Collapse
Word wrap
Dark theme
Copy code
  1. import { objectDetection } from '@kit.CoreVisionKit';
  2. import { hilog } from '@kit.PerformanceAnalysisKit';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. async function createAndDestroyDetector() {
  5. try {
  6. const detector = await objectDetection.ObjectDetector.create();
  7. if (detector) {
  8. hilog.info(0x0000, 'objectDetectionSample', 'Object detector created successfully');
  9. } else {
  10. hilog.error(0x0000, 'objectDetectionSample', 'Failed to create object detector');
  11. return;
  12. }
  13. // Use the detector to perform some operations.
  14. // ...
  15. // Destroy the detector.
  16. if (detector) {
  17. await detector.destroy();
  18. hilog.info(0x0000, 'objectDetectionSample', 'Object detector destroyed successfully');
  19. } else {
  20. hilog.error(0x0000, 'objectDetectionSample', 'Failed to destroy object detector');
  21. }
  22. } catch (err) {
  23. const error = err as BusinessError;
  24. hilog.error(0x0000, 'objectDetectionSample', `Object detector error. Code: ${error.code}, message: ${error.message}`);
  25. }
  26. }
  27. @Entry
  28. @Component
  29. struct Page {
  30. build() {
  31. Column(){
  32. Button('createAndDestroyDetector').onClick(() => {
  33. void createAndDestroyDetector();
  34. })
  35. }
  36. }
  37. }

process

Phone5.0.0(12)+PC/2in15.0.1(13)+Tablet5.0.0(12)+

process(request: visionBase.Request): Promise<ObjectDetectionResponse>

Creates a multi-object detection instance and performs multi-object detection. This API returns the result asynchronously through a promise.

System capability: SystemCapability.AI.Vision.ObjectDetection

Model restriction: This API can be used only in the stage model.

Since: 5.0.0(12)

Parameters:

Expand
Parameter Type Mandatory Description
request visionBase.Request Yes

Image instance. Only one image can be passed for multi-object detection.

For details, see Constraints.

Returns:

Expand
Type Description
Promise<ObjectDetectionResponse> Promise used to return the multi-object detection result.

Error codes:

For details about the error codes, please refer to Core Vision Kit Error Codes.

Expand
Error Code Error Message
401 The parameter check failed.
1011000001 Failed to run, please try again.
1011000003 Failed to run the model, please try again.
1011000004 Running the model timed out. Try again later.

Example:

Collapse
Word wrap
Dark theme
Copy code
  1. import { objectDetection, visionBase } from '@kit.CoreVisionKit';
  2. import { image } from '@kit.ImageKit';
  3. import { hilog } from '@kit.PerformanceAnalysisKit';
  4. import { BusinessError } from '@kit.BasicServicesKit';
  5. import { fileIo } from '@kit.CoreFileKit';
  6. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  7. async function objectDetectTest() {
  8. try {
  9. let imageSource: image.ImageSource | undefined = undefined;
  10. let chooseImage: image.PixelMap | undefined = undefined;
  11. // Select an image from the gallery.
  12. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  13. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  14. photoSelectOptions.maxSelectNumber = 1;
  15. let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
  16. let photoSelectResult = await photoPicker.select(photoSelectOptions);
  17. let uri = photoSelectResult.photoUris[0];
  18. if (uri === undefined) {
  19. hilog.info(0x0000, 'objectDetectionSample', 'uri is undefined');
  20. return;
  21. }
  22. // Convert the image into a pixel map.
  23. let file = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  24. imageSource = image.createImageSource(file.fd);
  25. chooseImage = await imageSource.createPixelMap();
  26. hilog.info(0x0000, 'objectDetectionSample', 'chooseImage:', chooseImage);
  27. if (!chooseImage) {
  28. return;
  29. }
  30. Create an analyzer.
  31. let detector = await objectDetection.ObjectDetector.create();
  32. hilog.info(0x0000, 'objectDetectionSample', 'Object detector created successfully');
  33. // Call the object detection API.
  34. let request: visionBase.Request = {
  35. inputData: { pixelMap: chooseImage },
  36. scene: visionBase.SceneMode.FOREGROUND
  37. };
  38. let response: objectDetection.ObjectDetectionResponse = await detector.process(request);
  39. if (response.objects.length === 0) {
  40. hilog.info(0x0000, 'objectDetectionSample', 'No objects detected in the image.');
  41. } else {
  42. let objectString = JSON.stringify(response.objects);
  43. hilog.info(0x0000, 'objectDetectionSample', 'Detected objects: ' + objectString);
  44. }
  45. // Resources cleanup
  46. if (chooseImage && imageSource) {
  47. void chooseImage.release();
  48. void imageSource.release();
  49. }
  50. if (file) {
  51. await fileIo.close(file);
  52. }
  53. if (detector) {
  54. await detector.destroy();
  55. hilog.info(0x0000, 'objectDetectionSample', 'Object detector destroyed successfully');
  56. }
  57. } catch (err) {
  58. const error = err as BusinessError;
  59. hilog.error(0x0000, 'objectDetectionSample', `Object detection error. Code: ${error.code}, message: ${error.message}`);
  60. }
  61. }
  62. @Entry
  63. @Component
  64. struct Page {
  65. build() {
  66. Column(){
  67. Button('Start').onClick(() => {
  68. // Invoke the nested function.
  69. void objectDetectTest();
  70. })
  71. }
  72. }
  73. }
Search in References
Enter a keyword.