xuxiuxi
2017-07-14 bcefcf7249692e61574438d3857e737c2fd29ca7
VisitFace/DemoForBsk/app/src/main/java/cn/com/basic/face/base/MainActivity.java
@@ -1,22 +1,25 @@
package cn.com.basic.face.base;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
@@ -25,7 +28,6 @@
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
@@ -38,6 +40,7 @@
import cn.com.basic.face.discern.common.CommonVariables;
import cn.com.basic.face.discern.query.item.SurveillanceQueryItem;
import cn.com.basic.face.fragment.AttenderRegisterFragment;
import cn.com.basic.face.fragment.SurveillanceFragment;
import cn.com.basic.face.service.SurveillanceMng;
import cn.com.basic.face.util.FileUtil;
@@ -47,13 +50,12 @@
import cn.com.basic.face.fragment.CheckInFragment;
import cn.com.basic.face.fragment.DeviceFragment;
import cn.com.basic.face.fragment.PhoneCallFragment;
import cn.com.basic.face.fragment.RegisterFragment;
import cn.com.basic.face.fragment.VisitorRegisterFragment;
import cn.com.basic.face.fragment.VisitFragment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -90,7 +92,8 @@
        int[] tabIcons = TabNameUtil.tabIcons;
        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),MainActivity.this);
        myFragmentPagerAdapter.addFragment(SurveillanceFragment.getInstance(), tabNamesList.get(0),tabIcons[0]);
        myFragmentPagerAdapter.addFragment(RegisterFragment.getInstance(), tabNamesList.get(1),tabIcons[1]);
//        myFragmentPagerAdapter.addFragment(VisitorRegisterFragment.getInstance(), tabNamesList.get(1),tabIcons[1]);
        myFragmentPagerAdapter.addFragment(AttenderRegisterFragment.getInstance(), tabNamesList.get(1),tabIcons[1]);
        myFragmentPagerAdapter.addFragment(CheckInFragment.getInstance(), tabNamesList.get(2),tabIcons[2]);
        myFragmentPagerAdapter.addFragment(PhoneCallFragment.getInstance(), tabNamesList.get(3),tabIcons[3]);
        myFragmentPagerAdapter.addFragment(VisitFragment.getInstance(), tabNamesList.get(4),tabIcons[4]);
@@ -108,9 +111,10 @@
                tab.getCustomView().setSelected(true);
            }
        }
        myThread = new MyThread();
        myThread.start();
        if (CommonVariables.ID_CARD) {
            myThread = new MyThread();
            myThread.start();
        }
    }
    public static MainActivity getInstance() {
@@ -256,7 +260,7 @@
    public Preview mPreview;
    public ProcessImageAndDrawResults mDraw;
    private final String database = "Memory50.dat";
    private final String help_text = "Luxand Face Recognition\n\nJust tap any detected face and name it. The app will recognize this face further. For best results, hold the device at arm's length. You may slowly rotate the head for the app to memorize you at multiple views. The app can memorize several persons. If a face is not recognized, tap and name it again.\n\nThe SDK is available for mobile developers: www.luxand.com/facesdk";
    private final String help_text = "help";
    public static float sDensity = 1.0f;
@@ -266,21 +270,14 @@
        if (CommonVariables.FACE_SERVER) {
            sDensity = getResources().getDisplayMetrics().scaledDensity;
            int res = FSDK.ActivateLibrary("bSB3NdbTnv/0eW/uhypSe6hDMtjZ76Sisw5NwcN+0sfahxOtoUW22el54e/M6cSG5/xsdVIorPgugbTIfoIIn7ltyw1QMSleNebVx/Xe8aRA8bP+aVDybjoWdW/0rDP9Pv7yqBzNXyuwjgsVhPB53VGP8oTirTSUP7PTzSwOEe0=");
            int res = 0;
            if (res != FSDK.FSDKE_OK) {
                mIsFailed = true;
                showErrorAndClose("FaceSDK activation failed", res);
                showErrorAndClose("failed", res);
            } else {
                FSDK.Initialize();
                // Hide the window title (it is done in manifest too)
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//z                requestWindowFeature(Window.FEATURE_NO_TITLE);
                // Lock orientation
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                // Camera layer and drawing layer
                mDraw = new ProcessImageAndDrawResults(this);
                mPreview = new Preview(this, mDraw);
                mDraw.mTracker = new FSDK.HTracker();
@@ -291,22 +288,17 @@
                        showErrorAndClose("Error creating tracker", res);
                    }
                }
                resetTrackerParameters();
                //this.getWindow().setBackgroundDrawable(new ColorDrawable()); //black background
                //setContentView(mPreview); //creates MainActivity contents
                //addContentView(mDraw, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                //addContentView(mDraw, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                // Menu
//                LayoutInflater inflater = (LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
//                View buttons = inflater.inflate(R.layout.bottom_menu, null );
//                buttons.findViewById(R.id.helpButton).setOnClickListener(this);
//                buttons.findViewById(R.id.clearButton).setOnClickListener(this);
//                addContentView(buttons, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//                addContentView(buttons, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            }
        }
    }
