Commit 898320a0 authored by Alexander Smorkalov's avatar Alexander Smorkalov Committed by Andrey Kamaev

Code clean up.

parent c64ee44c
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>15-puzzle</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.opencv.samples.puzzle15"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.CAMERA" required="false"/>
<uses-feature android:name="android.hardware.camera" required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" required="false"/>
<uses-sdk android:minSdkVersion="8"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Puzzle15Activity"
android:label="@string/title_activity_puzzle15"
android:configChanges = "keyboardHidden|orientation" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
\ No newline at end of file
<resources>
<string name="app_name">15-puzzle</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_puzzle15">Puzzle15Activity</string>
<string name="menu_toggle_tile_numbers">Show/hide tile numbers</string>
<string name="menu_start_new_game">Start new game</string>
</resources>
\ No newline at end of file
<resources>
<style name="AppTheme" parent="android:Theme.Light" />
</resources>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>OpenCV Sample - 15-puzzle</name>
<name>15-puzzle</name>
<comment></comment>
<projects>
</projects>
......
#Wed Jun 29 04:36:40 MSD 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.source=1.5
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.opencv.samples.puzzle15"
android:versionCode="21"
android:versionName="2.1">
android:versionCode="1"
android:versionName="1.0" >
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="puzzle15Activity"
<uses-permission android:name="android.permission.CAMERA" required="false"/>
<uses-feature android:name="android.hardware.camera" required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" required="false"/>
<uses-sdk android:minSdkVersion="8"/>
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".Puzzle15Activity"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation">
android:configChanges = "keyboardHidden|orientation" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<supports-screens android:resizeable="true"
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true" />
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>
</manifest>
\ No newline at end of file
set(sample example-15-puzzle)
add_android_project(${sample} "${CMAKE_CURRENT_SOURCE_DIR}" LIBRARY_DEPS ${OpenCV_BINARY_DIR} SDK_TARGET 11 ${ANDROID_SDK_TARGET})
if(TARGET ${sample})
add_dependencies(opencv_android_examples ${sample})
endif()
......@@ -3,10 +3,9 @@
android:layout_width="match_parent"
android:layout_height="match_parent" >
<org.opencv.framework.OpenCvNativeCameraView
<org.opencv.framework.OpenCvJavaCameraView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/puzzle_activity_surface_view"
/>
android:id="@+id/puzzle_activity_surface_view" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">OCV 15 Puzzle</string>
<string name="menu_toggle_tile_numbers">Show/hide tile numbers</string>
<string name="menu_start_new_game">Start new game</string>
</resources>
\ No newline at end of file
......@@ -5,7 +5,7 @@ import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.framework.OpenCvCameraBridgeViewBase.CvCameraViewListener;
import org.opencv.framework.OpenCvNativeCameraView;
import org.opencv.framework.OpenCvJavaCameraView;
import android.os.Bundle;
import android.app.Activity;
......@@ -20,7 +20,7 @@ public class Puzzle15Activity extends Activity implements CvCameraViewListener,
private static final String TAG = "Sample::Puzzle15::Activity";
private OpenCvNativeCameraView mOpenCvCameraView;
private OpenCvJavaCameraView mOpenCvCameraView;
private Puzzle15Processor mPuzzle15;
private int mGameWidth;
......@@ -54,7 +54,7 @@ public class Puzzle15Activity extends Activity implements CvCameraViewListener,
setContentView(R.layout.activity_puzzle15);
mOpenCvCameraView = (OpenCvNativeCameraView) findViewById(R.id.puzzle_activity_surface_view);
mOpenCvCameraView = (OpenCvJavaCameraView) findViewById(R.id.puzzle_activity_surface_view);
mOpenCvCameraView.setCvCameraViewListener(this);
mPuzzle15 = new Puzzle15Processor();
mPuzzle15.prepareNewGame();
......
package org.opencv.samples.puzzle15;
import java.util.List;
import org.opencv.core.Size;
import org.opencv.highgui.VideoCapture;
import org.opencv.highgui.Highgui;
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 abstract class SampleCvViewBase extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private static final String TAG = "OCVSample::BaseView";
private SurfaceHolder mHolder;
private VideoCapture mCamera;
public SampleCvViewBase(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
Log.i(TAG, "Instantiated new " + this.getClass());
}
public synchronized boolean openCamera() {
Log.i(TAG, "Opening Camera");
mCamera = new VideoCapture(Highgui.CV_CAP_ANDROID);
if (!mCamera.isOpened()) {
releaseCamera();
Log.e(TAG, "Can't open native camera");
return false;
}
return true;
}
public synchronized void releaseCamera() {
Log.i(TAG, "Releasing Camera");
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
public synchronized void setupCamera(int width, int height) {
if (mCamera != null && mCamera.isOpened()) {
Log.i(TAG, "Setup Camera - " + width + "x" + height);
List<Size> sizes = mCamera.getSupportedPreviewSizes();
int mFrameWidth = width;
int mFrameHeight = height;
// selecting optimal camera preview size
{
double minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - height) < minDiff) {
mFrameWidth = (int) size.width;
mFrameHeight = (int) size.height;
minDiff = Math.abs(size.height - height);
}
}
}
mCamera.set(Highgui.CV_CAP_PROP_FRAME_WIDTH, mFrameWidth);
mCamera.set(Highgui.CV_CAP_PROP_FRAME_HEIGHT, mFrameHeight);
}
}
public void surfaceChanged(SurfaceHolder _holder, int format, int width, int height) {
Log.i(TAG, "called surfaceChanged");
setupCamera(width, height);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.i(TAG, "called surfaceCreated");
(new Thread(this)).start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i(TAG, "called surfaceDestroyed");
}
protected abstract Bitmap processFrame(VideoCapture capture);
public void run() {
Log.i(TAG, "Started processing thread");
while (true) {
Bitmap bmp = null;
synchronized (this) {
if (mCamera == null)
break;
if (!mCamera.grab()) {
Log.e(TAG, "mCamera.grab() failed");
break;
}
bmp = processFrame(mCamera);
}
if (bmp != null) {
Canvas canvas = mHolder.lockCanvas();
if (canvas != null) {
canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR);
canvas.drawBitmap(bmp, (canvas.getWidth() - bmp.getWidth()) / 2, (canvas.getHeight() - bmp.getHeight()) / 2, null);
mHolder.unlockCanvasAndPost(canvas);
}
bmp.recycle();
}
}
Log.i(TAG, "Finished processing thread");
}
}
\ No newline at end of file
package org.opencv.samples.puzzle15;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
/** Activity class implements LoaderCallbackInterface to handle OpenCV initialization status **/
public class puzzle15Activity extends Activity {
private static final String TAG = "OCVSample::Activity";
private MenuItem mItemNewGame;
private MenuItem mItemToggleNumbers;
private puzzle15View mView = null;
private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
// Create and set View
mView = new puzzle15View(mAppContext);
setContentView(mView);
// Check native OpenCV camera
if( !mView.openCamera() ) {
AlertDialog ad = new AlertDialog.Builder(mAppContext).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("Fatal error: can't open camera!");
ad.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
ad.show();
}
} break;
/** OpenCV loader cannot start Google Play **/
case LoaderCallbackInterface.MARKET_ERROR:
{
Log.d(TAG, "Google Play service is not accessible!");
AlertDialog MarketErrorMessage = new AlertDialog.Builder(mAppContext).create();
MarketErrorMessage.setTitle("OpenCV Manager");
MarketErrorMessage.setMessage("Google Play service is not accessible!\nTry to install the 'OpenCV Manager' and the appropriate 'OpenCV binary pack' APKs from OpenCV SDK manually via 'adb install' command.");
MarketErrorMessage.setCancelable(false); // This blocks the 'BACK' button
MarketErrorMessage.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
MarketErrorMessage.show();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public puzzle15Activity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
@Override
protected void onPause() {
Log.i(TAG, "called onPause");
if (null != mView)
mView.releaseCamera();
super.onPause();
}
@Override
protected void onResume() {
Log.i(TAG, "called onResume");
super.onResume();
Log.i(TAG, "Trying to load OpenCV library");
if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this, mOpenCVCallBack)) {
Log.e(TAG, "Cannot connect to OpenCV Manager");
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "called onCreateOptionsMenu");
mItemNewGame = menu.add("Start new game");
mItemToggleNumbers = menu.add("Show/hide tile numbers");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "called onOptionsItemSelected; selected item: " + item);
if (item == mItemNewGame)
mView.startNewGame();
else if (item == mItemToggleNumbers)
mView.tolggleTileNumbers();
return true;
}
}
\ No newline at end of file
package org.opencv.samples.puzzle15;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnTouchListener;
public class puzzle15View extends SampleCvViewBase implements OnTouchListener {
private static final String TAG = "OCVSample::View";
private Mat mRgba;
private Mat mRgba15;
private Mat[] mCells;
private Mat[] mCells15;
private int[] mIndexses;
private int[] mTextWidths;
private int[] mTextHeights;
private boolean mShowTileNumbers = true;
int gridSize = 4;
int gridArea = gridSize * gridSize;
int gridEmptyIdx = gridArea - 1;
public puzzle15View(Context context) {
super(context);
setOnTouchListener(this);
mTextWidths = new int[gridArea];
mTextHeights = new int[gridArea];
for (int i = 0; i < gridArea; i++) {
Size s = Core.getTextSize(Integer.toString(i + 1), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, 2, null);
mTextHeights[i] = (int) s.height;
mTextWidths[i] = (int) s.width;
}
Log.i(TAG, "Instantiated new " + this.getClass());
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.i(TAG, "called surfaceCreated");
synchronized (this) {
// initialize Mat before usage
mRgba = new Mat();
}
super.surfaceCreated(holder);
}
public static void shuffle(int[] array) {
for (int i = array.length; i > 1; i--) {
int temp = array[i - 1];
int randIx = (int) (Math.random() * i);
array[i - 1] = array[randIx];
array[randIx] = temp;
}
}
public boolean isPuzzleSolvable() {
if (gridSize != 4)
return true;
int sum = 0;
for (int i = 0; i < gridArea; i++) {
if (mIndexses[i] == gridEmptyIdx)
sum += (i / gridSize) + 1;
else {
int smaller = 0;
for (int j = i + 1; j < gridArea; j++) {
if (mIndexses[j] < mIndexses[i])
smaller++;
}
sum += smaller;
}
}
return sum % 2 == 0;
}
private void createPuzzle(int cols, int rows, int type) {
mCells = new Mat[gridArea];
mCells15 = new Mat[gridArea];
mRgba15 = new Mat(rows, cols, type);
mIndexses = new int[gridArea];
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
int k = i * gridSize + j;
mIndexses[k] = k;
mCells[k] = mRgba.submat(i * rows / gridSize, (i + 1) * rows / gridSize, j * cols / gridSize, (j + 1) * cols / gridSize);
mCells15[k] = mRgba15.submat(i * rows / gridSize, (i + 1) * rows / gridSize, j * cols / gridSize, (j + 1) * cols / gridSize);
}
}
startNewGame();
}
private void drawGrid(int cols, int rows) {
for (int i = 1; i < gridSize; i++) {
Core.line(mRgba15, new Point(0, i * rows / gridSize), new Point(cols, i * rows / gridSize), new Scalar(0, 255, 0, 255), 3);
Core.line(mRgba15, new Point(i * cols / gridSize, 0), new Point(i * cols / gridSize, rows), new Scalar(0, 255, 0, 255), 3);
}
}
public synchronized void startNewGame() {
do {
shuffle(mIndexses);
} while (!isPuzzleSolvable());
}
public void tolggleTileNumbers() {
mShowTileNumbers = !mShowTileNumbers;
}
@Override
protected Bitmap processFrame(VideoCapture capture) {
capture.retrieve(mRgba, Highgui.CV_CAP_ANDROID_COLOR_FRAME_RGBA);
int cols = mRgba.cols();
int rows = mRgba.rows();
rows = rows - rows%4;
cols = cols - cols%4;
if (mCells == null)
createPuzzle(cols, rows, mRgba.type());
else if(mRgba15.cols() != cols || mRgba15.rows() != rows) {
releaseMats();
createPuzzle(cols, rows, mRgba.type());
}
// copy shuffled tiles
for (int i = 0; i < gridArea; i++) {
int idx = mIndexses[i];
if (idx == gridEmptyIdx)
mCells15[i].setTo(new Scalar(0x33, 0x33, 0x33, 0xFF));
else {
mCells[idx].copyTo(mCells15[i]);
if (mShowTileNumbers) {
Core.putText(mCells15[i], Integer.toString(1 + idx), new Point((cols / gridSize - mTextWidths[idx]) / 2,
(rows / gridSize + mTextHeights[idx]) / 2), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, new Scalar(255, 0, 0, 255), 2);
}
}
}
drawGrid(cols, rows);
Bitmap bmp = Bitmap.createBitmap(cols, rows, Bitmap.Config.ARGB_8888);
try {
Utils.matToBitmap(mRgba15, bmp);
return bmp;
} catch(Exception e) {
Log.e("org.opencv.samples.puzzle15", "Utils.matToBitmap() throws an exception: " + e.getMessage());
bmp.recycle();
return null;
}
}
@Override
public void run() {
super.run();
synchronized (this) {
releaseMats();
if (mRgba != null)
mRgba.release();
mRgba = null;
}
}
private void releaseMats() {
// Explicitly deallocate Mats
if (mCells != null) {
for (Mat m : mCells)
m.release();
}
if (mCells15 != null) {
for (Mat m : mCells15)
m.release();
}
if (mRgba15 != null)
mRgba15.release();
mRgba15 = null;
mCells = null;
mCells15 = null;
mIndexses = null;
}
public boolean onTouch(View v, MotionEvent event) {
if(mRgba==null) return false;
int cols = mRgba.cols();
int rows = mRgba.rows();
float xoffset = (getWidth() - cols) / 2;
float yoffset = (getHeight() - rows) / 2;
float x = event.getX() - xoffset;
float y = event.getY() - yoffset;
int row = (int) Math.floor(y * gridSize / rows);
int col = (int) Math.floor(x * gridSize / cols);
if (row < 0 || row >= gridSize || col < 0 || col >= gridSize)
return false;
int idx = row * gridSize + col;
int idxtoswap = -1;
// left
if (idxtoswap < 0 && col > 0)
if (mIndexses[idx - 1] == gridEmptyIdx)
idxtoswap = idx - 1;
// right
if (idxtoswap < 0 && col < gridSize - 1)
if (mIndexses[idx + 1] == gridEmptyIdx)
idxtoswap = idx + 1;
// top
if (idxtoswap < 0 && row > 0)
if (mIndexses[idx - gridSize] == gridEmptyIdx)
idxtoswap = idx - gridSize;
// bottom
if (idxtoswap < 0 && row < gridSize - 1)
if (mIndexses[idx + gridSize] == gridEmptyIdx)
idxtoswap = idx + gridSize;
// swap
if (idxtoswap >= 0) {
synchronized (this) {
int touched = mIndexses[idx];
mIndexses[idx] = mIndexses[idxtoswap];
mIndexses[idxtoswap] = touched;
}
}
return false;// don't need subsequent touch events
}
}
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>CameraWriter</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
#Wed Jun 29 04:36:40 MSD 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.source=1.5
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.opencv.test.camerawriter"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.CAMERA" required="false"/>
<uses-feature android:name="android.hardware.camera" required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" required="false"/>
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".PreviewActivity"
android:label="@string/title_activity_camera_writer" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
\ No newline at end of file
set(sample example-camera-preview)
add_android_project(${sample} "${CMAKE_CURRENT_SOURCE_DIR}" LIBRARY_DEPS ${OpenCV_BINARY_DIR} SDK_TARGET 11 ${ANDROID_SDK_TARGET})
if(TARGET ${sample})
add_dependencies(opencv_android_examples ${sample})
endif()
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<view class="org.opencv.test.camerawriter.NativeCameraView"
android:id="@+id/camera_surface_view"
android:layout_width = "fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
<resources>
<string name="app_name">CameraWriter</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_camera_writer">CameraWriterActivity</string>
</resources>
\ No newline at end of file
<resources>
<style name="AppTheme" parent="android:Theme.Light" />
</resources>
\ No newline at end of file
package org.opencv.test.camerawriter;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
/**
* This class is an implementation of a bridge between SurfaceView and native OpenCV camera.
* Due to the big amount of work done, by the base class this child is only responsible
* for creating camera, destroying camera and delivering frames while camera is enabled
*/
public class NativeCameraView extends CameraViewBase {
public static final String TAG = "OpenCvNativeCameraView";
private boolean mStopThread;
private Thread mThread;
private VideoCapture mCamera;
public NativeCameraView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void connectCamera(int width, int height) {
/* 1. We need to instantiate camera
* 2. We need to start thread which will be getting frames
*/
/* First step - initialize camera connection */
initializeCamera(getWidth(), getHeight());
/* now we can start update thread */
mThread = new Thread(new CameraWorker());
mThread.start();
}
@Override
protected void disconnectCamera() {
/* 1. We need to stop thread which updating the frames
* 2. Stop camera and release it
*/
try {
mStopThread = true;
mThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mThread = null;
mStopThread = false;
}
/* Now release camera */
releaseCamera();
}
private void initializeCamera(int width, int height) {
mCamera = new VideoCapture(Highgui.CV_CAP_ANDROID);
//TODO: improve error handling
java.util.List<Size> sizes = mCamera.getSupportedPreviewSizes();
/* Select the size that fits surface considering maximum size allowed */
Size frameSize = calculateCameraFrameSize(sizes, width, height);
double frameWidth = frameSize.width;
double frameHeight = frameSize.height;
mCamera.set(Highgui.CV_CAP_PROP_FRAME_WIDTH, frameWidth);
mCamera.set(Highgui.CV_CAP_PROP_FRAME_HEIGHT, frameHeight);
mFrameWidth = (int)frameWidth;
mFrameHeight = (int)frameHeight;
Log.i(TAG, "Selected camera frame size = (" + mFrameWidth + ", " + mFrameHeight + ")");
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release();
}
}
private class CameraWorker implements Runnable {
public void run() {
do {
if (!mCamera.grab()) {
Log.e(TAG, "Camera frame grab failed");
break;
}
mCamera.retrieve(mRgba, Highgui.CV_CAP_ANDROID_COLOR_FRAME_RGBA);
deliverAndDrawFrame(mRgba);
} while (!mStopThread);
}
private Mat mRgba = new Mat();
}
}
package org.opencv.test.camerawriter;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.test.camerawriter.CameraViewBase.CvCameraViewListener;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class PreviewActivity extends Activity implements CvCameraViewListener {
protected static final String TAG = "CameraWriterActivity";
private CameraViewBase mCameraView;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
Log.i(TAG, "OpenCV loaded successfully");
// Create and set View
mCameraView.setMaxFrameSize(640, 480);
mCameraView.enableView();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_writer);
mCameraView = (CameraViewBase)findViewById(R.id.camera_surface_view);
mCameraView.setCvCameraViewListener(this);
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this, mLoaderCallback);
}
public void onCameraViewStarted(int width, int height) {
// TODO Auto-generated method stub
}
public void onCameraViewStopped() {
// TODO Auto-generated method stub
}
public Mat onCameraFrame(Mat inputFrame) {
return inputFrame;
}
}
......@@ -5,16 +5,11 @@ import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
public class Sample0Base extends Activity {
private static final String TAG = "OCVSample::Activity";
private MenuItem mItemPreviewRGBA;
private MenuItem mItemPreviewGray;
private Sample0View mView;
public Sample0Base() {
......@@ -55,22 +50,4 @@ public class Sample0Base extends Activity {
mView = new Sample0View(this);
setContentView(mView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "called onCreateOptionsMenu");
mItemPreviewRGBA = menu.add("Preview RGBA");
mItemPreviewGray = menu.add("Preview GRAY");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "called onOptionsItemSelected; selected item: " + item);
if (item == mItemPreviewRGBA)
mView.setViewMode(Sample0View.VIEW_MODE_RGBA);
else if (item == mItemPreviewGray)
mView.setViewMode(Sample0View.VIEW_MODE_GRAY);
return true;
}
}
......@@ -3,6 +3,7 @@ package org.opencv.samples.tutorial0;
import java.io.IOException;
import java.util.List;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
......@@ -43,6 +44,7 @@ public abstract class SampleViewBase extends SurfaceView implements SurfaceHolde
return mFrameHeight;
}
@TargetApi(11)
public void setPreview() throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mSf = new SurfaceTexture(10);
......
......@@ -22,7 +22,7 @@
android:largeScreens="true"
android:anyDensity="true" />
<uses-sdk android:minSdkVersion="11" />
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.CAMERA"/>
......
......@@ -6,7 +6,6 @@ import org.opencv.android.OpenCVLoader;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.framework.OpenCvJavaCameraView;
import org.opencv.framework.OpenCvNativeCameraView;
import org.opencv.framework.OpenCvCameraBridgeViewBase.CvCameraViewListener;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
......@@ -122,8 +121,6 @@ public class Sample4Mixed extends Activity implements CvCameraViewListener {
public Mat onCameraFrame(Mat inputFrame) {
final int viewMode = mViewMode;
Log.d(TAG, "Input format: " + inputFrame);
switch (viewMode) {
case VIEW_MODE_GRAY:
// input frame has gray scale format
......@@ -140,15 +137,12 @@ public class Sample4Mixed extends Activity implements CvCameraViewListener {
break;
case VIEW_MODE_FEATURES:
// input frame has RGBA format
//Imgproc.cvtColor(mYuv, mRgba, Imgproc.COLOR_YUV420sp2RGB, 4);
inputFrame.copyTo(mRgba);
Imgproc.cvtColor(mRgba, mGrayMat, Imgproc.COLOR_RGBA2GRAY);
FindFeatures(mGrayMat.getNativeObjAddr(), mRgba.getNativeObjAddr());
break;
}
Log.d(TAG, "Output format: " + mRgba);
return mRgba;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment