Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e01e23eccd | ||
|
|
a493bafb79 | ||
|
|
aed079377f | ||
|
|
bff6abbd29 | ||
|
|
5d31f0bb46 | ||
|
|
ea0e88ed89 | ||
|
|
7dee124378 | ||
|
|
0ee1446cbc | ||
|
|
bc5227ba4f | ||
|
|
4185cb5200 | ||
|
|
0a3600d0d6 | ||
|
|
9b2d57ad37 | ||
|
|
847e90f5ac | ||
|
|
ab41217f0e | ||
|
|
e088b0afa3 | ||
|
|
493fa8ca83 | ||
|
|
6954d38143 | ||
|
|
057c7fc139 |
@@ -42,6 +42,8 @@ dependencies {
|
||||
def opencv_version = "4.5.3.0"
|
||||
implementation "com.quickbirdstudios:opencv:${opencv_version}"
|
||||
|
||||
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
|
||||
|
||||
|
||||
// Required for CameraX
|
||||
def camerax_version = "1.2.2"
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<service android:name=".Detection.DetectorService"/>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.example.ueberwachungssystem.Detection;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.MediaPlayer;
|
||||
import android.media.MediaRecorder;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class AudioRecorder {
|
||||
private final Context context;
|
||||
private MediaRecorder mediaRecorder = null;
|
||||
private boolean isRecording = false;
|
||||
private File outputDir; // Default: in app files directory
|
||||
|
||||
|
||||
public AudioRecorder (Context context) {
|
||||
this.context = context;
|
||||
this.outputDir = context.getFilesDir();
|
||||
}
|
||||
|
||||
public void startRecording() {
|
||||
// Handle logic
|
||||
if (outputDir == null)
|
||||
return;
|
||||
if (isRecording)
|
||||
return;
|
||||
isRecording = true;
|
||||
|
||||
// Setup Audio Recorder for output Format: 3GP
|
||||
mediaRecorder = new MediaRecorder();
|
||||
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
|
||||
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
|
||||
mediaRecorder.setOutputFile(outputDir + "/" + generateFileName() + ".3gp");
|
||||
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
|
||||
try {
|
||||
mediaRecorder.prepare();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
mediaRecorder.start();
|
||||
}
|
||||
|
||||
public void stopRecording() {
|
||||
if (mediaRecorder != null) {
|
||||
mediaRecorder.stop();
|
||||
mediaRecorder.reset();
|
||||
mediaRecorder.release();
|
||||
mediaRecorder = null;
|
||||
isRecording = false;
|
||||
Toast.makeText(context, "audio recording saved", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isRecording(){
|
||||
return isRecording;
|
||||
}
|
||||
|
||||
public void setOutputDir(File outputDir) {
|
||||
this.outputDir = outputDir;
|
||||
}
|
||||
|
||||
private String generateFileName(){
|
||||
// Get the current timestamp
|
||||
LocalDateTime currentTime = LocalDateTime.now();
|
||||
// Define the format for the timestamp
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
|
||||
// Return the timestamp as a string
|
||||
return currentTime.format(formatter);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.example.ueberwachungssystem.Detection;
|
||||
import android.os.CountDownTimer;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.camera.core.ExperimentalGetImage;
|
||||
|
||||
|
||||
abstract public class Detector {
|
||||
@@ -11,7 +12,7 @@ abstract public class Detector {
|
||||
private boolean extendViolation = false;
|
||||
|
||||
// Countdown parameters
|
||||
private final int COUNTDOWN_TIME = 5000; // milliseconds
|
||||
private final int COUNTDOWN_TIME = 10000; // milliseconds
|
||||
private final int COUNTDOWN_POLLING_TIME = 100; // milliseconds
|
||||
|
||||
/** Constructor - takes context of current activity */
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.example.ueberwachungssystem.Detection;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Binder;
|
||||
import android.os.IBinder;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.camera.core.ExperimentalGetImage;
|
||||
import androidx.lifecycle.LifecycleService;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
@ExperimentalGetImage
|
||||
public class DetectorService extends LifecycleService {
|
||||
public ServiceBinder serviceBinder = new ServiceBinder();
|
||||
private DetectorService.OnDetectionListener listener;
|
||||
private boolean isServiceRunning = false;
|
||||
|
||||
VideoDetector videoDetector = null;
|
||||
AudioRecorder audioRecorder = null;
|
||||
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
if (isServiceRunning)
|
||||
return START_NOT_STICKY;
|
||||
|
||||
|
||||
// Setup Service classes:
|
||||
videoDetector = new VideoDetector(this);
|
||||
videoDetector.setOnDetectionListener(new Detector.OnDetectionListener() {
|
||||
@Override
|
||||
public void onDetection(@NonNull DetectionReport detectionReport) {
|
||||
passToServiceListener(detectionReport);
|
||||
}
|
||||
});
|
||||
|
||||
audioRecorder = new AudioRecorder(this);
|
||||
|
||||
|
||||
|
||||
isServiceRunning = true;
|
||||
return super.onStartCommand(intent, flags, startId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
isServiceRunning = false;
|
||||
}
|
||||
|
||||
/** Service methods */
|
||||
public class ServiceBinder extends Binder {
|
||||
public DetectorService getBoundService() {
|
||||
// Return an instance of the TestService
|
||||
return DetectorService.this;
|
||||
}
|
||||
}
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
super.onBind(intent);
|
||||
return serviceBinder;
|
||||
}
|
||||
|
||||
|
||||
/** Video Detection */
|
||||
public void startVideoDetection() {
|
||||
if(videoDetector != null)
|
||||
videoDetector.startDetection();
|
||||
}
|
||||
public void stopVideoDetection() {
|
||||
if(videoDetector != null)
|
||||
videoDetector.stopDetection();
|
||||
}
|
||||
public boolean isVideoDetectionRunning() {
|
||||
if(videoDetector != null)
|
||||
return videoDetector.isDetecting();
|
||||
return false;
|
||||
}
|
||||
public void debugVideoProcessing(ImageView input, ImageView output) {
|
||||
if(videoDetector != null)
|
||||
videoDetector.debugProcessing(input, output);
|
||||
}
|
||||
|
||||
/** Audio Detection */
|
||||
public void startAudioDetection() {
|
||||
|
||||
}
|
||||
public void stopAudioDetection() {
|
||||
|
||||
}
|
||||
|
||||
/** Motion Detection */
|
||||
public void startMotionDetection() {
|
||||
|
||||
}
|
||||
public void stopMotionDetection() {
|
||||
|
||||
}
|
||||
|
||||
/** Video Recording */
|
||||
public void startVideoRecording() {
|
||||
if(videoDetector != null)
|
||||
videoDetector.startRecording();
|
||||
}
|
||||
public void stopVideoRecording() {
|
||||
if(videoDetector != null)
|
||||
videoDetector.stopRecording();
|
||||
}
|
||||
public boolean isVideoRecordingRunning() {
|
||||
if(videoDetector != null)
|
||||
return videoDetector.isRecording();
|
||||
return false;
|
||||
}
|
||||
public void setVideoRecordingDir(File outputDir) {
|
||||
if (videoDetector != null)
|
||||
videoDetector.setOutputDir(outputDir);
|
||||
}
|
||||
|
||||
/** Audio Recording */
|
||||
public void startAudioRecording() {
|
||||
if(audioRecorder != null)
|
||||
audioRecorder.startRecording();
|
||||
}
|
||||
public void stopAudioRecording() {
|
||||
if(audioRecorder != null)
|
||||
audioRecorder.stopRecording();
|
||||
}
|
||||
public boolean isAudioRecordingRunning() {
|
||||
if(videoDetector != null)
|
||||
return audioRecorder.isRecording();
|
||||
return false;
|
||||
}
|
||||
public void setAudioRecordingDir(File outputDir) {
|
||||
if (audioRecorder != null)
|
||||
audioRecorder.setOutputDir(outputDir);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/** pass Detection Report to Service Detection Listener and trigger it */
|
||||
public void passToServiceListener(DetectionReport detectionReport) {
|
||||
if (listener != null) {
|
||||
listener.onDetection(detectionReport);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** On Detection Listener - runs when violation is reported */
|
||||
public interface OnDetectionListener {
|
||||
void onDetection(@NonNull DetectionReport detectionReport);
|
||||
}
|
||||
public void setOnDetectionListener(@NonNull DetectorService.OnDetectionListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.example.ueberwachungssystem.Detection;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.media.Image;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.camera.core.ExperimentalGetImage;
|
||||
import androidx.camera.core.ImageProxy;
|
||||
|
||||
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.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@ExperimentalGetImage
|
||||
public class OpenCVHelper {
|
||||
|
||||
/** OpenCV helper methods **/
|
||||
public static Mat addGaussianBlur(Mat inputMat, Size kernelSize){
|
||||
Mat outputMat = new Mat();
|
||||
Imgproc.GaussianBlur(inputMat, outputMat, kernelSize, 0);
|
||||
return outputMat;
|
||||
}
|
||||
|
||||
public static Mat addBlur(Mat inputMat, Size kernelSize){
|
||||
Mat outputMat = new Mat();
|
||||
Imgproc.blur(inputMat, outputMat, kernelSize);
|
||||
return outputMat;
|
||||
}
|
||||
|
||||
public static Mat extractYChannel(@NonNull ImageProxy imgProxy) {
|
||||
Image img = imgProxy.getImage();
|
||||
|
||||
assert img != null;
|
||||
ByteBuffer yBuffer = img.getPlanes()[0].getBuffer();
|
||||
byte[] yData = new byte[yBuffer.remaining()];
|
||||
yBuffer.get(yData);
|
||||
|
||||
Mat yMat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC1);
|
||||
yMat.put(0, 0, yData);
|
||||
|
||||
return yMat;
|
||||
}
|
||||
|
||||
public static Mat thresholdPixels(Mat inputMat, Mat previousImage, int threshold){
|
||||
Mat diffImage = new Mat();
|
||||
Core.absdiff(inputMat, previousImage, diffImage);
|
||||
Mat binaryMat = new Mat();
|
||||
Imgproc.threshold(diffImage, binaryMat, threshold, 255, Imgproc.THRESH_BINARY);
|
||||
return binaryMat;
|
||||
}
|
||||
|
||||
|
||||
public 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;
|
||||
}
|
||||
|
||||
public 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;
|
||||
}
|
||||
|
||||
public static int countNonZeroPixels(Mat inputImage) {
|
||||
if (inputImage != null)
|
||||
return Core.countNonZero(inputImage);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
public 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);
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,15 @@ package com.example.ueberwachungssystem.Detection;
|
||||
|
||||
import android.Manifest;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.ImageFormat;
|
||||
import android.media.Image;
|
||||
import android.os.CountDownTimer;
|
||||
import android.util.Log;
|
||||
import android.view.Display;
|
||||
import android.view.Surface;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.Toast;
|
||||
|
||||
@@ -31,20 +31,12 @@ import androidx.lifecycle.LifecycleOwner;
|
||||
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.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
|
||||
@@ -57,18 +49,14 @@ import java.util.concurrent.ExecutionException;
|
||||
|
||||
@ExperimentalGetImage
|
||||
public class VideoDetector extends Detector {
|
||||
|
||||
// Calling Activity
|
||||
private final Context context;
|
||||
|
||||
// Permission handling
|
||||
private static final int PERMISSION_REQUEST_CODE = 3691;
|
||||
|
||||
// Camera Provider
|
||||
private ProcessCameraProvider cameraProvider;
|
||||
private final ImageAnalysis imageAnalysis;
|
||||
private final VideoCapture videoCapture;
|
||||
private final Preview preview;
|
||||
private ImageAnalysis imageAnalysis;
|
||||
private VideoCapture videoCapture;
|
||||
//private Preview preview;
|
||||
|
||||
// Logic
|
||||
private boolean isDetecting = false;
|
||||
@@ -82,23 +70,18 @@ public class VideoDetector extends Detector {
|
||||
private ImageView inputImageView = null;
|
||||
private ImageView outputImageView = null;
|
||||
|
||||
|
||||
// Recording
|
||||
private final String outputName = "video.mp4";
|
||||
// Recorder
|
||||
private File outputDir; // Default: in app files directory
|
||||
|
||||
|
||||
// Parameters
|
||||
private static final float ALARM_THRESHOLD = 0.5f; // Percent of pixels changed
|
||||
private static final long START_DELAY = 20000; // milliseconds
|
||||
private static final float ALARM_THRESHOLD = 0f; // Percent of pixels changed
|
||||
private static final float AREA_THRESHOLD = 10f;
|
||||
private static final int DILATE_ITERATIONS = 2;
|
||||
private static final float 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) {
|
||||
@@ -106,13 +89,17 @@ public class VideoDetector extends Detector {
|
||||
this.context = context;
|
||||
this.imageAnalysis = setupImageAnalysis();
|
||||
this.videoCapture = setupVideoCapture();
|
||||
this.preview = new Preview.Builder().build();
|
||||
this.outputDir = context.getFilesDir();
|
||||
//this.preview = new Preview.Builder().build();
|
||||
}
|
||||
|
||||
/** Get State of the Detector */
|
||||
public boolean isRunning() {
|
||||
/** Get States */
|
||||
public boolean isDetecting() {
|
||||
return isDetecting;
|
||||
}
|
||||
public boolean isRecording(){
|
||||
return isRecording;
|
||||
}
|
||||
|
||||
|
||||
/** Starts the Video Detection */
|
||||
@@ -121,11 +108,8 @@ public class VideoDetector extends Detector {
|
||||
// Check States
|
||||
if (isDetecting)
|
||||
return;
|
||||
// Return On Request Permissions
|
||||
if (!hasPermissions()) {
|
||||
getPermissions();
|
||||
return;
|
||||
}
|
||||
// Configure Image Analysis
|
||||
imageAnalysis = setupImageAnalysis();
|
||||
// Open CV startup check
|
||||
if (!OpenCVLoader.initDebug()) {
|
||||
Log.e("OpenCV", "Unable to load OpenCV!");
|
||||
@@ -138,11 +122,52 @@ public class VideoDetector extends Detector {
|
||||
try {
|
||||
cameraProvider = cameraProviderFuture.get();
|
||||
isDetecting = true;
|
||||
bindCameraProvider(UseCase.ImageAnalysis);
|
||||
bindCameraProvider();
|
||||
} catch (ExecutionException | InterruptedException e) {}
|
||||
}, ContextCompat.getMainExecutor(context));
|
||||
// Disable Violation Calling for Setup Time
|
||||
startViolationTimer(START_DELAY);
|
||||
}
|
||||
|
||||
startViolationTimer();
|
||||
/** Starts the Recorder */
|
||||
@SuppressLint("RestrictedApi")
|
||||
public void startRecording() {
|
||||
// Check States
|
||||
if (isRecording){
|
||||
return;
|
||||
}
|
||||
|
||||
videoCapture = setupVideoCapture();
|
||||
|
||||
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context);
|
||||
cameraProviderFuture.addListener(() -> {
|
||||
try {
|
||||
cameraProvider = cameraProviderFuture.get();
|
||||
isRecording = true;
|
||||
bindCameraProvider();
|
||||
|
||||
File vidFile = new File(context.getFilesDir() + "/" + generateFileName() + ".mp4");
|
||||
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, "video recording saved", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
@Override
|
||||
public void onError(int videoCaptureError, @NonNull String message, @Nullable Throwable cause) {
|
||||
isRecording = false;
|
||||
Toast.makeText(context, "video recording failed", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch (ExecutionException | InterruptedException ignored) {}
|
||||
}, ContextCompat.getMainExecutor(context));
|
||||
}
|
||||
|
||||
/** Stops the Video Detection */
|
||||
@@ -155,29 +180,136 @@ public class VideoDetector extends Detector {
|
||||
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);
|
||||
/** Stops the Recording */
|
||||
@SuppressLint("RestrictedApi")
|
||||
public void stopRecording(){
|
||||
if(!isRecording)
|
||||
return;
|
||||
|
||||
videoCapture.stopRecording();
|
||||
cameraProvider.unbind(videoCapture);
|
||||
isRecording = false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** Binds the Luminosity Analyzer (configure and run Analysis) */
|
||||
private void bindCameraProvider(UseCase useCase) {
|
||||
/** Bind Camera Provider */
|
||||
private void bindCameraProvider() {
|
||||
// Specify which Camera to use
|
||||
CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
|
||||
cameraProvider.unbindAll();
|
||||
cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, imageAnalysis, videoCapture);
|
||||
}
|
||||
|
||||
/** Setup Use Cases */
|
||||
private ImageAnalysis setupImageAnalysis() {
|
||||
// Configure and create Image Analysis
|
||||
ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
|
||||
builder.setTargetResolution(IMAGE_RES);
|
||||
builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
|
||||
builder.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888);
|
||||
builder.setTargetRotation(Surface.ROTATION_90);
|
||||
ImageAnalysis imageAnalysis = builder.build();
|
||||
// Set Analyzer
|
||||
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(context), imageProxy -> {
|
||||
if (imageProxy.getFormat() == ImageFormat.YUV_420_888) {
|
||||
Image image = imageProxy.getImage();
|
||||
assert image != null;
|
||||
|
||||
// Violation Handling
|
||||
Mat processed = processImage(imageProxy);
|
||||
|
||||
int n = OpenCVHelper.countNonZeroPixels(processed);
|
||||
int pixelCount = image.getWidth() * image.getHeight();
|
||||
float percentChanged = (float) n / pixelCount;
|
||||
|
||||
// Violation Condition
|
||||
if (percentChanged * 100 > ALARM_THRESHOLD) {
|
||||
if (allowReportViolation)
|
||||
reportViolation("Video", percentChanged);
|
||||
}
|
||||
}
|
||||
imageProxy.close();
|
||||
});
|
||||
return imageAnalysis;
|
||||
}
|
||||
|
||||
@SuppressLint("RestrictedApi")
|
||||
private VideoCapture setupVideoCapture() {
|
||||
int rotation = getDisplayRotation();
|
||||
return new VideoCapture.Builder()
|
||||
.setTargetRotation(rotation)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** 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));
|
||||
// Set Previous Image
|
||||
if (previousImage == null) {
|
||||
previousImage = preprocessed;
|
||||
return null;
|
||||
}
|
||||
// Process Image
|
||||
Mat processed = preprocessed.clone();
|
||||
processed = OpenCVHelper.thresholdPixels(processed, previousImage, 25);
|
||||
|
||||
for(int i = 0; i < DILATE_ITERATIONS; i++)
|
||||
processed = OpenCVHelper.dilateBinaryMat(processed, new Size(3,3));
|
||||
|
||||
processed = OpenCVHelper.thresholdContourArea(processed, AREA_THRESHOLD);
|
||||
// Output
|
||||
previousImage = preprocessed.clone();
|
||||
// Show Output Image
|
||||
if (outputImageView != null)
|
||||
OpenCVHelper.debugMat(processed, outputImageView);
|
||||
return processed;
|
||||
}
|
||||
|
||||
|
||||
/** Debug input and result of processing */
|
||||
public void debugProcessing(@NonNull ImageView inputImageView, @NonNull ImageView outputImageView){
|
||||
this.inputImageView = inputImageView;
|
||||
this.outputImageView = outputImageView;
|
||||
}
|
||||
|
||||
/**
|
||||
private void setPreviewView(@NonNull PreviewView previewView) {
|
||||
// Create Preview
|
||||
if (this.preview != null)
|
||||
this.preview.setSurfaceProvider(previewView.getSurfaceProvider());
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
/** Generate File Name */
|
||||
private String generateFileName(){
|
||||
// Get the current timestamp
|
||||
LocalDateTime currentTime = LocalDateTime.now();
|
||||
// Define the format for the timestamp
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
|
||||
// Return the timestamp as a string
|
||||
return currentTime.format(formatter);
|
||||
}
|
||||
|
||||
|
||||
/** Get current Display Rotation */
|
||||
private int getDisplayRotation() {
|
||||
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
|
||||
Display display = windowManager.getDefaultDisplay();
|
||||
return display.getRotation();
|
||||
}
|
||||
|
||||
/** Start delay until Violation Report is allowed */
|
||||
private void startViolationTimer() {
|
||||
private void startViolationTimer(float setupTime) {
|
||||
new CountDownTimer((long) (START_DELAY), 100) {
|
||||
@Override
|
||||
public void onTick(long millisUntilFinished) {
|
||||
@@ -189,253 +321,7 @@ public class VideoDetector extends Detector {
|
||||
}.start();
|
||||
}
|
||||
|
||||
|
||||
private ImageAnalysis setupImageAnalysis() {
|
||||
// Configure and create Image Analysis
|
||||
ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
|
||||
builder.setTargetResolution(IMAGE_RES);
|
||||
builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
|
||||
builder.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888);
|
||||
ImageAnalysis imageAnalysis = builder.build();
|
||||
// Set Analyzer
|
||||
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(context), imageProxy -> {
|
||||
if (imageProxy.getFormat() == ImageFormat.YUV_420_888) {
|
||||
Image image = imageProxy.getImage();
|
||||
assert image != null;
|
||||
|
||||
// Violation Handling
|
||||
Mat processed = processImage(imageProxy);
|
||||
int n = OpenCVHelper.countNonZeroPixels(processed);
|
||||
int pixelCount = image.getWidth() * image.getHeight();
|
||||
float percentChanged = (float) n / pixelCount;
|
||||
|
||||
// Violation Condition
|
||||
if (percentChanged * 100 > ALARM_THRESHOLD) {
|
||||
if (allowReportViolation)
|
||||
reportViolation("Video", n);
|
||||
}
|
||||
}
|
||||
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
|
||||
if (this.preview != null)
|
||||
this.preview.setSurfaceProvider(previewView.getSurfaceProvider());
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static class OpenCVHelper{
|
||||
private OpenCVHelper() {}
|
||||
|
||||
/** OpenCV helper methods **/
|
||||
private static Mat addGaussianBlur(Mat inputMat, Size kernelSize){
|
||||
Mat outputMat = new Mat();
|
||||
Imgproc.GaussianBlur(inputMat, outputMat, kernelSize, 0);
|
||||
return outputMat;
|
||||
}
|
||||
|
||||
private static Mat addBlur(Mat inputMat, Size kernelSize){
|
||||
Mat outputMat = new Mat();
|
||||
Imgproc.blur(inputMat, outputMat, kernelSize);
|
||||
return outputMat;
|
||||
}
|
||||
|
||||
private static Mat extractYChannel(@NonNull ImageProxy imgProxy) {
|
||||
Image img = imgProxy.getImage();
|
||||
|
||||
assert img != null;
|
||||
ByteBuffer yBuffer = img.getPlanes()[0].getBuffer();
|
||||
byte[] yData = new byte[yBuffer.remaining()];
|
||||
yBuffer.get(yData);
|
||||
|
||||
Mat yMat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC1);
|
||||
yMat.put(0, 0, yData);
|
||||
|
||||
return yMat;
|
||||
}
|
||||
|
||||
private static Mat thresholdPixels(Mat inputMat, Mat previousImage, int threshold){
|
||||
Mat diffImage = new Mat();
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
}
|
||||
public void setOutputDir(File outputDir) {
|
||||
this.outputDir = outputDir;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import android.view.View;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.ToggleButton;
|
||||
|
||||
import com.example.ueberwachungssystem.Detection.AudioRecorder;
|
||||
import com.example.ueberwachungssystem.Detection.DetectionReport;
|
||||
import com.example.ueberwachungssystem.Detection.Detector;
|
||||
import com.example.ueberwachungssystem.Detection.VideoDetector;
|
||||
@@ -29,33 +30,50 @@ public class MainActivity extends AppCompatActivity {
|
||||
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();
|
||||
PermissionHandler permissionHandler = new PermissionHandler(this);
|
||||
|
||||
|
||||
permissionHandler.getPermissions();
|
||||
|
||||
ToggleButton toggleButton = findViewById(R.id.toggleButton);
|
||||
toggleButton.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (toggleButton.isChecked())
|
||||
{
|
||||
//vd.startDetection();
|
||||
vd.startRecording();
|
||||
if (permissionHandler.hasPermissions()) {
|
||||
AudioRecorder audioRecorder = new AudioRecorder(this);
|
||||
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());
|
||||
}
|
||||
else {
|
||||
//vd.stopDetection();
|
||||
vd.stopRecording();
|
||||
});
|
||||
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.stopDetection();
|
||||
vd.startRecording();
|
||||
audioRecorder.startRecording();
|
||||
}
|
||||
else {
|
||||
//vd.stopDetection();
|
||||
vd.stopRecording();
|
||||
audioRecorder.stopRecording();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.example.ueberwachungssystem;
|
||||
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
public class PermissionHandler {
|
||||
private final Context context;
|
||||
private static final int PERMISSION_REQUEST_CODE = 23409;
|
||||
private static final String[] permissions = new String[]{
|
||||
android.Manifest.permission.CAMERA,
|
||||
android.Manifest.permission.RECORD_AUDIO
|
||||
};
|
||||
|
||||
public PermissionHandler(Context context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public boolean hasPermissions() {
|
||||
boolean permissionState = true;
|
||||
for (String permission: permissions) {
|
||||
permissionState = permissionState && ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
return permissionState;
|
||||
}
|
||||
|
||||
public void getPermissions() {
|
||||
if (!hasPermissions())
|
||||
ActivityCompat.requestPermissions((Activity) context, permissions, PERMISSION_REQUEST_CODE);
|
||||
}
|
||||
|
||||
public void showPermissionToast() {
|
||||
if (hasPermissions())
|
||||
Toast.makeText(context, "permissions available", Toast.LENGTH_SHORT).show();
|
||||
else
|
||||
Toast.makeText(context, "permissions missing", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
@@ -24,15 +24,18 @@
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/inputImageView"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
tools:srcCompat="@tools:sample/avatars" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/outputImageView"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
tools:srcCompat="@tools:sample/avatars" />
|
||||
|
||||
<androidx.camera.view.PreviewView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content" />
|
||||
|
||||
</LinearLayout>
|
||||
Reference in New Issue
Block a user