@@ -331,7 +323,7 @@
                            @Override public void onClick(DialogInterface dialogInterface, int j) {
                            }
                        })
                        .setCancelable(false) // cancel with button only
                        .setCancelable(false)
                        .show();
            }
        }
@@ -377,7 +369,7 @@
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                })
                .setCancelable(false) // cancel with button only
                .setCancelable(false)
                .show();
    }
@@ -392,7 +384,6 @@
    private void pauseProcessingFrames() {
        mDraw.mStopping = 1;
        // It is essential to limit wait time, because mStopped will not be set to 0, if no frames are feeded to mDraw
        for (int i=0; i<100; ++i) {
            if (mDraw.mStopped != 0) break;
            try { Thread.sleep(10); }
@@ -412,7 +403,6 @@
    public int x1, y1, x2, y2;
}
// Draw graphics on top of the video
class ProcessImageAndDrawResults extends View {
    public FSDK.HTracker mTracker;
@@ -485,7 +475,6 @@
        mPaintBlueTransparent.setColor(Color.BLUE);
        mPaintBlueTransparent.setTextSize(25);
        //mBitmap = null;
        mYUVData = null;
        mRGBData = null;
@@ -502,16 +491,13 @@
        if (mYUVData == null || mTouchedIndex != -1) {
            super.onDraw(canvas);
            return; //nothing to process or name is being entered now
            return;
        }
        int canvasWidth = canvas.getWidth();
        //int canvasHeight = canvas.getHeight();
        // Convert from YUV to RGB
        decodeYUV420SP(mRGBData, mYUVData, mImageWidth, mImageHeight);
        // Load image to FaceSDK
        FSDK.HImage Image = new FSDK.HImage();
        FSDK.FSDK_IMAGEMODE imagemode = new FSDK.FSDK_IMAGEMODE();
        imagemode.mode = FSDK.FSDK_IMAGEMODE.FSDK_IMAGE_COLOR_24BIT;
@@ -520,34 +506,31 @@
        FSDK.HImage RotatedImage = new FSDK.HImage();
        FSDK.CreateEmptyImage(RotatedImage);
//        FSDK.SaveImageToFile(Image, MainActivity.getInstance().getFilesDir().getAbsolutePath()+System.currentTimeMillis()+".jpg");
        //it is necessary to work with local variables (onDraw called not the time when mImageWidth,... being reassigned, so swapping mImageWidth and mImageHeight may be not safe)
        int ImageWidth = mImageWidth;
        //int ImageHeight = mImageHeight;
        if (rotated) {
            ImageWidth = mImageHeight;
            //ImageHeight = mImageWidth;
            FSDK.RotateImage90(Image, -1, RotatedImage);
        } else {
            FSDK.CopyImage(Image, RotatedImage);
        }
        FSDK.FreeImage(Image);
        // Save first frame to gallery to debug (e.g. rotation angle)
      /*
      if (!first_frame_saved) {
         first_frame_saved = true;
         String galleryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
         FSDK.SaveImageToFile(RotatedImage, galleryPath + "/first_frame.jpg"); //frame is rotated!
      }
      */
//        FSDK.TFacePosition fp11 = new FSDK.TFacePosition();
//        FSDK.DetectFace(RotatedImage, fp11);
        String surveillancePhotoName11 = "/storage/sdcard1/"+System.currentTimeMillis()+".jpg";
        FSDK.SaveImageToFile(Image, surveillancePhotoName11);
        FSDK.FreeImage(Image);
        long IDs[] = new long[MAX_FACES];
        long face_count[] = new long[1];
        FSDK.FeedFrame(mTracker, 0, RotatedImage, face_count, IDs);
//        FSDK.FreeImage(RotatedImage);
        System.out.println("face_count="+face_count[0]);
        faceLock.lock();
@@ -602,13 +585,20 @@
                nativeImg.size = nativeImg.image.length;
                SurveillanceQueryItem surveillanceQueryItem = new SurveillanceQueryItem();
                surveillanceQueryItem.setNativeImg(nativeImg);
                //surveillanceQueryItem.setBitmap(bitmap);
                nativeImg.st_track_id = 1;
                surveillanceQueryItem.setStTrackId(nativeImg.st_track_id);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inMutable = true;
                Bitmap bmp = BitmapFactory.decodeByteArray(nativeImg.image, 0, nativeImg.image.length, options);
                Canvas canvas1 = new Canvas(bmp);
                surveillanceQueryItem.setBitmap(bmp);
                surveillanceQueryItem.setWidth("100");
                surveillanceQueryItem.setHeight("100");
                bitmapList.add(surveillanceQueryItem);
                SurveillanceMng.getInstance().addBitmap(bitmapList, nativeImg.image, 0, CommonVariables.Camera.IN+"");
                SurveillanceMng.getInstance().addBitmap(bitmapList, nativeImg.image, 0, CommonVariables.Camera.IN+"", nativeImg.image);
            }
        }
