Compare commits
11
Commits
ko
...
29c193b716
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29c193b716 | ||
|
|
76442888f7 | ||
|
|
d32e0a11f5 | ||
|
|
fb8bdcd895 | ||
|
|
7ef0df48dd | ||
|
|
50b579705e | ||
|
|
8551abfc5d | ||
|
|
bbd333426d | ||
|
|
e98ae10267 | ||
|
|
7d29ed1ca9 | ||
|
|
f98079d431 |
No files matched your search
@@ -37,6 +37,12 @@ dependencies {
|
|||||||
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
|
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
|
||||||
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
|
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
|
||||||
|
|
||||||
|
|
||||||
|
// OpenCV (from: https://github.com/QuickBirdEng/opencv-android)
|
||||||
|
def opencv_version = "4.5.3.0"
|
||||||
|
implementation "com.quickbirdstudios:opencv:${opencv_version}"
|
||||||
|
|
||||||
|
|
||||||
// Required for CameraX
|
// Required for CameraX
|
||||||
def camerax_version = "1.2.2"
|
def camerax_version = "1.2.2"
|
||||||
implementation "androidx.camera:camera-core:${camerax_version}"
|
implementation "androidx.camera:camera-core:${camerax_version}"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
<uses-feature android:name="android.hardware.camera"/>
|
<uses-feature android:name="android.hardware.camera"/>
|
||||||
<uses-permission android:name="android.permission.CAMERA"/>
|
<uses-permission android:name="android.permission.CAMERA"/>
|
||||||
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
|
|||||||
@@ -9,24 +9,26 @@ public class DetectionReport {
|
|||||||
public String timeStamp;
|
public String timeStamp;
|
||||||
public String detectionType;
|
public String detectionType;
|
||||||
public float detectedValue;
|
public float detectedValue;
|
||||||
public String detectorID;
|
public boolean detectionState;
|
||||||
|
|
||||||
public DetectionReport(String detectorID, String detectionType, float detectedAmplitude) {
|
public DetectionReport(boolean detectionState, String detectionType, float detectedAmplitude) {
|
||||||
this.timeStamp = String.valueOf(Calendar.getInstance().getTime());
|
this.timeStamp = String.valueOf(Calendar.getInstance().getTime());
|
||||||
this.detectionType = detectionType;
|
this.detectionType = detectionType;
|
||||||
this.detectedValue = detectedAmplitude;
|
this.detectedValue = detectedAmplitude;
|
||||||
this.detectorID = detectorID;
|
this.detectionState = detectionState;
|
||||||
|
|
||||||
|
//this.detectorID = detectorID;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/** Get Detection Report in String format */
|
/** Get Detection Report in String format */
|
||||||
public String toString() {
|
public String toString() {
|
||||||
|
String state = "State: " + "[" + this.detectionState + "]";
|
||||||
String time = "Time: " + "[" + this.timeStamp + "]";
|
String time = "Time: " + "[" + this.timeStamp + "]";
|
||||||
String type = "Type: " + "[" + this.detectionType + "]";
|
String type = "Type: " + "[" + this.detectionType + "]";
|
||||||
String value = "Value: " + "[" + this.detectedValue + "]";
|
String value = "Value: " + "[" + this.detectedValue + "]";
|
||||||
String id = "ID: " + "[" + this.detectorID + "]";
|
|
||||||
|
|
||||||
return String.join("\t", time, type, value, id);
|
return String.join("\t", state, time, type, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Debug Report */
|
/** Debug Report */
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
package com.example.ueberwachungssystem.Detection;
|
package com.example.ueberwachungssystem.Detection;
|
||||||
|
|
||||||
|
import android.os.CountDownTimer;
|
||||||
|
|
||||||
import androidx.annotation.NonNull;
|
import androidx.annotation.NonNull;
|
||||||
|
|
||||||
|
|
||||||
abstract public class Detector {
|
abstract public class Detector {
|
||||||
private OnDetectionListener listener;
|
private OnDetectionListener listener;
|
||||||
|
private boolean isDetecting = false;
|
||||||
|
private boolean extendViolation = false;
|
||||||
|
|
||||||
|
// Countdown parameters
|
||||||
|
private final int COUNTDOWN_TIME = 5000; // milliseconds
|
||||||
|
private final int COUNTDOWN_POLLING_TIME = 100; // milliseconds
|
||||||
|
|
||||||
/** Constructor - takes context of current activity */
|
/** Constructor - takes context of current activity */
|
||||||
public Detector() {}
|
public Detector() {}
|
||||||
@@ -18,17 +26,46 @@ abstract public class Detector {
|
|||||||
this.listener = listener;
|
this.listener = listener;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/** Triggers onDetectionListener - call this to trigger violation/alarm */
|
/** Triggers onDetectionListener - call this to trigger violation/alarm */
|
||||||
public void reportViolation(String detectorID, String detectionType, float amplitude) {
|
public void reportViolation(String detectionType, float amplitude) {
|
||||||
if (listener != null) {
|
if (listener != null) {
|
||||||
DetectionReport detectionReport = new DetectionReport(detectorID, detectionType, amplitude);
|
if (!isDetecting) {
|
||||||
listener.onDetection(detectionReport);
|
isDetecting = true;
|
||||||
|
DetectionReport detectionReport = new DetectionReport(true, detectionType, amplitude);
|
||||||
|
listener.onDetection(detectionReport);
|
||||||
|
startDetectionTimer(detectionType, amplitude);
|
||||||
|
} else {
|
||||||
|
extendViolation = true;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalStateException("No listener set for violation reporting");
|
isDetecting = false;
|
||||||
|
extendViolation = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void startDetectionTimer(String detectionType, float amplitude) {
|
||||||
|
isDetecting = true;
|
||||||
|
new CountDownTimer((long) COUNTDOWN_TIME, COUNTDOWN_POLLING_TIME) {
|
||||||
|
@Override
|
||||||
|
public void onTick(long millisUntilFinished) {
|
||||||
|
if (extendViolation) {
|
||||||
|
extendViolation = false;
|
||||||
|
startDetectionTimer(detectionType, amplitude);
|
||||||
|
this.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public void onFinish() {
|
||||||
|
isDetecting = false;
|
||||||
|
DetectionReport detectionReport = new DetectionReport(false, detectionType, amplitude);
|
||||||
|
listener.onDetection(detectionReport);
|
||||||
|
}
|
||||||
|
}.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extendViolation(){
|
||||||
|
this.extendViolation = true;
|
||||||
|
}
|
||||||
|
|
||||||
/** Starts Detection (abstract method: needs to be overridden in child class) */
|
/** Starts Detection (abstract method: needs to be overridden in child class) */
|
||||||
public abstract void startDetection();
|
public abstract void startDetection();
|
||||||
|
|||||||
@@ -1,38 +1,57 @@
|
|||||||
package com.example.ueberwachungssystem.Detection;
|
package com.example.ueberwachungssystem.Detection;
|
||||||
|
|
||||||
|
import android.Manifest;
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.app.Activity;
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
|
import android.content.pm.PackageManager;
|
||||||
|
import android.graphics.Bitmap;
|
||||||
import android.graphics.ImageFormat;
|
import android.graphics.ImageFormat;
|
||||||
import android.media.Image;
|
import android.media.Image;
|
||||||
import android.util.Size;
|
import android.os.CountDownTimer;
|
||||||
|
import android.util.Log;
|
||||||
|
import android.view.Surface;
|
||||||
|
import android.widget.ImageView;
|
||||||
|
import android.widget.Toast;
|
||||||
|
|
||||||
import androidx.annotation.NonNull;
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
import androidx.camera.core.CameraSelector;
|
import androidx.camera.core.CameraSelector;
|
||||||
import androidx.camera.core.ExperimentalGetImage;
|
import androidx.camera.core.ExperimentalGetImage;
|
||||||
import androidx.camera.core.ImageAnalysis;
|
import androidx.camera.core.ImageAnalysis;
|
||||||
|
import androidx.camera.core.ImageProxy;
|
||||||
import androidx.camera.core.Preview;
|
import androidx.camera.core.Preview;
|
||||||
|
import androidx.camera.core.VideoCapture;
|
||||||
import androidx.camera.lifecycle.ProcessCameraProvider;
|
import androidx.camera.lifecycle.ProcessCameraProvider;
|
||||||
import androidx.camera.view.PreviewView;
|
import androidx.camera.view.PreviewView;
|
||||||
|
import androidx.core.app.ActivityCompat;
|
||||||
import androidx.core.content.ContextCompat;
|
import androidx.core.content.ContextCompat;
|
||||||
import androidx.lifecycle.LifecycleOwner;
|
import androidx.lifecycle.LifecycleOwner;
|
||||||
|
|
||||||
import com.google.common.util.concurrent.ListenableFuture;
|
import com.google.common.util.concurrent.ListenableFuture;
|
||||||
|
|
||||||
|
import org.opencv.android.OpenCVLoader;
|
||||||
|
import org.opencv.android.Utils;
|
||||||
|
import org.opencv.core.Core;
|
||||||
|
import org.opencv.core.CvType;
|
||||||
|
import org.opencv.core.Mat;
|
||||||
|
import org.opencv.core.MatOfPoint;
|
||||||
|
import org.opencv.core.Scalar;
|
||||||
|
import org.opencv.core.Size;
|
||||||
|
import org.opencv.imgproc.Imgproc;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
import java.util.concurrent.ExecutionException;
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Video Detector inherits some methods from abstract Detector class (more info there)
|
* Video Detector inherits some methods from abstract Detector class (more info there)
|
||||||
*
|
|
||||||
*
|
|
||||||
* USE FROM MAIN ACTIVITY:
|
* USE FROM MAIN ACTIVITY:
|
||||||
*
|
|
||||||
* VideoDetector vd = new VideoDetector(this);
|
* VideoDetector vd = new VideoDetector(this);
|
||||||
* vd.setPreview(previewView); //THIS IS OPTIONAL!
|
|
||||||
* vd.setOnDetectionListener(new Detector.OnDetectionListener{...});
|
|
||||||
* vd.startDetection();
|
|
||||||
* vd.stopDetection
|
|
||||||
*
|
|
||||||
* */
|
* */
|
||||||
|
|
||||||
|
|
||||||
@@ -41,156 +60,382 @@ public class VideoDetector extends Detector {
|
|||||||
|
|
||||||
// Calling Activity
|
// Calling Activity
|
||||||
private final Context context;
|
private final Context context;
|
||||||
|
|
||||||
|
// Permission handling
|
||||||
|
private static final int PERMISSION_REQUEST_CODE = 3691;
|
||||||
|
|
||||||
// Camera Provider
|
// Camera Provider
|
||||||
private ProcessCameraProvider cameraProvider;
|
private ProcessCameraProvider cameraProvider;
|
||||||
private Boolean isDetectionRunning = false;
|
private final ImageAnalysis imageAnalysis;
|
||||||
// Preview Camera Image
|
private final VideoCapture videoCapture;
|
||||||
private PreviewView previewView = null;
|
private final Preview preview;
|
||||||
// Detect Violation
|
|
||||||
private static final float PIXEL_THRESHOLD = 30f; // Luminosity (brightness channel of YUV_420_888)
|
// Logic
|
||||||
private static final float ALARM_THRESHOLD = 0.2f; // Percent of pixels changed
|
private boolean isDetecting = false;
|
||||||
private ByteBuffer previousBuffer = null;
|
private boolean isRecording = false;
|
||||||
|
private boolean allowReportViolation = false;
|
||||||
|
|
||||||
|
// Image Processing
|
||||||
|
private Mat previousImage = null;
|
||||||
|
|
||||||
|
// Debugging
|
||||||
|
private ImageView inputImageView = null;
|
||||||
|
private ImageView outputImageView = null;
|
||||||
|
|
||||||
|
|
||||||
|
// Recording
|
||||||
|
private final String outputName = "video.mp4";
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructor
|
// Parameters
|
||||||
* @param context: the context of calling activity (usually "this")
|
private static final float ALARM_THRESHOLD = 0.5f; // Percent of pixels changed
|
||||||
* */
|
private static final long START_DELAY = 20000; // milliseconds
|
||||||
|
private static final android.util.Size IMAGE_RES = new android.util.Size(640, 480);
|
||||||
|
|
||||||
|
|
||||||
|
private enum UseCase {
|
||||||
|
ImageAnalysis,
|
||||||
|
Preview,
|
||||||
|
VideoCapture
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/** Constructor */
|
||||||
public VideoDetector(Context context) {
|
public VideoDetector(Context context) {
|
||||||
super();
|
super();
|
||||||
this.context = context;
|
this.context = context;
|
||||||
|
this.imageAnalysis = setupImageAnalysis();
|
||||||
|
this.videoCapture = setupVideoCapture();
|
||||||
|
this.preview = new Preview.Builder().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get State of the Detector */
|
||||||
|
public boolean isRunning() {
|
||||||
|
return isDetecting;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/** Starts the Video Detection */
|
||||||
* Starts the Video Detection
|
|
||||||
* */
|
|
||||||
@Override
|
@Override
|
||||||
public void startDetection() {
|
public void startDetection() {
|
||||||
if (isDetectionRunning)
|
// Check States
|
||||||
|
if (isDetecting)
|
||||||
return;
|
return;
|
||||||
// Request Camera Provider
|
// Return On Request Permissions
|
||||||
|
if (!hasPermissions()) {
|
||||||
|
getPermissions();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Open CV startup check
|
||||||
|
if (!OpenCVLoader.initDebug()) {
|
||||||
|
Log.e("OpenCV", "Unable to load OpenCV!");
|
||||||
|
return;
|
||||||
|
} else
|
||||||
|
Log.d("OpenCV", "OpenCV loaded Successfully!");
|
||||||
|
// Get Process Camera Provider and start
|
||||||
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context);
|
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context);
|
||||||
//Check for Camera availability
|
|
||||||
cameraProviderFuture.addListener(() -> {
|
cameraProviderFuture.addListener(() -> {
|
||||||
try {
|
try {
|
||||||
cameraProvider = cameraProviderFuture.get();
|
cameraProvider = cameraProviderFuture.get();
|
||||||
bindAnalysis(cameraProvider);
|
isDetecting = true;
|
||||||
isDetectionRunning = true;
|
bindCameraProvider(UseCase.ImageAnalysis);
|
||||||
previousBuffer = null;
|
} catch (ExecutionException | InterruptedException e) {}
|
||||||
} catch (ExecutionException | InterruptedException e) {
|
}, ContextCompat.getMainExecutor(context));
|
||||||
// No errors need to be handled for this Future. This should never be reached.
|
|
||||||
}
|
startViolationTimer();
|
||||||
},ContextCompat.getMainExecutor(context));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Stops the Video Detection */
|
||||||
/**
|
|
||||||
* Stops the Video Detection
|
|
||||||
* */
|
|
||||||
@Override
|
@Override
|
||||||
public void stopDetection() {
|
public void stopDetection() {
|
||||||
if (!isDetectionRunning)
|
if (!isDetecting || imageAnalysis == null)
|
||||||
return;
|
return;
|
||||||
|
cameraProvider.unbind(imageAnalysis);
|
||||||
|
isDetecting = false;
|
||||||
|
allowReportViolation = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Permission handling */
|
||||||
|
private boolean hasPermissions() {
|
||||||
|
return ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&
|
||||||
|
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
|
||||||
|
}
|
||||||
|
private void getPermissions() {
|
||||||
|
if (!hasPermissions())
|
||||||
|
ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, PERMISSION_REQUEST_CODE);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/** Binds the Luminosity Analyzer (configure and run Analysis) */
|
||||||
|
private void bindCameraProvider(UseCase useCase) {
|
||||||
|
// Specify which Camera to use
|
||||||
|
CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
|
||||||
cameraProvider.unbindAll();
|
cameraProvider.unbindAll();
|
||||||
isDetectionRunning = false;
|
cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, imageAnalysis, videoCapture);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/** Start delay until Violation Report is allowed */
|
||||||
* Set PreviewView to show video feed while detecting
|
private void startViolationTimer() {
|
||||||
* this is optional and does not need to be called
|
new CountDownTimer((long) (START_DELAY), 100) {
|
||||||
* */
|
@Override
|
||||||
public void setPreviewView(PreviewView previewView) {
|
public void onTick(long millisUntilFinished) {
|
||||||
this.previewView = previewView;
|
}
|
||||||
|
@Override
|
||||||
|
public void onFinish() {
|
||||||
|
allowReportViolation = true;
|
||||||
|
}
|
||||||
|
}.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
private ImageAnalysis setupImageAnalysis() {
|
||||||
* Binds the Luminosity Analyzer (configure and run Analysis)
|
|
||||||
* @param cameraProvider: CameraProvider of Context passed by Constructor
|
|
||||||
* */
|
|
||||||
private void bindAnalysis(@NonNull ProcessCameraProvider cameraProvider) {
|
|
||||||
// Configure and create Image Analysis
|
// Configure and create Image Analysis
|
||||||
ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
|
ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
|
||||||
builder.setTargetResolution(new Size(640, 480));
|
builder.setTargetResolution(IMAGE_RES);
|
||||||
builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
|
builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
|
||||||
builder.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888);
|
builder.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888);
|
||||||
ImageAnalysis imageAnalysis = builder.build();
|
ImageAnalysis imageAnalysis = builder.build();
|
||||||
|
|
||||||
// Set Analyzer
|
// Set Analyzer
|
||||||
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(context), imageProxy -> {
|
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(context), imageProxy -> {
|
||||||
if (imageProxy.getFormat() == ImageFormat.YUV_420_888) {
|
if (imageProxy.getFormat() == ImageFormat.YUV_420_888) {
|
||||||
Image image = imageProxy.getImage();
|
Image image = imageProxy.getImage();
|
||||||
assert image != null;
|
assert image != null;
|
||||||
|
|
||||||
// Changed Pixel Detection
|
// Violation Handling
|
||||||
int pixelChanged = getChangedPixelCount(image);
|
Mat processed = processImage(imageProxy);
|
||||||
int width = image.getWidth();
|
int n = OpenCVHelper.countNonZeroPixels(processed);
|
||||||
int height = image.getHeight();
|
int pixelCount = image.getWidth() * image.getHeight();
|
||||||
|
float percentChanged = (float) n / pixelCount;
|
||||||
|
|
||||||
float percentPixelChanged = (float) 100f * pixelChanged / (width * height);
|
// Violation Condition
|
||||||
|
if (percentChanged * 100 > ALARM_THRESHOLD) {
|
||||||
if (percentPixelChanged > ALARM_THRESHOLD)
|
if (allowReportViolation)
|
||||||
reportViolation("0", "Video", percentPixelChanged);
|
reportViolation("Video", n);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
imageProxy.close();
|
imageProxy.close();
|
||||||
});
|
});
|
||||||
|
return imageAnalysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("RestrictedApi")
|
||||||
|
private VideoCapture setupVideoCapture() {
|
||||||
|
return new VideoCapture.Builder()
|
||||||
|
.setTargetRotation(Surface.ROTATION_0)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("RestrictedApi")
|
||||||
|
public void startRecording() {
|
||||||
|
// Check States
|
||||||
|
if (isRecording){
|
||||||
|
extendViolation();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return On Request Permissions
|
||||||
|
if (!hasPermissions()) {
|
||||||
|
getPermissions();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context);
|
||||||
|
cameraProviderFuture.addListener(() -> {
|
||||||
|
try {
|
||||||
|
cameraProvider = cameraProviderFuture.get();
|
||||||
|
isRecording = true;
|
||||||
|
bindCameraProvider(UseCase.VideoCapture);
|
||||||
|
|
||||||
|
File vidFile = new File(context.getFilesDir() + "/" + outputName);
|
||||||
|
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
videoCapture.startRecording(
|
||||||
|
new VideoCapture.OutputFileOptions.Builder(vidFile).build(),
|
||||||
|
context.getMainExecutor(),
|
||||||
|
new VideoCapture.OnVideoSavedCallback() {
|
||||||
|
@Override
|
||||||
|
public void onVideoSaved(@NonNull VideoCapture.OutputFileResults outputFileResults) {
|
||||||
|
isRecording = false;
|
||||||
|
Toast.makeText(context, "recording saved", Toast.LENGTH_SHORT).show();
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public void onError(int videoCaptureError, @NonNull String message, @Nullable Throwable cause) {
|
||||||
|
isRecording = false;
|
||||||
|
Toast.makeText(context, "recording failed", Toast.LENGTH_SHORT).show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} catch (ExecutionException | InterruptedException e) {}
|
||||||
|
}, ContextCompat.getMainExecutor(context));
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("RestrictedApi")
|
||||||
|
public void stopRecording(){
|
||||||
|
videoCapture.stopRecording();
|
||||||
|
cameraProvider.unbind(videoCapture);
|
||||||
|
isRecording = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Process Image to be used for Motion Detection */
|
||||||
|
private Mat processImage(ImageProxy imageProxy){
|
||||||
|
if (imageProxy == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
// Image Transformation
|
||||||
|
Mat imageMat = OpenCVHelper.extractYChannel(imageProxy);
|
||||||
|
|
||||||
|
// Show Input Image
|
||||||
|
if (inputImageView != null)
|
||||||
|
OpenCVHelper.debugMat(imageMat, inputImageView);
|
||||||
|
|
||||||
|
// Preprocess Image
|
||||||
|
Mat preprocessed = imageMat;
|
||||||
|
preprocessed = OpenCVHelper.addGaussianBlur(preprocessed, new Size(21, 21));
|
||||||
|
preprocessed = OpenCVHelper.addBlur(preprocessed, new Size(3, 3));
|
||||||
|
|
||||||
|
if (previousImage == null) {
|
||||||
|
previousImage = preprocessed;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process Image
|
||||||
|
Mat processed = preprocessed.clone();
|
||||||
|
processed = OpenCVHelper.thresholdPixels(processed, previousImage, 25);
|
||||||
|
processed = OpenCVHelper.dilateBinaryMat(processed, new Size(3,3));
|
||||||
|
processed = OpenCVHelper.dilateBinaryMat(processed, new Size(3,3));
|
||||||
|
processed = OpenCVHelper.thresholdContourArea(processed, 500);
|
||||||
|
|
||||||
|
// Output
|
||||||
|
previousImage = preprocessed.clone();
|
||||||
|
// Show Output Image
|
||||||
|
if (outputImageView != null)
|
||||||
|
OpenCVHelper.debugMat(processed, outputImageView);
|
||||||
|
return processed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void debugProcessing(@NonNull ImageView inputImageView, @NonNull ImageView outputImageView){
|
||||||
|
this.inputImageView = inputImageView;
|
||||||
|
this.outputImageView = outputImageView;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPreviewView(@NonNull PreviewView previewView) {
|
||||||
// Create Preview
|
// Create Preview
|
||||||
Preview preview = new Preview.Builder().build();
|
if (this.preview != null)
|
||||||
// Specify which Camera to use
|
this.preview.setSurfaceProvider(previewView.getSurfaceProvider());
|
||||||
CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
|
|
||||||
// Update PreviewView if set
|
|
||||||
if (previewView != null)
|
|
||||||
preview.setSurfaceProvider(previewView.getSurfaceProvider());
|
|
||||||
|
|
||||||
cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, imageAnalysis, preview);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
private static class OpenCVHelper{
|
||||||
* Calculate Amount of Pixels changed using a threshold
|
private OpenCVHelper() {}
|
||||||
* @param image
|
|
||||||
* */
|
|
||||||
private int getChangedPixelCount(Image image) {
|
|
||||||
Image.Plane[] planes = image.getPlanes();
|
|
||||||
ByteBuffer buffer = planes[0].getBuffer();
|
|
||||||
|
|
||||||
if (previousBuffer == null) {
|
/** OpenCV helper methods **/
|
||||||
previousBuffer = ByteBuffer.allocate(buffer.capacity());
|
private static Mat addGaussianBlur(Mat inputMat, Size kernelSize){
|
||||||
buffer.rewind();
|
Mat outputMat = new Mat();
|
||||||
previousBuffer.put(buffer);
|
Imgproc.GaussianBlur(inputMat, outputMat, kernelSize, 0);
|
||||||
previousBuffer.rewind();
|
return outputMat;
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int width = image.getWidth();
|
private static Mat addBlur(Mat inputMat, Size kernelSize){
|
||||||
int height = image.getHeight();
|
Mat outputMat = new Mat();
|
||||||
|
Imgproc.blur(inputMat, outputMat, kernelSize);
|
||||||
|
return outputMat;
|
||||||
|
}
|
||||||
|
|
||||||
int yRowStride = image.getPlanes()[0].getRowStride();
|
private static Mat extractYChannel(@NonNull ImageProxy imgProxy) {
|
||||||
int yPixelStride = image.getPlanes()[0].getPixelStride();
|
Image img = imgProxy.getImage();
|
||||||
|
|
||||||
int changedPixelCount = 0;
|
assert img != null;
|
||||||
|
ByteBuffer yBuffer = img.getPlanes()[0].getBuffer();
|
||||||
|
byte[] yData = new byte[yBuffer.remaining()];
|
||||||
|
yBuffer.get(yData);
|
||||||
|
|
||||||
// Count changed pixels
|
Mat yMat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC1);
|
||||||
for (int y = 0; y < height; ++y) {
|
yMat.put(0, 0, yData);
|
||||||
for (int x = 0; x < width; x++) {
|
|
||||||
int index = (y * yRowStride) + (x * yPixelStride);
|
return yMat;
|
||||||
int luminosity = (buffer.get(index) & 0xff);
|
}
|
||||||
int previousLuminosity = (previousBuffer.get(index) & 0xff);
|
|
||||||
int diff = Math.abs(luminosity - previousLuminosity);
|
private static Mat thresholdPixels(Mat inputMat, Mat previousImage, int threshold){
|
||||||
if (diff > PIXEL_THRESHOLD)
|
Mat diffImage = new Mat();
|
||||||
changedPixelCount++;
|
Core.absdiff(inputMat, previousImage, diffImage);
|
||||||
|
Mat binaryMat = new Mat();
|
||||||
|
Imgproc.threshold(diffImage, binaryMat, threshold, 255, Imgproc.THRESH_BINARY);
|
||||||
|
return binaryMat;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Mat imageProxyToGrayscaleMat(ImageProxy imageProxy) {
|
||||||
|
// Step 1: Extract the image data from ImageProxy
|
||||||
|
ImageProxy.PlaneProxy[] planes = imageProxy.getPlanes();
|
||||||
|
ByteBuffer yBuffer = planes[0].getBuffer();
|
||||||
|
byte[] yData = new byte[yBuffer.remaining()];
|
||||||
|
yBuffer.get(yData);
|
||||||
|
|
||||||
|
// Step 2: Convert the image data to NV21 format
|
||||||
|
int width = imageProxy.getWidth();
|
||||||
|
int height = imageProxy.getHeight();
|
||||||
|
byte[] nv21Data = new byte[width * height * 3 / 2];
|
||||||
|
// Assuming the image format is YUV_420_888
|
||||||
|
System.arraycopy(yData, 0, nv21Data, 0, yData.length);
|
||||||
|
for (int i = yData.length; i < nv21Data.length; i += 2) {
|
||||||
|
nv21Data[i] = yData[i + 1];
|
||||||
|
nv21Data[i + 1] = yData[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Step 3: Create a grayscale Mat from the NV21 data
|
||||||
|
Mat grayscaleMat = new Mat(height, width, CvType.CV_8UC1);
|
||||||
|
grayscaleMat.put(0, 0, nv21Data);
|
||||||
|
|
||||||
|
return grayscaleMat;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset and copy Byte Buffer
|
|
||||||
buffer.rewind();
|
|
||||||
previousBuffer.rewind();
|
|
||||||
previousBuffer.put(buffer);
|
|
||||||
|
|
||||||
return changedPixelCount;
|
private static Mat thresholdContourArea(Mat inputMat, float areaThreshold){
|
||||||
|
List<MatOfPoint> contours = new ArrayList<>();
|
||||||
|
Mat hierarchy = new Mat();
|
||||||
|
Imgproc.findContours(inputMat, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
|
||||||
|
|
||||||
|
Mat outputMat = new Mat(inputMat.size(), inputMat.type(), new Scalar(0));
|
||||||
|
// Iterate over the contours and draw only the larger contours on the outputMat
|
||||||
|
for (MatOfPoint contour : contours) {
|
||||||
|
double contourArea = Imgproc.contourArea(contour);
|
||||||
|
if (contourArea > areaThreshold) {
|
||||||
|
Imgproc.drawContours(outputMat, Collections.singletonList(contour), 0, new Scalar(255), -1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Apply the outputMat as a mask to the dilatedImage
|
||||||
|
Mat maskedImage = new Mat();
|
||||||
|
inputMat.copyTo(maskedImage, outputMat);
|
||||||
|
return outputMat;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Mat dilateBinaryMat(Mat inputMat, Size kernelSize){
|
||||||
|
Mat dilatedMat = new Mat();
|
||||||
|
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, kernelSize);
|
||||||
|
Imgproc.dilate(inputMat, dilatedMat, kernel);
|
||||||
|
return dilatedMat;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int countNonZeroPixels(Mat inputImage) {
|
||||||
|
if (inputImage != null)
|
||||||
|
return Core.countNonZero(inputImage);
|
||||||
|
else
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private static void debugMat(Mat mat, ImageView imageView) {
|
||||||
|
if (imageView == null || mat == null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
Bitmap bitmap = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888);
|
||||||
|
Utils.matToBitmap(mat, bitmap);
|
||||||
|
|
||||||
|
// Display the bitmap in an ImageView
|
||||||
|
imageView.setImageBitmap(bitmap);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,61 @@
|
|||||||
package com.example.ueberwachungssystem;
|
package com.example.ueberwachungssystem;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
import androidx.appcompat.app.AppCompatActivity;
|
import androidx.appcompat.app.AppCompatActivity;
|
||||||
|
import androidx.camera.core.ExperimentalGetImage;
|
||||||
|
import androidx.camera.view.PreviewView;
|
||||||
|
|
||||||
import android.os.Bundle;
|
import android.os.Bundle;
|
||||||
|
import android.util.Log;
|
||||||
|
import android.view.View;
|
||||||
|
import android.widget.ImageView;
|
||||||
|
import android.widget.ToggleButton;
|
||||||
|
|
||||||
|
import com.example.ueberwachungssystem.Detection.DetectionReport;
|
||||||
|
import com.example.ueberwachungssystem.Detection.Detector;
|
||||||
|
import com.example.ueberwachungssystem.Detection.VideoDetector;
|
||||||
|
|
||||||
|
@ExperimentalGetImage
|
||||||
public class MainActivity extends AppCompatActivity {
|
public class MainActivity extends AppCompatActivity {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void onCreate(Bundle savedInstanceState) {
|
protected void onCreate(Bundle savedInstanceState) {
|
||||||
super.onCreate(savedInstanceState);
|
super.onCreate(savedInstanceState);
|
||||||
setContentView(R.layout.activity_main);
|
setContentView(R.layout.activity_main);
|
||||||
|
|
||||||
|
|
||||||
|
ImageView inputImageView = findViewById(R.id.inputImageView);
|
||||||
|
ImageView outputImageView = findViewById(R.id.outputImageView);
|
||||||
|
PreviewView previewView = findViewById(R.id.previewView);
|
||||||
|
|
||||||
|
|
||||||
|
VideoDetector vd = new VideoDetector(this);
|
||||||
|
//vd.setPreviewView(previewView);
|
||||||
|
vd.debugProcessing(inputImageView, outputImageView);
|
||||||
|
vd.setOnDetectionListener(new Detector.OnDetectionListener() {
|
||||||
|
@Override
|
||||||
|
public void onDetection(@NonNull DetectionReport detectionReport) {
|
||||||
|
Log.d("onDetection", detectionReport.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
vd.startDetection();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
ToggleButton toggleButton = findViewById(R.id.toggleButton);
|
||||||
|
toggleButton.setOnClickListener(new View.OnClickListener() {
|
||||||
|
@Override
|
||||||
|
public void onClick(View v) {
|
||||||
|
if (toggleButton.isChecked())
|
||||||
|
{
|
||||||
|
//vd.startDetection();
|
||||||
|
vd.startRecording();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
//vd.stopDetection();
|
||||||
|
vd.stopRecording();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,18 +1,38 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
xmlns:tools="http://schemas.android.com/tools"
|
xmlns:tools="http://schemas.android.com/tools"
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="match_parent"
|
android:layout_height="match_parent"
|
||||||
|
android:layout_gravity="center"
|
||||||
|
android:gravity="top"
|
||||||
|
android:orientation="vertical"
|
||||||
tools:context=".MainActivity">
|
tools:context=".MainActivity">
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:layout_width="wrap_content"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:text="Hello World!"
|
|
||||||
app:layout_constraintBottom_toBottomOf="parent"
|
|
||||||
app:layout_constraintEnd_toEndOf="parent"
|
|
||||||
app:layout_constraintStart_toStartOf="parent"
|
|
||||||
app:layout_constraintTop_toTopOf="parent" />
|
|
||||||
|
|
||||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
<androidx.camera.view.PreviewView
|
||||||
|
android:id="@+id/previewView"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:backgroundTint="@android:color/black"/>
|
||||||
|
|
||||||
|
<ToggleButton
|
||||||
|
android:id="@+id/toggleButton"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="ToggleButton" />
|
||||||
|
|
||||||
|
<ImageView
|
||||||
|
android:id="@+id/inputImageView"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
tools:srcCompat="@tools:sample/avatars" />
|
||||||
|
|
||||||
|
<ImageView
|
||||||
|
android:id="@+id/outputImageView"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
tools:srcCompat="@tools:sample/avatars" />
|
||||||
|
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
Reference in new issue
Block a user