face-api/src/faceFeatureExtractor/TinyFaceFeatureExtractor.ts

53 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 { denseBlock3 } from './denseBlock';
2021-01-12 16:14:33 +01:00
import { extractParamsFromWeightMapTiny } from './extractParamsFromWeightMapTiny';
2020-08-18 13:54:53 +02:00
import { extractParamsTiny } from './extractParamsTiny';
import { IFaceFeatureExtractor, TinyFaceFeatureExtractorParams } from './types';
export class TinyFaceFeatureExtractor extends NeuralNetwork<TinyFaceFeatureExtractorParams> implements IFaceFeatureExtractor<TinyFaceFeatureExtractorParams> {
constructor() {
2020-12-23 17:26:55 +01:00
super('TinyFaceFeatureExtractor');
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('TinyFaceFeatureExtractor - 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];
2021-03-20 02:39:45 +01:00
const normalized = normalize(batchTensor, meanRgb).div(255) as tf.Tensor4D;
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
let out = denseBlock3(normalized, params.dense0, true);
out = denseBlock3(out, params.dense1);
out = denseBlock3(out, params.dense2);
out = tf.avgPool(out, [14, 14], [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_tiny_model';
2020-08-18 13:54:53 +02:00
}
2021-01-12 16:14:33 +01:00
protected extractParamsFromWeightMap(weightMap: tf.NamedTensorMap) {
return extractParamsFromWeightMapTiny(weightMap);
2020-08-18 13:54:53 +02:00
}
protected extractParams(weights: Float32Array) {
2020-12-23 17:26:55 +01:00
return extractParamsTiny(weights);
2020-08-18 13:54:53 +02:00
}
2020-12-23 17:26:55 +01:00
}