комментирование строки "cameraource.start ();" внутри try-улова появляется предварительный просмотр, но я не могу этого сделать, потому что детектор лица не работает. Пожалуйста, помогите ... моя основная активность. java is
package com.example.android.drownsinessdetector;
import android.Manifest;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.Tracker;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
private static final String TAG = "Video";
int camIdx;
CameraSource cameraSource;
TextView textView;
private Camera mCamera;
private CameraPreview mPreview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera=getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = findViewById(R.id.videoView);
preview.addView(mPreview);
Camera.getCameraInfo(camIdx, cameraInfo);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mCamera.setDisplayOrientation(90);
textView = findViewById(R.id.textView);
createCameraSource();
}
private Camera getCameraInstance() {
int inf = Camera.CameraInfo.CAMERA_FACING_FRONT;
Camera c = null;
try {
c = Camera.open(inf);
} catch (Exception e){
}
return c;
}
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
this.mCamera=camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Log.d(TAG,"camera preview class");
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
//This class will use google vision api to detect eyes
private class EyesTracker extends Tracker<Face> {
private final float THRESHOLD = 0.75f;
private EyesTracker(){}
@Override
public void onUpdate(Detector.Detections<Face> detections, Face face) {
if (face.getIsLeftEyeOpenProbability() > THRESHOLD || face.getIsRightEyeOpenProbability() > THRESHOLD) {
Log.i(TAG, "onUpdate: Eyes Detected");
showStatus("Eyes Detected and open");
}
else {
showStatus("Eyes Detected and closed");
}
}
@Override
public void onMissing(Detector.Detections<Face> detections) {
super.onMissing(detections);
showStatus("Face Not Detected yet!");
}
@Override
public void onDone() {
super.onDone();
}
}
private class FaceTrackerFactory implements MultiProcessor.Factory<Face> {
private FaceTrackerFactory() {
}
@Override
public Tracker<Face> create(Face face) {
return new EyesTracker();
}
}
public void createCameraSource() {
FaceDetector detector = new FaceDetector.Builder(this)
.setTrackingEnabled(true)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.setMode(FaceDetector.FAST_MODE)
.build();
detector.setProcessor(new MultiProcessor.Builder(new FaceTrackerFactory()).build());
cameraSource = new CameraSource.Builder(this, detector)
.setRequestedPreviewSize(1024, 768)
.setFacing(CameraSource.CAMERA_FACING_FRONT)
.setRequestedFps(30.0f)
.build();
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
cameraSource.start();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void showStatus(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(message);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
my макет xml файл
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<FrameLayout
android:id="@+id/videoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0.75"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:orientation="vertical"/>
<EditText
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="63dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="15dp"
android:clickable="false"
android:text="face_not_found"
android:textSize="20sp" />
мой файл манифеста
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.drownsinessdetector">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />[enter image description here][1]
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
я могу видеть только черный экран вместо Предварительный просмотр камеры. но детектор глаз и лица работает должным образом. Он показывает сообщение о состоянии, когда глаза открыты или нет. Я также хочу показать предварительный просмотр камеры.