face-api/src/faceFeatureExtractor/FaceFeatureExtractor.ts

54 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-12-23 18:58:47 +01:00
import * as tf from '../../dist/tfjs.esm';
2020-08-18 13:54:53 +02:00
2020-12-19 17:46:41 +01:00
import { NetInput, TNetInput, toNetInput } from '../dom/index';
2020-08-18 13:54:53 +02:00
import { NeuralNetwork } from '../NeuralNetwork';
2020-12-19 17:46:41 +01:00
import { normalize } from '../ops/index';
2020-08-18 13:54:53 +02:00
import { denseBlock4 } from './denseBlock';
import { extractParams } from './extractParams';
2021-01-12 16:14:33 +01:00
import { extractParamsFromWeightMap } from './extractParamsFromWeightMap';
2020-08-18 13:54:53 +02:00
import { FaceFeatureExtractorParams, IFaceFeatureExtractor } from './types';
export class FaceFeatureExtractor extends NeuralNetwork<FaceFeatureExtractorParams> implements IFaceFeatureExtractor<FaceFeatureExtractorParams> {
constructor() {
2020-12-23 17:26:55 +01:00
super('FaceFeatureExtractor');
2020-08-18 13:54:53 +02:00
}
public forwardInput(input: NetInput): tf.Tensor4D {
2020-12-23 17:26:55 +01:00
const { params } = this;
2020-08-18 13:54:53 +02:00
if (!params) {
2020-12-23 17:26:55 +01:00
throw new Error('FaceFeatureExtractor - load model before inference');
2020-08-18 13:54:53 +02:00
}
return tf.tidy(() => {
2020-10-26 01:01:36 +01:00
const batchTensor = tf.cast(input.toBatchTensor(112, true), 'float32');
2020-12-23 17:26:55 +01:00
const meanRgb = [122.782, 117.001, 104.298];
const normalized = normalize(batchTensor, meanRgb).div(tf.scalar(255)) as tf.Tensor4D;
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
let out = denseBlock4(normalized, params.dense0, true);
out = denseBlock4(out, params.dense1);
out = denseBlock4(out, params.dense2);
out = denseBlock4(out, params.dense3);
out = tf.avgPool(out, [7, 7], [2, 2], 'valid');
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
return out;
});
2020-08-18 13:54:53 +02:00
}
public async forward(input: TNetInput): Promise<tf.Tensor4D> {
2020-12-23 17:26:55 +01:00
return this.forwardInput(await toNetInput(input));
2020-08-18 13:54:53 +02:00
}
protected getDefaultModelName(): string {
2020-12-23 17:26:55 +01:00
return 'face_feature_extractor_model';
2020-08-18 13:54:53 +02:00
}
2021-01-12 16:14:33 +01:00
protected extractParamsFromWeightMap(weightMap: tf.NamedTensorMap) {
return extractParamsFromWeightMap(weightMap);
2020-08-18 13:54:53 +02:00
}
protected extractParams(weights: Float32Array) {
2020-12-23 17:26:55 +01:00
return extractParams(weights);
2020-08-18 13:54:53 +02:00
}
2020-12-23 17:26:55 +01:00
}