@@ -617,7 +607,6 @@
        int shift = (int)(22 * MainActivity.sDensity);
        // Mark and name faces
        for (int i=0; i<face_count[0]; ++i) {
            canvas.drawRect(mFacePositions[i].x1, mFacePositions[i].y1, mFacePositions[i].x2, mFacePositions[i].y2, mPaintBlueTransparent);
@@ -636,7 +625,7 @@
        }
        super.onDraw(canvas);
    } // end onDraw method
    }
    @Override
@@ -665,7 +654,6 @@
                        mTouchedIndex = i;
                        // requesting name on tapping the face
                        final EditText input = new EditText(mContext);
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                        builder.setMessage("Enter person's name" )
@@ -683,7 +671,7 @@
                                        mTouchedIndex = -1;
                                    }
                                })
                                .setCancelable(false) // cancel with button only
                                .setCancelable(false)
                                .show();
                        break;
@@ -720,12 +708,8 @@
            }
        }
    }
} // end of ProcessImageAndDrawResults class
}
// Show video from camera and pass frames to ProcessImageAndDraw class
class Preview extends SurfaceView implements SurfaceHolder.Callback {
    Context mContext;
    SurfaceHolder mHolder;
@@ -738,28 +722,28 @@
        mContext = context;
        mDraw = draw;
        //Install a SurfaceHolder.Callback so we get notified when the underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    //SurfaceView callback
    public void surfaceCreated(SurfaceHolder holder) {
        mFinished = false;
        // Find the ID of the camera
        int cameraId = 0;
        boolean frontCameraFound = false;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
            Camera.getCameraInfo(i, cameraInfo);
            //if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                cameraId = i;
                frontCameraFound = true;
            }
        }
        //If authorisation not granted for camera
        if (ContextCompat.checkSelfPermission(MainActivity.getInstance(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
            //ask for authorisation
            ActivityCompat.requestPermissions(MainActivity.getInstance(), new String[]{Manifest.permission.CAMERA}, 50);
        if (frontCameraFound) {
            mCamera = Camera.open(cameraId);
@@ -767,17 +751,16 @@
            mCamera = Camera.open();
        }
        try {
            mCamera.setPreviewDisplay(holder);
            // Preview callback used whenever new viewfinder frame is available
            mCamera.setPreviewCallback(new Camera.PreviewCallback() {
                public void onPreviewFrame(byte[] data, Camera camera) {
                    if ( (mDraw == null) || mFinished )
                        return;
                    if (mDraw.mYUVData == null) {
                        // Initialize the draw-on-top companion
                        Camera.Parameters params = camera.getParameters();
                        mDraw.mImageWidth = params.getPreviewSize().width;
                        mDraw.mImageHeight = params.getPreviewSize().height;
@@ -785,7 +768,6 @@
                        mDraw.mYUVData = new byte[data.length];
                    }
                    // Pass YUV data to draw-on-top companion
                    System.arraycopy(data, 0, mDraw.mYUVData, 0, data.length);
                    mDraw.invalidate();
                }
@@ -808,11 +790,7 @@
        }
    }
    //SurfaceView callback
    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        // Because the CameraDevice object is not a shared resource, it's very
        // important to release it when the activity is paused.
        mFinished = true;
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
@@ -822,31 +800,23 @@
        }
    }
    //SurfaceView callback, configuring camera
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        if (mCamera == null) return;
        // Now that the size is known, set up the camera parameters and begin
        // the preview.
        Camera.Parameters parameters = mCamera.getParameters();
        //Keep uncommented to work correctly on phones:
        //This is an undocumented although widely known feature
      /**/
        if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
            parameters.set("orientation", "portrait");
            mCamera.setDisplayOrientation(90); // For Android 2.2 and above
            mCamera.setDisplayOrientation(90);
            mDraw.rotated = true;
        } else {
            parameters.set("orientation", "landscape");
            mCamera.setDisplayOrientation(0); // For Android 2.2 and above
            mCamera.setDisplayOrientation(0);
        }
      /**/
        // choose preview size closer to 640x480 for optimal performance
        List<Camera.Size> supportedSizes = parameters.getSupportedPreviewSizes();
        int width = 0;
        int height = 0;
        System.out.println("surfaceChanged");
        for (Camera.Size s: supportedSizes) {
            if ((width - 640)*(width - 640) + (height - 480)*(height - 480) >
                    (s.width - 640)*(s.width - 640) + (s.height - 480)*(s.height - 480)) {
@@ -855,12 +825,10 @@
            }
        }
        //try to set preferred parameters
        try {
            if (width*height > 0) {
                parameters.setPreviewSize(width, height);
            }
            //parameters.setPreviewFrameRate(10);
            parameters.setSceneMode(Camera.Parameters.SCENE_MODE_PORTRAIT);
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            mCamera.setParameters(parameters);
@@ -884,5 +852,5 @@
            this.invalidate();
        }
    }
} // end of Preview class
}