Browse Source

Working Video Detector + Recorder WIP: Use Case logic

bk_video_test
Bastian Kohler 1 year ago
parent
commit
76442888f7

+ 0
- 1
app/src/main/AndroidManifest.xml View File



<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" /> <uses-permission android:name="android.permission.RECORD_AUDIO" />


<application <application

+ 4
- 0
app/src/main/java/com/example/ueberwachungssystem/Detection/Detector.java View File

}.start(); }.start();
} }


public void extendDetection(){
this.extendDetection = 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();



+ 109
- 38
app/src/main/java/com/example/ueberwachungssystem/Detection/VideoDetector.java View File

import androidx.camera.core.Preview; import androidx.camera.core.Preview;
import androidx.camera.core.VideoCapture; import androidx.camera.core.VideoCapture;
import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LifecycleOwner;
private final Context context; private final Context context;


// Permission handling // Permission handling
private static final int CAMERA_PERMISSION_REQUEST_CODE = 3691;
private static final int PERMISSION_REQUEST_CODE = 3691;


// Camera Provider // Camera Provider
private ProcessCameraProvider cameraProvider; private ProcessCameraProvider cameraProvider;
private final ImageAnalysis imageAnalysis; private final ImageAnalysis imageAnalysis;
private final VideoCapture videoCapture; private final VideoCapture videoCapture;
private final Preview preview;


// Logic // Logic
private boolean isDetectionRunning = false;
private boolean isDetecting = false;
private boolean isRecording = false;
private boolean allowReportViolation = false; private boolean allowReportViolation = false;


// Image Processing // Image Processing
private ImageView outputImageView = null; private ImageView outputImageView = null;




// Recording
private final String outputName = "video.mp4";


// Parameters // Parameters
private static final float ALARM_THRESHOLD = 0.5f; // Percent of pixels changed private static final float ALARM_THRESHOLD = 0.5f; // Percent of pixels changed
private static final long START_DELAY = 5000; // milliseconds
private static final long START_DELAY = 20000; // milliseconds
private static final android.util.Size IMAGE_RES = new android.util.Size(640, 480); private static final android.util.Size IMAGE_RES = new android.util.Size(640, 480);




private enum UseCase {
ImageAnalysis,
Preview,
VideoCapture
};


/** Constructor */ /** Constructor */
public VideoDetector(Context context) { public VideoDetector(Context context) {
super(); super();
this.context = context; this.context = context;
this.imageAnalysis = setupImageAnalysis(); this.imageAnalysis = setupImageAnalysis();
this.videoCapture = setupVideoCapture(); this.videoCapture = setupVideoCapture();
this.preview = new Preview.Builder().build();
} }


/** Get State of the Detector */ /** Get State of the Detector */
public boolean isRunning() { public boolean isRunning() {
return isDetectionRunning;
return isDetecting;
} }




@Override @Override
public void startDetection() { public void startDetection() {
// Check States // Check States
if (isDetectionRunning)
if (isDetecting)
return;
// Return On Request Permissions
if (!hasPermissions()) {
getPermissions();
return; return;
if (!isCameraAccessAllowed()) {
getCameraAccess();
} }
// Open CV startup check // Open CV startup check
if (!OpenCVLoader.initDebug()) { if (!OpenCVLoader.initDebug()) {
return; return;
} else } else
Log.d("OpenCV", "OpenCV loaded Successfully!"); Log.d("OpenCV", "OpenCV loaded Successfully!");

// Request Camera Provider
// 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();
bindCameraProvider(cameraProvider);
isDetectionRunning = true;
} catch (ExecutionException | InterruptedException e) {
// No errors need to be handled for this Future. This should never be reached.
}
isDetecting = true;
bindCameraProvider(UseCase.ImageAnalysis);
} catch (ExecutionException | InterruptedException e) {}
}, ContextCompat.getMainExecutor(context)); }, ContextCompat.getMainExecutor(context));
} }


/** Stops the Video Detection */ /** Stops the Video Detection */
@Override @Override
public void stopDetection() { public void stopDetection() {
if (!isDetectionRunning || imageAnalysis == null)
if (!isDetecting || imageAnalysis == null)
return; return;
cameraProvider.unbind(imageAnalysis); cameraProvider.unbind(imageAnalysis);
isDetectionRunning = false;
cameraProvider.unbind(preview);
isDetecting = false;
allowReportViolation = false; allowReportViolation = false;
} }


/** Permission handling */ /** Permission handling */
private boolean isCameraAccessAllowed() {
return ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
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 getCameraAccess() {
if (!isCameraAccessAllowed())
ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
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) */ /** Binds the Luminosity Analyzer (configure and run Analysis) */
private void bindCameraProvider(@NonNull ProcessCameraProvider cameraProvider) {
// Create Preview
//Preview preview = new Preview.Builder().build();
private void bindCameraProvider(UseCase useCase) {
// Specify which Camera to use // Specify which Camera to use
CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build(); CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();

cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, imageAnalysis);

// Delay till violation is allowed
startViolationTimer();
if(useCase == UseCase.ImageAnalysis && !cameraProvider.isBound(videoCapture)) {
cameraProvider.unbindAll();
cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, imageAnalysis, preview);
startViolationTimer();
}
if(useCase == UseCase.VideoCapture) {
if(cameraProvider.isBound(imageAnalysis)) {
cameraProvider.unbindAll();
cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, imageAnalysis, videoCapture);
} else {
cameraProvider.unbindAll();
cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, videoCapture);
}
}
} }




@Override @Override
public void onTick(long millisUntilFinished) { public void onTick(long millisUntilFinished) {
} }

@Override @Override
public void onFinish() { public void onFinish() {
allowReportViolation = true; allowReportViolation = true;
@SuppressLint("RestrictedApi") @SuppressLint("RestrictedApi")
private VideoCapture setupVideoCapture() { private VideoCapture setupVideoCapture() {
return new VideoCapture.Builder() return new VideoCapture.Builder()
.setVideoFrameRate(30)
.setTargetRotation(Surface.ROTATION_0) .setTargetRotation(Surface.ROTATION_0)
.build(); .build();
} }


@SuppressLint("RestrictedApi")
public void startRecording() {
// Check States
if (isRecording){
extendDetection();
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) {
Toast.makeText(context, "recording saved", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(int videoCaptureError, @NonNull String message, @Nullable Throwable cause) {
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);
if (isDetecting)
bindCameraProvider(UseCase.ImageAnalysis);
}


/** Process Image to be used for Motion Detection */ /** Process Image to be used for Motion Detection */
private Mat processImage(Image image){ private Mat processImage(Image image){

// Image Transformation // Image Transformation
Mat imageMat = OpenCVHelper.extractYChannel(image); Mat imageMat = OpenCVHelper.extractYChannel(image);


processed = OpenCVHelper.dilateBinaryMat(processed, new Size(3,3)); processed = OpenCVHelper.dilateBinaryMat(processed, new Size(3,3));
processed = OpenCVHelper.thresholdContourArea(processed, 500); processed = OpenCVHelper.thresholdContourArea(processed, 500);



// Output // Output
previousImage = preprocessed.clone(); previousImage = preprocessed.clone();
// Show Output Image // Show Output Image
return processed; return processed;
} }


public void debugProcessing(ImageView inputImageView, ImageView outputImageView){
public void debugProcessing(@NonNull ImageView inputImageView, @NonNull ImageView outputImageView){
this.inputImageView = inputImageView; this.inputImageView = inputImageView;
this.outputImageView = outputImageView; this.outputImageView = outputImageView;
} }




public void setPreviewView(@NonNull PreviewView previewView) {
// Create Preview
if (this.preview != null)
this.preview.setSurfaceProvider(previewView.getSurfaceProvider());
}







+ 7
- 12
app/src/main/java/com/example/ueberwachungssystem/MainActivity.java View File

import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.ExperimentalGetImage; import androidx.camera.core.ExperimentalGetImage;
import androidx.camera.view.PreviewView;


import android.os.Bundle; import android.os.Bundle;
import android.view.View; import android.view.View;
@ExperimentalGetImage @ExperimentalGetImage
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {


private static final int CAMERA_PERMISSION_REQUEST_CODE = 101;


@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);


ImageView inputImageView = findViewById(R.id.inputImageView); ImageView inputImageView = findViewById(R.id.inputImageView);
ImageView outputImageView = findViewById(R.id.outputImageView); ImageView outputImageView = findViewById(R.id.outputImageView);
PreviewView previewView = findViewById(R.id.previewView);




VideoDetector vd = new VideoDetector(this); VideoDetector vd = new VideoDetector(this);
vd.setPreviewView(previewView);
vd.debugProcessing(inputImageView, outputImageView); vd.debugProcessing(inputImageView, outputImageView);
vd.setOnDetectionListener(new Detector.OnDetectionListener(){
@Override
public void onDetection(@NonNull DetectionReport detectionReport) {
detectionReport.log("OnDetection");
}
});






public void onClick(View v) { public void onClick(View v) {
if (toggleButton.isChecked()) if (toggleButton.isChecked())
{ {
vd.startDetection();
//vd.startDetection();
vd.startRecording();
} }
else { else {
vd.stopDetection();
//vd.stopDetection();
vd.stopRecording();
} }
} }
}); });

} }
} }

+ 1
- 1
app/src/main/res/layout/activity_main.xml View File

<androidx.camera.view.PreviewView <androidx.camera.view.PreviewView
android:id="@+id/previewView" android:id="@+id/previewView"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_height="wrap_content"
android:backgroundTint="@android:color/black"/> android:backgroundTint="@android:color/black"/>


<ToggleButton <ToggleButton

Loading…
Cancel
Save