如何在捕获的照片 android 上进行人脸检测?

Posted

技术标签:

【中文标题】如何在捕获的照片 android 上进行人脸检测?【英文标题】:How can I make a face detection on a captured photo android? 【发布时间】:2018-03-19 20:48:34 【问题描述】:

我正在尝试检测自动拍摄的照片上的人脸,但它不起作用。捕获图片后,我将其发送到 ImageView,然后尝试从他们那里获取并进行面部检测。但是有错误,位图需要R.drawble,我给R.id。我不知道用什么 我是新手

public class MainActivity extends AppCompatActivity 
public static int cameraID = 0;
public static boolean isBlack = true;
public static ImageView image;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    image = (ImageView) findViewById(R.id.imgView);
    Button btfront=(Button) findViewById(R.id.frontButton);
    btfront.setOnClickListener(new View.OnClickListener()
    

        @Override
        public void onClick(View v) 
            onFrontClick(v);
            facedetection(v);


        

    );


public void onFrontClick(View v)
    RadioButton rdbBlack = (RadioButton) findViewById(R.id.rdb_black);
    if(rdbBlack.isChecked())
        isBlack = true;
    else
        isBlack = false;
    
    cameraID = 1;
    Intent i = new Intent(MainActivity.this,CameraView.class);
    startActivityForResult(i, 999);





public void onBackClick(View v)
    RadioButton rdbBlack = (RadioButton) findViewById(R.id.rdb_black);
    if(rdbBlack.isChecked())
        isBlack = true;
    else
        isBlack = false;
    
    cameraID = 0;
    Intent i = new Intent(MainActivity.this,CameraView.class);
    startActivityForResult(i, 999);

public void facedetection(View v)

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inMutable=true;
    Bitmap myBitmap = BitmapFactory.decodeResource(
            getApplicationContext().getResources(),
            R.id.imgView,
            options);
    Paint myRectPaint = new Paint();
    myRectPaint.setStrokeWidth(5);
    myRectPaint.setColor(Color.RED);
    myRectPaint.setStyle(Paint.Style.STROKE);
    Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565);
    Canvas tempCanvas = new Canvas(tempBitmap);
    tempCanvas.drawBitmap(myBitmap, 0, 0, null);
    FaceDetector faceDetector = new
            FaceDetector.Builder(getApplicationContext()).setTrackingEnabled(false)
            .build();
    if(!faceDetector.isOperational())
        new AlertDialog.Builder(v.getContext()).setMessage("Could not set up the face detector!").show();
        return;
    

    Frame frame = new Frame.Builder().setBitmap(myBitmap).build();
    SparseArray<Face> faces = faceDetector.detect(frame);
    for(int j=0; j<faces.size(); j++) 
        Face thisFace = faces.valueAt(j);
        float x1 = thisFace.getPosition().x;
        float y1 = thisFace.getPosition().y;
        float x2 = x1 + thisFace.getWidth();
        float y2 = y1 + thisFace.getHeight();
        tempCanvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, myRectPaint);
    
    image.setImageDrawable(new BitmapDrawable(getResources(),tempBitmap));

这是我拍摄照片的班级

public class CameraView extends Activity implements SurfaceHolder.Callback, OnClickListener
        private static final String TAG = "CameraTest";
        Camera mCamera;
        boolean mPreviewRunning = false;
    @SuppressWarnings("deprecation")
    public void onCreate(Bundle icicle)
        super.onCreate(icicle);
        Log.e(TAG, "onCreate");

        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.cameraview);
        ImageView img = (ImageView) findViewById(R.id.blankImage);

        if(MainActivity.isBlack)
            img.setBackgroundResource(android.R.color.black);
        else
            img.setBackgroundResource(android.R.color.white);

        mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        mSurfaceView.setOnClickListener(this);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
        super.onRestoreInstanceState(savedInstanceState);
    


    Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() 

        public void onPictureTaken(byte[] data, Camera camera) 
            // TODO Auto-generated method stub
            if (data != null)
                //Intent mIntent = new Intent();
                //mIntent.putExtra("image",imageData);

                mCamera.stopPreview();
                mPreviewRunning = false;
                mCamera.release();

                 try
                     BitmapFactory.Options opts = new BitmapFactory.Options();
                     Bitmap bitmap= BitmapFactory.decodeByteArray(data, 0, data.length,opts);
                     bitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, false);
                     int width = bitmap.getWidth();
                     int height = bitmap.getHeight();
                     int newWidth = 300;
                     int newHeight = 300;

                     // calculate the scale - in this case = 0.4f
                     float scaleWidth = ((float) newWidth) / width;
                     float scaleHeight = ((float) newHeight) / height;

                     // createa matrix for the manipulation
                     Matrix matrix = new Matrix();
                     // resize the bit map
                     matrix.postScale(scaleWidth, scaleHeight);
                     // rotate the Bitmap
                     matrix.postRotate(-90);
                     Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                             width, height, matrix, true);
                     MainActivity.image.setImageBitmap(resizedBitmap);

                 catch(Exception e)
                     e.printStackTrace();
                 
                //StoreByteImage(mContext, imageData, 50,"ImageName");
                //setResult(FOTO_MODE, mIntent);
                setResult(585);
                finish();
                   
        
    ;

    protected void onResume()
        Log.e(TAG, "onResume");
        super.onResume();
    

    protected void onSaveInstanceState(Bundle outState)
        super.onSaveInstanceState(outState);
    

    protected void onStop()
        Log.e(TAG, "onStop");
        super.onStop();
    

    @TargetApi(9)
    public void surfaceCreated(SurfaceHolder holder)
        Log.e(TAG, "surfaceCreated");
        mCamera = Camera.open(MainActivity.cameraID);
    

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) 
        Log.e(TAG, "surfaceChanged");

        // XXX stopPreview() will crash if preview is not running
        if (mPreviewRunning)
            mCamera.stopPreview();
        

        Camera.Parameters p = mCamera.getParameters();
        p.setPreviewSize(300, 300);

        if(MainActivity.cameraID == 0)
            String stringFlashMode = p.getFlashMode();
            if (stringFlashMode.equals("torch"))
                    p.setFlashMode("on"); // Light is set off, flash is set to normal 'on' mode
            else
                    p.setFlashMode("torch");
        

        mCamera.setParameters(p);
        try
            mCamera.setPreviewDisplay(holder);
        catch (Exception e)
            // TODO Auto-generated catch block
            e.printStackTrace();
        
        mCamera.startPreview();
        mPreviewRunning = true;
        mCamera.takePicture(null, mPictureCallback, mPictureCallback);
    

    public void surfaceDestroyed(SurfaceHolder holder) 
        Log.e(TAG, "surfaceDestroyed");
        //mCamera.stopPreview();
        //mPreviewRunning = false;
        //mCamera.release();
    

    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;

    public void onClick(View v) 
        // TODO Auto-generated method stub
        mCamera.takePicture(null, mPictureCallback, mPictureCallback);
    


【问题讨论】:

【参考方案1】:

@Lefteris 如果您正在查看它的转换

ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

【讨论】:

以上是关于如何在捕获的照片 android 上进行人脸检测?的主要内容,如果未能解决你的问题,请参考以下文章

Android人脸检测[重复]

MLkit 人脸检测不适用于 android 的前置摄像头

如何在 Android 中检测到人脸后将图像下载到图库?

Android自动裁剪相机捕获的图像

照片或真人脸 如何使用 Android 相机进行检查

使用位图时,Android MLKit 人脸检测未检测到人脸