EVAx10_Video_analitics/src/VisionModels.java

162 lines
6.9 KiB
Java

package com.it_screen.edgevision;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import java.util.*;
import org.json.JSONArray;
interface FaceDetector {
List<Face> detect(Bitmap frame, float threshold) throws Exception;
}
interface AgeEstimator {
Integer age(Demographics result);
}
interface GenderEstimator {
String gender(Demographics result, float threshold);
}
final class Face {
final RectF box;
final float confidence;
final float[] landmarks;
Face(RectF box, float confidence, float[] landmarks) {
this.box = box;
this.confidence = confidence;
this.landmarks = landmarks;
}
float overlap(Face other) {
RectF intersection = new RectF(box);
if (!intersection.intersect(other.box)) return 0;
float area = intersection.width() * intersection.height();
return area / (box.width() * box.height() + other.box.width() * other.box.height() - area);
}
}
final class Demographics {
final Integer age;
final String gender;
final float confidence;
Demographics(Integer age, String gender, float confidence) {
this.age = age;
this.gender = gender;
this.confidence = confidence;
}
}
abstract class ImageModel {
final InferenceEngine.Model session;
final int width, height;
private final String input;
private final Set<String> outputs = new LinkedHashSet<>();
private final Bitmap buffer;
private final Canvas canvas;
private final Paint filter = new Paint(Paint.FILTER_BITMAP_FLAG);
private final int[] pixels;
private final float[] tensor;
ImageModel(InferenceEngine.Model session, ModelRegistry.Entry entry) throws Exception {
this.session = session;
input = entry.input().getString("name");
width = entry.input().getInt("width");
height = entry.input().getInt("height");
if (width <= 0 || height <= 0 || width > 1024 || height > 1024)
throw new IllegalArgumentException("Invalid adapter dimensions");
JSONArray names = entry.json.getJSONArray("outputs");
for (int i = 0; i < names.length(); i++) outputs.add(names.getString(i));
buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
canvas = new Canvas(buffer);
pixels = new int[width * height];
tensor = new float[3 * pixels.length];
}
Map<String,float[]> run(Bitmap frame, Rect crop, RectF destination) throws Exception {
buffer.eraseColor(android.graphics.Color.BLACK);
canvas.drawBitmap(frame, crop, destination, filter);
return infer(false, null, null);
}
Map<String,float[]> runNormalized(Bitmap frame, RectF destination, float[] means, float[] std) throws Exception {
buffer.eraseColor(android.graphics.Color.BLACK);
canvas.drawBitmap(frame, null, destination, filter);
buffer.getPixels(pixels, 0, width, 0, 0, width, height);
return infer(true, means, std);
}
Map<String,float[]> runNormalized(Bitmap frame, android.graphics.Matrix transform, float[] means) throws Exception {
buffer.eraseColor(android.graphics.Color.BLACK);
canvas.drawBitmap(frame, transform, filter);
buffer.getPixels(pixels, 0, width, 0, 0, width, height);
return infer(true, means, null);
}
private Map<String,float[]> infer(boolean rgb, float[] means, float[] std) throws Exception {
if (!rgb) buffer.getPixels(pixels, 0, width, 0, 0, width, height);
for (int i = 0; i < pixels.length; i++) {
int pixel = pixels[i];
int first = rgb ? (pixel >> 16) & 255 : pixel & 255;
int third = rgb ? pixel & 255 : (pixel >> 16) & 255;
int second = (pixel >> 8) & 255;
tensor[i] = means == null ? first : (first - means[0]) / (std == null ? 256f : std[0]);
tensor[i + pixels.length] = means == null ? second : (second - means[1]) / (std == null ? 256f : std[1]);
tensor[i + 2 * pixels.length] = means == null ? third : (third - means[2]) / (std == null ? 256f : std[2]);
}
return session.run(input, tensor, new long[]{1, 3, height, width}, outputs);
}
}
final class YuNet extends ImageModel implements FaceDetector {
YuNet(InferenceEngine.Model session, ModelRegistry.Entry entry) throws Exception { super(session, entry); }
@Override public List<Face> detect(Bitmap frame, float threshold) throws Exception {
float scale = Math.min((float) width / frame.getWidth(), (float) height / frame.getHeight());
float drawnWidth = frame.getWidth() * scale;
float drawnHeight = frame.getHeight() * scale;
Map<String,float[]> result = run(frame, null, new RectF(0, 0, drawnWidth, drawnHeight));
List<Face> candidates = new ArrayList<>();
for (int stride : new int[]{8,16,32}) {
float[] cls = result.get("cls_" + stride);
float[] obj = result.get("obj_" + stride);
float[] bbox = result.get("bbox_" + stride);
float[] points = result.get("kps_" + stride);
int cols = width / stride;
for (int i = 0; i < cls.length; i++) {
float score = (float) Math.sqrt(clamp(cls[i], 1) * clamp(obj[i], 1));
if (score < threshold) continue;
int p = 4 * i;
float cx = (i % cols + bbox[p]) * stride;
float cy = (i / cols + bbox[p + 1]) * stride;
float halfW = (float) Math.exp(bbox[p + 2]) * stride / 2;
float halfH = (float) Math.exp(bbox[p + 3]) * stride / 2;
RectF rect = new RectF(clamp(cx - halfW, drawnWidth) / drawnWidth,
clamp(cy - halfH, drawnHeight) / drawnHeight,
clamp(cx + halfW, drawnWidth) / drawnWidth, clamp(cy + halfH, drawnHeight) / drawnHeight);
if (rect.width() <= 0 || rect.height() <= 0) continue;
float[] landmarks = null;
if (points != null) {
landmarks = new float[10];
for (int j = 0; j < 5; j++) {
landmarks[2*j] = (i % cols + points[10*i + 2*j]) * stride / scale;
landmarks[2*j+1] = (i / cols + points[10*i + 2*j+1]) * stride / scale;
}
}
candidates.add(new Face(rect, score, landmarks));
}
}
candidates.sort(Comparator.comparingDouble((Face face) -> face.confidence).reversed());
List<Face> accepted = new ArrayList<>();
for (Face face : candidates) {
if (accepted.stream().noneMatch(other -> face.overlap(other) > 0.3)) accepted.add(face);
if (accepted.size() == 32) break;
}
return accepted;
}
private static float clamp(float value, float max) { return Math.max(0, Math.min(max, value)); }
}