안 드 로 이 드 카메라 실시 간 미리보기 실시 간 처리,얼굴 인식 예시
미리 보기 작업 은 네티즌 들 이 공유 하 는 코드 입 니 다.저 는 Surface View 를 계승 하 는 Camera Surface View 에 프레임 감청 사건 을 추 가 했 습 니 다.매번 미리 보기 감청 전 5 개의 데이터 프레임 을 처리 하여 얼굴 인식 을 하고 있 습 니 다.
디렉토리 관계 먼저 보기
사용자 정의 컨트롤 CameraSurfaceView.java사용자 정의 인터페이스 방법 CameraInterface.java
package com.centaur.camera.preview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.centaur.camera.camera.CameraInterface;
import java.io.ByteArrayOutputStream;
/**
* Created by Tianchaoxiong on 2017/1/16.
*/
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback{
private static final int FACENUM = 5;
private static final String TAG = "yanzi";
CameraInterface mCameraInterface;
Context mContext;
SurfaceHolder mSurfaceHolder;
private boolean isFinish;
// bitmap
Bitmap [] bitmaps = new Bitmap[5];
int number = 0;//
OnFaceCollectListener onFaceCollectListener = null;
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mSurfaceHolder = getHolder();
mSurfaceHolder.setFormat(PixelFormat.TRANSPARENT);//translucent transparent
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mSurfaceHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
Log.i(TAG, "surfaceCreated...");
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
Log.i(TAG, "surfaceChanged...");
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
Log.i(TAG, "surfaceDestroyed...");
CameraInterface.getInstance().doStopCamera();
}
public SurfaceHolder getSurfaceHolder(){
return mSurfaceHolder;
}
/**
*
*/
public static interface OnFaceCollectListener {
/**
* face
* @param bitmaps
*/
void OnFaceCollected(Bitmap[] bitmaps);
/**
* face
* @param isStart
*/
void OnFaceCollectStart(boolean isStart);
}
/**
*
* @param onFaceCollectListener
*/
public void setOnFaceCollectListener(OnFaceCollectListener onFaceCollectListener){
if(onFaceCollectListener!=null){
this.onFaceCollectListener = onFaceCollectListener;
}
}
/***
*
* @param bytes
* @param camera
*/
@Override
public void onPreviewFrame(byte[] bytes, Camera camera) {
if(number<FACENUM){
//
//
if(onFaceCollectListener!=null){
onFaceCollectListener.OnFaceCollectStart(true);
// byte bitmap
bitmaps[number] = byte2bitmap(bytes,camera);
Log.d("ceshiTian","******** "+number+" ************");
number = number+1;
if(number==5){
Log.d("ceshiTian","******** 5 ************");
//
onFaceCollectListener.OnFaceCollected(bitmaps);
}
}
}else {
//
onFaceCollectListener.OnFaceCollectStart(false);
onFaceCollectListener.OnFaceCollected(null);
}
}
private Bitmap byte2bitmap(byte[] bytes, Camera camera) {
Bitmap bitmap = null;
Camera.Size size = camera.getParameters().getPreviewSize(); //
final int w = size.width; //
final int h = size.height;
final YuvImage image = new YuvImage(bytes, ImageFormat.NV21, w, h,
null);
ByteArrayOutputStream os = new ByteArrayOutputStream(bytes.length);
if (!image.compressToJpeg(new Rect(0, 0, w, h), 100, os)) {
return null;
}
byte[] tmp = os.toByteArray();
bitmap = BitmapFactory.decodeByteArray(tmp, 0, tmp.length);
Matrix matrix = new Matrix();
matrix.setRotate(-90);
bitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
return bitmap;
}
}
CameraInterface.java
package com.centaur.camera.camera;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import com.centaur.camera.util.CamParaUtil;
import com.centaur.camera.util.ImageUtil;
import com.centaur.util.FileUtils;
import java.io.IOException;
import java.util.List;
/**
* Created by Tianchaoxiong on 2017/1/16.
*/
public class CameraInterface {
private static final String TAG = "Tianchaoxiong";
private Camera mCamera;
private Camera.Parameters mParams;
private boolean isPreviewing = false;
private float mPreviwRate = -1f;
private static CameraInterface mCameraInterface;
public interface CamOpenOverCallback {
public void cameraHasOpened();
}
private CameraInterface() {
}
public static synchronized CameraInterface getInstance() {
if (mCameraInterface == null) {
mCameraInterface = new CameraInterface();
}
return mCameraInterface;
}
/**
* Camera
*
* @param callback
*/
public void doOpenCamera(CamOpenOverCallback callback) {
Log.i(TAG, "Camera open....");
mCamera = Camera.open(1);
Log.i(TAG, "Camera open over....");
callback.cameraHasOpened();
}
/**
*
*
* @param holder
* @param previewRate
*/
public void doStartPreview(SurfaceHolder holder, float previewRate, Camera.PreviewCallback previewCallback) {
Log.i(TAG, "doStartPreview...");
if (isPreviewing) {
mCamera.stopPreview();
return;
}
if (mCamera != null) {
mParams = mCamera.getParameters();
mParams.setPictureFormat(PixelFormat.JPEG);//
//
CamParaUtil.getInstance().printSupportPictureSize(mParams);
CamParaUtil.getInstance().printSupportPreviewSize(mParams);
// PreviewSize PictureSize
Camera.Size pictureSize = CamParaUtil.getInstance().getPropPictureSize(
mParams.getSupportedPictureSizes(), previewRate, 800);
mParams.setPictureSize(pictureSize.width, pictureSize.height);
Camera.Size previewSize = CamParaUtil.getInstance().getPropPreviewSize(
mParams.getSupportedPreviewSizes(), previewRate, 800);
mParams.setPreviewSize(previewSize.width, previewSize.height);
mCamera.setDisplayOrientation(90);
CamParaUtil.getInstance().printSupportFocusMode(mParams);
List<String> focusModes = mParams.getSupportedFocusModes();
if (focusModes.contains("continuous-video")) {
mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
mCamera.setParameters(mParams); //
try {
mCamera.setPreviewDisplay(holder);
mCamera.setPreviewCallback(previewCallback);
mCamera.startPreview();//
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isPreviewing = true;
mPreviwRate = previewRate;
mParams = mCamera.getParameters(); // get
Log.i(TAG, " :PreviewSize--With = " + mParams.getPreviewSize().width
+ "Height = " + mParams.getPreviewSize().height);
Log.i(TAG, " :PictureSize--With = " + mParams.getPictureSize().width
+ "Height = " + mParams.getPictureSize().height);
}
}
/**
* , Camera
*/
public void doStopCamera() {
if (null != mCamera) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
isPreviewing = false;
mPreviwRate = -1f;
mCamera.release();
mCamera = null;
}
}
/**
*
*/
public void doTakePicture() {
if (isPreviewing && (mCamera != null)) {
Log.d("FileUtils", " 111");
mCamera.takePicture(mShutterCallback, null, mJpegPictureCallback);
}
}
/* */
Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback()
// , “ ” 。 。
{
public void onShutter() {
// TODO Auto-generated method stub
Log.i(TAG, "myShutterCallback:onShutter...");
}
};
/* Camera.PictureCallback mRawCallback = new Camera.PictureCallback()
// , null
{
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
Log.i(TAG, "myRawCallback:onPictureTaken...");
}
};*/
Camera.PictureCallback mJpegPictureCallback = new Camera.PictureCallback()
// jpeg ,
{
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("FileUtils", " 222");
// TODO Auto-generated method stub
Log.i(TAG, "myJpegCallback:onPictureTaken...");
Bitmap b = null;
if (null != data) {
b = BitmapFactory.decodeByteArray(data, 0, data.length);//data ,
mCamera.stopPreview();
isPreviewing = false;
Log.d("FileUtils", " 333");
}
// sdcard
if (null != b) {
Log.d("FileUtils", " 444");
// FOCUS_MODE_CONTINUOUS_VIDEO) ,myParam.set("rotation", 90) 。
// ,
Log.d("FileUtils", " ");
Bitmap rotaBitmap = ImageUtil.getRotateBitmap(b, -90.0f);
FileUtils.savePaiZhaoBitmap(rotaBitmap);
}
}
};
}
CameraActivity
package com.centaur.camera.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import com.centaur.camera.camera.CameraInterface;
import com.centaur.camera.preview.CameraSurfaceView;
import com.centaur.camera.util.DisplayUtil;
import com.centaur.testutil.R;
import com.centaur.testutil.ShowPic;
import com.centaur.util.DetecteSDK;
import com.centaur.util.DetecteSeeta;
public class CameraActivity extends AppCompatActivity implements CameraSurfaceView.OnFaceCollectListener, CameraInterface.CamOpenOverCallback{
private static final String TAG = "CameraActivity";
private float recLen = 0;
long te;
float previewRate = -1f;
DetecteSDK detecteSDK;
DetecteSeeta detecteSeeta;
Bitmap bmp;
Bitmap bitmapfianl;
private ImageButton shutterBtn;
private TextView textView;
private CameraSurfaceView surfaceView = null;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Thread openThread = new Thread(){
@Override
public void run() {
CameraInterface.getInstance().doOpenCamera(CameraActivity.this);
}
};
openThread.start();
te = System.currentTimeMillis();
setContentView(R.layout.activity_camera);
initView();
initViewParams();
surfaceView.setOnFaceCollectListener(this);
shutterBtn.setOnClickListener(new BtnListeners());
TimeHandler.postDelayed(TimeRunnable, 500);
}
/**
*
* activity interface
*/
@Override
public void cameraHasOpened() {
SurfaceHolder holder = surfaceView.getSurfaceHolder();
CameraInterface.getInstance().doStartPreview(holder, previewRate,surfaceView );
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
CameraInterface.getInstance().doStopCamera();
Log.d("RunTime", "onDestroy:time:"+te);
TimeHandler.removeCallbacks(TimeRunnable);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
CameraInterface.getInstance().doStopCamera();
te = System.currentTimeMillis()-te;
Log.d("RunTime", "onPause:time:"+te);
TimeHandler.removeCallbacks(TimeRunnable);
}
Handler TimeHandler = new Handler();
Runnable TimeRunnable = new Runnable() {
@Override
public void run() {
recLen+=500;
textView.setText(" :" + recLen/1000+" ");
TimeHandler.postDelayed(this, 500);
}
};
private void initView(){
surfaceView = (CameraSurfaceView)findViewById(R.id.camera_surfaceview);
shutterBtn = (ImageButton)findViewById(R.id.btn_shutter);
textView = (TextView) findViewById(R.id.time);
}
private void initViewParams(){
ViewGroup.LayoutParams params = surfaceView.getLayoutParams();
Point p = DisplayUtil.getScreenMetrics(this);
params.width = p.x;
params.height = p.y;
previewRate = DisplayUtil.getScreenRate(this); //
surfaceView.setLayoutParams(params);
// ImageButton 120dip×120dip, 64×64
ViewGroup.LayoutParams p2 = shutterBtn.getLayoutParams();
p2.width = DisplayUtil.dip2px(this, 80);
p2.height = DisplayUtil.dip2px(this, 80);
shutterBtn.setLayoutParams(p2);
}
/**
*
* @param bitmaps
*/
@Override
public void OnFaceCollected(Bitmap[] bitmaps) {
}
/**
*
* @param isStart
*/
@Override
public void OnFaceCollectStart(boolean isStart) {
if(isStart){
Log.d("CameraActivity"," ");
}
}
private class BtnListeners implements View.OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btn_shutter:
CameraInterface.getInstance().doTakePicture();
Intent intent =new Intent(CameraActivity.this, ShowPic.class);
// /FaceDetection/useso/Pictures/Tmp/tmp.png
String FolderPath = "/FaceDetection/useso/Pictures/Tmp/tmp.png";
String path = Environment.getExternalStorageDirectory()+FolderPath;
intent.putExtra("picpath",path);
startActivity(intent);
finish();
break;
default:break;
}
}
}
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.