Face detection detects faces in images and returns high-precision bounding box coordinates, facial landmark positions, facial orientation, and confidence scores. By locating faces, this capability enables precise beautification and modification of specific facial features. It is widely used in various facial recognition scenarios, such as face clustering and beauty enhancement.
Example:

The following image shows the coordinate system used for representing face orientation.

Add the classes for implementing face detection to a project.
import { faceDetector } from '@kit.CoreVisionKit';
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit'; Initialization and release: Call faceDetector.init() in aboutToAppear to initialize the faceDetector (load the model), and call faceDetector.release() in aboutToDisappear to release resources.
async aboutToAppear(): Promise<void> {
const initResult = await faceDetector.init();
hilog.info(0x0000, 'faceDetectorSample', `Face detector initialization result:${initResult}`);
}
async aboutToDisappear(): Promise<void> {
await faceDetector.release();
hilog.info(0x0000, 'faceDetectorSample', 'Face detector released successfully');
} 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, 'faceDetectorSample', 'Failed to get uri.');
return;
}
this.loadImage(uri);
}
private async openPhoto(): Promise<string> {
return new Promise<string>((resolve) => {
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, 'faceDetectorSample', `Failed to get photo image uri.code: ${err.code}, message: ${err.message}`);
resolve('');
});
});
}
private loadImage(name: string) {
setTimeout(async () => {
let imageSource: image.ImageSource | undefined = undefined;
let fileSource = await fileIo.open(name, fileIo.OpenMode.READ_ONLY);
imageSource = image.createImageSource(fileSource.fd);
this.chooseImage = await imageSource.createPixelMap();
this.dataValues = '';
await fileIo.close(fileSource);
}, 100);
} Construct a VisionInfo object, pass the pixel map of the image to be detected, call the faceDetector.detect method to obtain the detection result of the face location, facial landmarks, and orientation, and display the result on the screen.
Button('Detect face')
.type(ButtonType.Capsule)
.fontColor(Color.White)
.alignSelf(ItemAlign.Center)
.width('80%')
.margin(10)
.onClick(() => {
if (!this.chooseImage) {
hilog.error(0x0000, 'faceDetectorSample', 'Failed to detect face.');
return;
}
// Call the face detection API.
let visionInfo: faceDetector.VisionInfo = {
pixelMap: this.chooseImage
};
faceDetector.detect(visionInfo)
.then((data: faceDetector.Face[]) => {
if (data && Array.isArray(data)) {
if (data.length === 0) {
this.dataValues = 'No face is detected in the image. Select an image that contains a face.';
} else {
let faceString = JSON.stringify(data);
hilog.info(0x0000, 'faceDetectorSample', 'faceString data is ' + faceString);
this.dataValues = faceString;
}
} else {
hilog.error(0x0000, 'faceDetectorSample', 'Unexpected data format received from faceDetector.detect');
this.dataValues = 'Unexpected data format';
}
})
.catch((error: BusinessError) => {
hilog.error(0x0000, 'faceDetectorSample', `Face detection failed. Code: ${error.code}, message: ${error.message}`);
this.dataValues = `Error: ${error.message}`;
});
}) import { faceDetector } from '@kit.CoreVisionKit';
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
@Entry
@Component
struct Index {
@State chooseImage: PixelMap | undefined = undefined;
@State dataValues: string = '';
async aboutToAppear(): Promise<void> {
const initResult = await faceDetector.init();
hilog.info(0x0000, 'faceDetectorSample', `Face detector initialization result:${initResult}`);
}
async aboutToDisappear(): Promise<void> {
await faceDetector.release();
hilog.info(0x0000, 'faceDetectorSample', 'Face detector released successfully');
}
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('Detect face')
.type(ButtonType.Capsule)
.fontColor(Color.White)
.alignSelf(ItemAlign.Center)
.width('80%')
.margin(10)
.onClick(() => {
if (!this.chooseImage) {
hilog.error(0x0000, 'faceDetectorSample', 'Failed to detect face.');
return;
}
// Call the face detection API.
let visionInfo: faceDetector.VisionInfo = {
pixelMap: this.chooseImage
};
faceDetector.detect(visionInfo)
.then((data: faceDetector.Face[]) => {
if (data && Array.isArray(data)) {
if (data.length === 0) {
this.dataValues = 'No face is detected in the image. Select an image that contains a face.';
} else {
let faceString = JSON.stringify(data);
hilog.info(0x0000, 'faceDetectorSample', 'faceString data is ' + faceString);
this.dataValues = faceString;
}
} else {
hilog.error(0x0000, 'faceDetectorSample', 'Unexpected data format received from faceDetector.detect');
this.dataValues = 'Unexpected data format';
}
})
.catch((error: BusinessError) => {
hilog.error(0x0000, 'faceDetectorSample', `Face detection failed. Code: ${error.code}, message: ${error.message}`);
this.dataValues = `Error: ${error.message}`;
});
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
private async selectImage() {
let uri = await this.openPhoto();
if (!uri) {
hilog.error(0x0000, 'faceDetectorSample', 'Failed to get uri.');
return;
}
this.loadImage(uri);
}
private async openPhoto(): Promise<string> {
return new Promise<string>((resolve) => {
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, 'faceDetectorSample', `Failed to get photo image uri.code: ${err.code}, message: ${err.message}`);
resolve('');
});
});
}
private loadImage(name: string) {
setTimeout(async () => {
let imageSource: image.ImageSource | undefined = undefined;
let fileSource = await fileIo.open(name, fileIo.OpenMode.READ_ONLY);
imageSource = image.createImageSource(fileSource.fd);
this.chooseImage = await imageSource.createPixelMap();
this.dataValues = '';
await fileIo.close(fileSource);
}, 100);
}
}