Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.opencv.android.Utils;
- import org.opencv.core.Core;
- import org.opencv.core.Mat;
- import org.opencv.highgui.Highgui;
- import org.opencv.highgui.VideoCapture;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.Canvas;
- import android.util.Log;
- import android.view.SurfaceHolder;
- import android.view.SurfaceView;
- public class CameraViewOpenCV extends SurfaceView implements SurfaceHolder.Callback, Runnable {
- private static final String TAG = "Sample::SurfaceView";
- private SurfaceHolder mHolder;
- private VideoCapture mCamera;
- private Mat mRgba;
- public CameraViewOpenCV(Context context) {
- super(context);
- mHolder = getHolder();
- mHolder.addCallback(this);
- }
- public void surfaceChanged(SurfaceHolder _holder, int format, int width, int height) {
- Log.i(TAG, "surfaceCreated");
- if (mCamera != null && mCamera.isOpened()) {
- mCamera.set(Highgui.CV_CAP_PROP_FRAME_WIDTH, 640);
- mCamera.set(Highgui.CV_CAP_PROP_FRAME_HEIGHT, 480);
- }
- }
- public void surfaceCreated(SurfaceHolder holder) {
- Log.i(TAG, "surfaceCreated");
- mRgba = new Mat();
- mCamera = new VideoCapture(Highgui.CV_CAP_ANDROID);
- if(mCamera.isOpened()){
- (new Thread(this)).start();
- } else {
- mRgba.release();
- mCamera.release();
- mCamera = null;
- Log.e(TAG, "Failed to open native camera");
- }
- }
- public void surfaceDestroyed(SurfaceHolder holder) {
- Log.i(TAG, "surfaceDestroyed");
- if (mCamera != null) {
- mCamera.release();
- mCamera = null;
- }
- }
- public double timet(double l){
- return ((Core.getTickCount() - l)/Core.getTickFrequency()) * 1000;
- }
- public void run() {
- int i = 0;
- double d, total = 0;
- while (true) {
- d = Core.getTickCount();
- Bitmap bmp = null;
- if (mCamera == null)
- break;
- if (!mCamera.grab()) {
- Log.e(TAG, "mCamera.grab() failed");
- break;
- }
- mCamera.retrieve(mRgba, Highgui.CV_CAP_ANDROID_COLOR_FRAME_RGBA);
- bmp = Bitmap.createBitmap(mRgba.cols(), mRgba.rows(), Bitmap.Config.ARGB_8888);
- Utils.matToBitmap(mRgba, bmp);
- if (bmp != null) {
- Canvas canvas = mHolder.lockCanvas();
- if (canvas != null) {
- canvas.drawBitmap(bmp, (canvas.getWidth() - bmp.getWidth()) / 2, (canvas.getHeight() - bmp.getHeight()) / 2, null);
- mHolder.unlockCanvasAndPost(canvas);
- }
- bmp.recycle();
- // measure frame rate
- total += timet(d);
- if((i++ % 100) == 0){
- Log.w("Opencv Camera", "Average frame time: " + total/100 + "ms" + " ##Frame Rate:" + (100000/(total)) + "fps");
- total = 0;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement