feat: 切换后端至PaddleOCR-NCNN,切换工程为CMake

1.项目后端整体迁移至PaddleOCR-NCNN算法,已通过基本的兼容性测试
2.工程改为使用CMake组织,后续为了更好地兼容第三方库,不再提供QMake工程
3.重整权利声明文件,重整代码工程,确保最小化侵权风险

Log: 切换后端至PaddleOCR-NCNN,切换工程为CMake
Change-Id: I4d5d2c5d37505a4a24b389b1a4c5d12f17bfa38c
This commit is contained in:
wangzhengyang
2022-05-10 09:54:44 +08:00
parent ecdd171c6f
commit 718c41634f
10018 changed files with 3593797 additions and 186748 deletions

View File

@ -0,0 +1,9 @@
<?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="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>OpenCV_JavaAPI_Tests</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>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.opencv.test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<!-- We add an application tag here just so that we can indicate that
this package needs to link against the android.test library,
which is needed when building test cases. -->
<application>
<uses-library android:name="android.test.runner" />
</application>
<!--
This declares that this application uses the instrumentation test runner targeting
the package of org.opencv. To run the tests use the command:
"adb shell am instrument -w org.opencv.test/android.test.InstrumentationTestRunner"
-->
<instrumentation android:name="org.opencv.test.OpenCVTestRunner"
android:targetPackage="org.opencv.test"
android:label="Tests for org.opencv"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>

View File

@ -0,0 +1,77 @@
if(NOT ANT_EXECUTABLE OR NOT ANDROID_EXECUTABLE OR NOT ANDROID_TOOLS_Pkg_Revision GREATER 13)
return()
endif()
project(opencv_test_java)
set(OPENCV_JAVA_TEST_DIR "${OpenCV_BINARY_DIR}/android_test" CACHE INTERNAL "")
file(REMOVE_RECURSE "${OPENCV_JAVA_TEST_DIR}")
file(REMOVE "${OPENCV_DEPHELPER}/${the_module}_test_source_copy")
set(test_dir "${CMAKE_CURRENT_SOURCE_DIR}")
set(depends "")
# 1. gather and copy common test files (resources, utils, etc.)
copy_common_tests("${CMAKE_CURRENT_SOURCE_DIR}/../common_test" "${OPENCV_JAVA_TEST_DIR}" depends)
# 2. gather and copy tests from each module
ocv_copyfiles_append_dir(JAVA_TEST_SRC_COPY "${OPENCV_JAVA_BINDINGS_DIR}/gen/test" "${OPENCV_JAVA_TEST_DIR}/src")
list(APPEND depends gen_opencv_java_source "${OPENCV_DEPHELPER}/gen_opencv_java_source")
ocv_copyfiles_add_target(${the_module}_test_source_copy JAVA_TEST_SRC_COPY "Copy Java(Android test) source files" ${depends})
set(depends ${the_module}_test_source_copy "${OPENCV_DEPHELPER}/${the_module}_test_source_copy")
# 3. gather and copy specific files for Android
file(GLOB_RECURSE test_files RELATIVE "${test_dir}" "${test_dir}/res/*" "${test_dir}/src/*")
foreach(f ${test_files} ${ANDROID_MANIFEST_FILE} ".classpath" ".project")
add_custom_command(
OUTPUT "${OPENCV_JAVA_TEST_DIR}/${f}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${test_dir}/${f}" "${OPENCV_JAVA_TEST_DIR}/${f}"
MAIN_DEPENDENCY "${test_dir}/${f}"
COMMENT "Copying ${f}")
list(APPEND depends "${test_dir}/${f}" "${OPENCV_JAVA_TEST_DIR}/${f}")
endforeach()
# fix Android project
set(android_proj_target_files ${ANDROID_PROJECT_FILES})
ocv_list_add_prefix(android_proj_target_files "${OPENCV_JAVA_TEST_DIR}/")
file(RELATIVE_PATH __dep "${OPENCV_JAVA_TEST_DIR}" "${OpenCV_BINARY_DIR}/android_sdk")
add_custom_command(
OUTPUT ${android_proj_target_files}
COMMAND ${CMAKE_COMMAND} -E remove ${android_proj_target_files}
COMMAND ${ANDROID_EXECUTABLE} --silent update test-project --path "${OPENCV_JAVA_TEST_DIR}" --main "${OpenCV_BINARY_DIR}/android_sdk"
COMMAND ${ANDROID_EXECUTABLE} --silent update project --path "${OPENCV_JAVA_TEST_DIR}" --library "${__dep}"
MAIN_DEPENDENCY "${OPENCV_JAVA_TEST_DIR}/${ANDROID_MANIFEST_FILE}"
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${ANDROID_MANIFEST_FILE}"
COMMENT "Updating Android Java API test project")
list(APPEND depends ${android_proj_target_files})
# build java part
add_custom_command(
OUTPUT "${OPENCV_JAVA_TEST_DIR}/bin/OpenCVTest-debug.apk"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "$<TARGET_FILE:opencv_java>" "${OPENCV_JAVA_TEST_DIR}/libs/${ANDROID_NDK_ABI_NAME}/$<TARGET_FILE_NAME:opencv_java>"
COMMAND ${ANT_EXECUTABLE} -q -noinput -k debug -Djava.target=1.6 -Djava.source=1.6
COMMAND ${CMAKE_COMMAND} -E touch "${OPENCV_JAVA_TEST_DIR}/bin/OpenCVTest-debug.apk" # needed because ant does not update the timestamp of updated apk
WORKING_DIRECTORY "${OPENCV_JAVA_TEST_DIR}"
MAIN_DEPENDENCY "${OPENCV_JAVA_TEST_DIR}/${ANDROID_MANIFEST_FILE}"
DEPENDS opencv_java_android opencv_java
DEPENDS ${depends})
add_custom_target(${PROJECT_NAME} ALL SOURCES "${OPENCV_JAVA_TEST_DIR}/bin/OpenCVTest-debug.apk" "${CMAKE_CURRENT_SOURCE_DIR}/${ANDROID_MANIFEST_FILE}")
add_dependencies(${PROJECT_NAME} opencv_java ${__android_project_chain})
set(__android_project_chain ${PROJECT_NAME} CACHE INTERNAL "auxiliary variable used for Android progects chaining" FORCE)
# put the final .apk to the OpenCV's bin folder
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${OPENCV_JAVA_TEST_DIR}/bin/OpenCVTest-debug.apk" "${OpenCV_BINARY_DIR}/bin/${PROJECT_NAME}.apk")
add_dependencies(opencv_tests ${PROJECT_NAME})
if(PYTHON_DEFAULT_AVAILABLE)
set(CHECK_TEST_COVERAGE "${OPENCV_MODULE_opencv_java_LOCATION}/check-tests.py")
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${PYTHON_DEFAULT_EXECUTABLE} ${CHECK_TEST_COVERAGE} "${OPENCV_JAVA_TEST_DIR}/src" "${OPENCV_ANDROID_LIB_DIR}/src" > "${CMAKE_CURRENT_BINARY_DIR}/tests_coverage.log"
)
endif()

View File

@ -0,0 +1,629 @@
package org.opencv.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.List;
import junit.framework.TestCase;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Point3;
import org.opencv.core.Rect;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.core.DMatch;
import org.opencv.core.KeyPoint;
import org.opencv.imgcodecs.Imgcodecs;
import android.util.Log;
import java.lang.reflect.Method;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
public class OpenCVTestCase extends TestCase {
public static class TestSkipException extends RuntimeException {
public TestSkipException() {}
}
//change to 'true' to unblock fail on fail("Not yet implemented")
public static final boolean passNYI = true;
protected static boolean isTestCaseEnabled = true;
protected static final String XFEATURES2D = "org.opencv.xfeatures2d.";
protected static final String DEFAULT_FACTORY = "create";
protected static final int matSize = 10;
protected static final double EPS = 0.001;
protected static final double weakEPS = 0.5;
private static final String TAG = "OpenCVTestCase";
protected Mat dst;
protected Mat truth;
protected Scalar colorBlack;
protected Scalar colorWhite;
// Naming notation: <channels info>_[depth]_[dimensions]_value
// examples: gray0 - single channel 8U 2d Mat filled with 0
// grayRnd - single channel 8U 2d Mat filled with random numbers
// gray0_32f_1d
// TODO: OpenCVTestCase refactorings
// - rename matrices
// - create methods gray0() and create src1 explicitly
// - create some masks
// - use truth member everywhere - remove truth from base class - each test
// fixture should use own truth filed
protected Mat gray0;
protected Mat gray1;
protected Mat gray2;
protected Mat gray3;
protected Mat gray9;
protected Mat gray127;
protected Mat gray128;
protected Mat gray255;
protected Mat grayRnd;
protected Mat gray_16u_256;
protected Mat gray_16s_1024;
protected Mat gray0_32f;
protected Mat gray1_32f;
protected Mat gray3_32f;
protected Mat gray9_32f;
protected Mat gray255_32f;
protected Mat grayE_32f;
protected Mat grayRnd_32f;
protected Mat gray0_32f_1d;
protected Mat gray0_64f;
protected Mat gray0_64f_1d;
protected Mat rgba0;
protected Mat rgba128;
protected Mat rgbLena;
protected Mat grayChess;
protected Mat gray255_32f_3d;
protected Mat v1;
protected Mat v2;
@Override
protected void setUp() throws Exception {
super.setUp();
dst = new Mat();
assertTrue(dst.empty());
truth = null;
colorBlack = new Scalar(0);
colorWhite = new Scalar(255, 255, 255);
gray0 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(0));
gray1 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(1));
gray2 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(2));
gray3 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(3));
gray9 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(9));
gray127 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(127));
gray128 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(128));
gray255 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(255));
grayRnd = new Mat(matSize, matSize, CvType.CV_8U);
Core.randu(grayRnd, 0, 256);
gray_16u_256 = new Mat(matSize, matSize, CvType.CV_16U, new Scalar(256));
gray_16s_1024 = new Mat(matSize, matSize, CvType.CV_16S, new Scalar(1024));
gray0_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(0.0));
gray1_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(1.0));
gray3_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(3.0));
gray9_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(9.0));
gray255_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(255.0));
grayE_32f = new Mat(matSize, matSize, CvType.CV_32F);
grayE_32f = Mat.eye(matSize, matSize, CvType.CV_32FC1);
grayRnd_32f = new Mat(matSize, matSize, CvType.CV_32F);
Core.randu(grayRnd_32f, 0, 256);
gray0_64f = new Mat(matSize, matSize, CvType.CV_64F, new Scalar(0.0));
gray0_32f_1d = new Mat(1, matSize, CvType.CV_32F, new Scalar(0.0));
gray0_64f_1d = new Mat(1, matSize, CvType.CV_64F, new Scalar(0.0));
rgba0 = new Mat(matSize, matSize, CvType.CV_8UC4, Scalar.all(0));
rgba128 = new Mat(matSize, matSize, CvType.CV_8UC4, Scalar.all(128));
rgbLena = Imgcodecs.imread(OpenCVTestRunner.LENA_PATH);
grayChess = Imgcodecs.imread(OpenCVTestRunner.CHESS_PATH, 0);
gray255_32f_3d = new Mat(new int[]{matSize, matSize, matSize}, CvType.CV_32F, new Scalar(255.0));
v1 = new Mat(1, 3, CvType.CV_32F);
v1.put(0, 0, 1.0, 3.0, 2.0);
v2 = new Mat(1, 3, CvType.CV_32F);
v2.put(0, 0, 2.0, 1.0, 3.0);
}
@Override
protected void tearDown() throws Exception {
gray0.release();
gray1.release();
gray2.release();
gray3.release();
gray9.release();
gray127.release();
gray128.release();
gray255.release();
gray_16u_256.release();
gray_16s_1024.release();
grayRnd.release();
gray0_32f.release();
gray1_32f.release();
gray3_32f.release();
gray9_32f.release();
gray255_32f.release();
grayE_32f.release();
grayE_32f.release();
grayRnd_32f.release();
gray0_32f_1d.release();
gray0_64f.release();
gray0_64f_1d.release();
rgba0.release();
rgba128.release();
rgbLena.release();
grayChess.release();
gray255_32f_3d.release();
v1.release();
v2.release();
super.tearDown();
}
@Override
protected void runTest() throws Throwable {
// Do nothing if the precondition does not hold.
if (isTestCaseEnabled) {
try {
super.runTest();
} catch (TestSkipException ex) {
Log.w(TAG, "Test case \"" + this.getClass().getName() + "\" skipped!");
assertTrue(true);
}
} else {
Log.e(TAG, "Test case \"" + this.getClass().getName() + "\" disabled!");
}
}
public void runBare() throws Throwable {
Throwable exception = null;
try {
setUp();
} catch (TestSkipException ex) {
Log.w(TAG, "Test case \"" + this.getClass().getName() + "\" skipped!");
assertTrue(true);
return;
}
try {
runTest();
} catch (Throwable running) {
exception = running;
} finally {
try {
tearDown();
} catch (Throwable tearingDown) {
if (exception == null) exception = tearingDown;
}
}
if (exception != null) throw exception;
}
protected Mat getMat(int type, double... vals)
{
return new Mat(matSize, matSize, type, new Scalar(vals));
}
protected Mat makeMask(Mat m, double... vals)
{
m.submat(0, m.rows(), 0, m.cols() / 2).setTo(new Scalar(vals));
return m;
}
public static void fail(String msg) {
if(msg == "Not yet implemented" && passNYI)
return;
TestCase.fail(msg);
}
public static void assertGE(double v1, double v2) {
assertTrue("Failed: " + v1 + " >= " + v2, v1 >= v2);
}
public static <E extends Number> void assertListEquals(List<E> list1, List<E> list2) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
if (!list1.isEmpty())
{
if (list1.get(0) instanceof Float || list1.get(0) instanceof Double)
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertEquals(list1.get(i), list2.get(i));
}
public static <E extends Number> void assertListEquals(List<E> list1, List<E> list2, double epsilon) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertTrue(Math.abs(list1.get(i).doubleValue() - list2.get(i).doubleValue()) <= epsilon);
}
public static <E extends Number> void assertArrayEquals(E[] ar1, E[] ar2, double epsilon) {
assertEquals(ar1.length, ar2.length);
for (int i = 0; i < ar1.length; i++)
assertEquals(ar1[i].doubleValue(), ar2[i].doubleValue(), epsilon);
//assertTrue(Math.abs(ar1[i].doubleValue() - ar2[i].doubleValue()) <= epsilon);
}
public static void assertArrayEquals(short[] ar1, short[] ar2) {
assertEquals(ar1.length, ar2.length);
for (int i = 0; i < ar1.length; i++)
assertEquals(ar1[i], ar2[i]);
//assertTrue(Math.abs(ar1[i].doubleValue() - ar2[i].doubleValue()) <= epsilon);
}
public static void assertArrayEquals(double[] ar1, double[] ar2, double epsilon) {
assertEquals(ar1.length, ar2.length);
for (int i = 0; i < ar1.length; i++)
assertEquals(ar1[i], ar2[i], epsilon);
//assertTrue(Math.abs(ar1[i].doubleValue() - ar2[i].doubleValue()) <= epsilon);
}
public static void assertListMatEquals(List<Mat> list1, List<Mat> list2, double epsilon) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertMatEqual(list1.get(i), list2.get(i), epsilon);
}
public static void assertListPointEquals(List<Point> list1, List<Point> list2, double epsilon) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertPointEquals(list1.get(i), list2.get(i), epsilon);
}
public static void assertArrayPointsEquals(Point[] vp1, Point[] vp2, double epsilon) {
if (vp1.length != vp2.length) {
fail("Arrays have different sizes.");
}
for (int i = 0; i < vp1.length; i++)
assertPointEquals(vp1[i], vp2[i], epsilon);
}
public static void assertListPoint3Equals(List<Point3> list1, List<Point3> list2, double epsilon) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertPoint3Equals(list1.get(i), list2.get(i), epsilon);
}
public static void assertListRectEquals(List<Rect> list1, List<Rect> list2) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertRectEquals(list1.get(i), list2.get(i));
}
public static void assertListRotatedRectEquals(List<RotatedRect> list1, List<RotatedRect> list2) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertRotatedRectEquals(list1.get(i), list2.get(i));
}
public static void assertRectEquals(Rect expected, Rect actual) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.x, actual.x);
assertEquals(msg, expected.y, actual.y);
assertEquals(msg, expected.width, actual.width);
assertEquals(msg, expected.height, actual.height);
}
public static void assertRotatedRectEquals(RotatedRect expected, RotatedRect actual) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.center.x, actual.center.x);
assertEquals(msg, expected.center.y, actual.center.y);
assertEquals(msg, expected.size.width, actual.size.width);
assertEquals(msg, expected.size.height, actual.size.height);
assertEquals(msg, expected.angle, actual.angle);
}
public static void assertMatEqual(Mat m1, Mat m2) {
compareMats(m1, m2, true);
}
public static void assertMatNotEqual(Mat m1, Mat m2) {
compareMats(m1, m2, false);
}
public static void assertMatEqual(Mat expected, Mat actual, double eps) {
compareMats(expected, actual, eps, true);
}
public static void assertMatNotEqual(Mat expected, Mat actual, double eps) {
compareMats(expected, actual, eps, false);
}
public static void assertKeyPointEqual(KeyPoint expected, KeyPoint actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertTrue(msg, Math.hypot(expected.pt.x - actual.pt.x, expected.pt.y - actual.pt.y) < eps);
assertTrue(msg, Math.abs(expected.size - actual.size) < eps);
assertTrue(msg, Math.abs(expected.angle - actual.angle) < eps);
assertTrue(msg, Math.abs(expected.response - actual.response) < eps);
assertEquals(msg, expected.octave, actual.octave);
assertEquals(msg, expected.class_id, actual.class_id);
}
public static void assertListKeyPointEquals(List<KeyPoint> expected, List<KeyPoint> actual, double epsilon) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++)
assertKeyPointEqual(expected.get(i), actual.get(i), epsilon);
}
public static void assertDMatchEqual(DMatch expected, DMatch actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.queryIdx, actual.queryIdx);
assertEquals(msg, expected.trainIdx, actual.trainIdx);
assertEquals(msg, expected.imgIdx, actual.imgIdx);
assertTrue(msg, Math.abs(expected.distance - actual.distance) < eps);
}
public static void assertScalarEqual(Scalar expected, Scalar actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertTrue(msg, Math.abs(expected.val[0] - actual.val[0]) < eps);
assertTrue(msg, Math.abs(expected.val[1] - actual.val[1]) < eps);
assertTrue(msg, Math.abs(expected.val[2] - actual.val[2]) < eps);
assertTrue(msg, Math.abs(expected.val[3] - actual.val[3]) < eps);
}
public static void assertArrayDMatchEquals(DMatch[] expected, DMatch[] actual, double epsilon) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++)
assertDMatchEqual(expected[i], actual[i], epsilon);
}
public static void assertListDMatchEquals(List<DMatch> expected, List<DMatch> actual, double epsilon) {
DMatch expectedArray[] = expected.toArray(new DMatch[0]);
DMatch actualArray[] = actual.toArray(new DMatch[0]);
assertArrayDMatchEquals(expectedArray, actualArray, epsilon);
}
public static void assertPointEquals(Point expected, Point actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.x, actual.x, eps);
assertEquals(msg, expected.y, actual.y, eps);
}
public static void assertSizeEquals(Size expected, Size actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.width, actual.width, eps);
assertEquals(msg, expected.height, actual.height, eps);
}
public static void assertPoint3Equals(Point3 expected, Point3 actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.x, actual.x, eps);
assertEquals(msg, expected.y, actual.y, eps);
assertEquals(msg, expected.z, actual.z, eps);
}
static private boolean dimensionsEqual(Mat expected, Mat actual) {
if (expected.dims() != actual.dims()) {
return false;
}
if (expected.dims() > 2) {
for (int i = 0; i < expected.dims(); i++) {
if (expected.size(i) != actual.size(i)) {
return false;
}
}
return true;
} else {
return expected.cols() == actual.cols() && expected.rows() == actual.rows();
}
}
static private void compareMats(Mat expected, Mat actual, boolean isEqualityMeasured) {
if (expected.type() != actual.type() || !dimensionsEqual(expected, actual)) {
throw new UnsupportedOperationException("Can not compare " + expected + " and " + actual);
}
if (expected.depth() == CvType.CV_32F || expected.depth() == CvType.CV_64F) {
if (isEqualityMeasured)
throw new UnsupportedOperationException(
"Floating-point Mats must not be checked for exact match. Use assertMatEqual(Mat expected, Mat actual, double eps) instead.");
else
throw new UnsupportedOperationException(
"Floating-point Mats must not be checked for exact match. Use assertMatNotEqual(Mat expected, Mat actual, double eps) instead.");
}
Mat diff = new Mat();
Core.absdiff(expected, actual, diff);
Mat reshaped = diff.reshape(1);
int mistakes = Core.countNonZero(reshaped);
reshaped.release();
diff.release();
if (isEqualityMeasured)
assertTrue("Mats are different in " + mistakes + " points", 0 == mistakes);
else
assertFalse("Mats are equal", 0 == mistakes);
}
static private void compareMats(Mat expected, Mat actual, double eps, boolean isEqualityMeasured) {
if (expected.type() != actual.type() || !dimensionsEqual(expected, actual)) {
throw new UnsupportedOperationException("Can not compare " + expected + " and " + actual);
}
Mat diff = new Mat();
Core.absdiff(expected, actual, diff);
double maxDiff = Core.norm(diff, Core.NORM_INF);
if (isEqualityMeasured)
assertTrue("Max difference between expected and actual Mats is "+ maxDiff + ", that bigger than " + eps,
maxDiff <= eps);
else
assertFalse("Max difference between expected and actual Mats is "+ maxDiff + ", that less than " + eps,
maxDiff <= eps);
}
protected static String readFile(String path) {
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
StringBuffer result = new StringBuffer();
while ((line = br.readLine()) != null) {
result.append(line);
result.append("\n");
}
return result.toString();
} catch (IOException e) {
OpenCVTestRunner.Log("Failed to read file \"" + path
+ "\". Exception is thrown: " + e);
return null;
}
}
protected static void writeFile(String path, String content) {
FileOutputStream stream = null;
try {
stream = new FileOutputStream(new File(path));
FileChannel fc = stream.getChannel();
fc.write(Charset.defaultCharset().encode(content));
} catch (IOException e) {
OpenCVTestRunner.Log("Failed to write file \"" + path
+ "\". Exception is thrown: " + e);
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
OpenCVTestRunner.Log("Exception is thrown: " + e);
}
}
}
protected <T> T createClassInstance(String cname, String factoryName, Class cParams[], Object oValues[]) {
T instance = null;
assertFalse("Class name should not be empty", "".equals(cname));
String message="";
try {
Class algClass = getClassForName(cname);
Method factory = null;
if(cParams!=null && cParams.length>0) {
if(!"".equals(factoryName)) {
factory = algClass.getDeclaredMethod(factoryName, cParams);
instance = (T) factory.invoke(null, oValues);
}
else {
instance = (T) algClass.getConstructor(cParams).newInstance(oValues);
}
}
else {
if(!"".equals(factoryName)) {
factory = algClass.getDeclaredMethod(factoryName);
instance = (T) factory.invoke(null);
}
else {
instance = (T) algClass.getConstructor().newInstance();
}
}
}
catch(Exception ex) {
if (cname.startsWith(XFEATURES2D))
{
throw new TestSkipException();
}
message = TAG + " :: " + "could not instantiate " + cname + "! Exception: " + ex.getMessage();
}
assertNotNull(message, instance);
return instance;
}
protected <T> void setProperty(T instance, String propertyName, String propertyType, Object propertyValue) {
String message = "";
try {
String smethod = "set" + propertyName.substring(0,1).toUpperCase() + propertyName.substring(1);
Method setter = instance.getClass().getMethod(smethod, getClassForName(propertyType));
setter.invoke(instance, propertyValue);
}
catch(Exception ex) {
message = "Error when setting property [" + propertyName + "]: " + ex.getMessage();
}
assertTrue(message, "".equals(message));
}
protected Class getClassForName(String sclass) throws ClassNotFoundException{
if("int".equals(sclass))
return Integer.TYPE;
else if("long".equals(sclass))
return Long.TYPE;
else if("double".equals(sclass))
return Double.TYPE;
else if("float".equals(sclass))
return Float.TYPE;
else if("boolean".equals(sclass))
return Boolean.TYPE;
else if("char".equals(sclass))
return Character.TYPE;
else if("byte".equals(sclass))
return Byte.TYPE;
else if("short".equals(sclass))
return Short.TYPE;
else
return Class.forName(sclass);
}
}

View File

@ -0,0 +1,124 @@
package org.opencv.test;
import java.io.File;
import java.io.IOException;
import junit.framework.Assert;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import android.content.Context;
import android.test.AndroidTestRunner;
import android.test.InstrumentationTestRunner;
import android.util.Log;
/**
* This only class is Android specific.
*/
public class OpenCVTestRunner extends InstrumentationTestRunner {
private static final long MANAGER_TIMEOUT = 3000;
public static String LENA_PATH;
public static String CHESS_PATH;
public static String LBPCASCADE_FRONTALFACE_PATH;
public static Context context;
private AndroidTestRunner androidTestRunner;
private static String TAG = "opencv_test_java";
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(getContext()) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log("OpenCV loaded successfully");
synchronized (this) {
notify();
}
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public static String getTempFileName(String extension)
{
File cache = context.getCacheDir();
if (!extension.startsWith("."))
extension = "." + extension;
try {
File tmp = File.createTempFile("OpenCV", extension, cache);
String path = tmp.getAbsolutePath();
tmp.delete();
return path;
} catch (IOException e) {
Log("Failed to get temp file name. Exception is thrown: " + e);
}
return null;
}
static public void Log(String message) {
Log.e(TAG, message);
}
static public void Log(Mat m) {
Log.e(TAG, m + "\n " + m.dump());
}
@Override
public void onStart() {
// try to load internal libs
if (!OpenCVLoader.initDebug()) {
// There is no internal OpenCV libs
// Using OpenCV Manager for initialization;
Log("Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION, getContext(), mLoaderCallback);
synchronized (this) {
try {
wait(MANAGER_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
Log("OpenCV library found inside test package. Using it!");
}
context = getContext();
Assert.assertNotNull("Context can't be 'null'", context);
LENA_PATH = Utils.exportResource(context, R.drawable.lena);
CHESS_PATH = Utils.exportResource(context, R.drawable.chessboard);
LBPCASCADE_FRONTALFACE_PATH = Utils.exportResource(context, R.raw.lbpcascade_frontalface);
/*
* The original idea about test order randomization is from
* marek.defecinski blog.
*/
//List<TestCase> testCases = androidTestRunner.getTestCases();
//Collections.shuffle(testCases); //shuffle the tests order
super.onStart();
}
@Override
protected AndroidTestRunner getAndroidTestRunner() {
androidTestRunner = super.getAndroidTestRunner();
return androidTestRunner;
}
public static String getOutputFileName(String name)
{
return context.getExternalFilesDir(null).getAbsolutePath() + File.separatorChar + name;
}
}

View File

@ -0,0 +1,172 @@
package org.opencv.test.android;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.test.OpenCVTestCase;
import org.opencv.test.OpenCVTestRunner;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
public class UtilsTest extends OpenCVTestCase {
public void testBitmapToMat() {
BitmapFactory.Options opt16 = new BitmapFactory.Options();
opt16.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bmp16 = BitmapFactory.decodeFile(OpenCVTestRunner.LENA_PATH, opt16);
Mat m16 = new Mat();
Utils.bitmapToMat(bmp16, m16);
assertTrue(m16.rows() == 512 && m16.cols() == 512 && m16.type() == CvType.CV_8UC4);
/*BitmapFactory.Options opt32 = new BitmapFactory.Options();
opt32.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bmp32 = BitmapFactory.decodeFile(OpenCVTestRunner.LENA_PATH, opt32);*/
Bitmap bmp32 = bmp16.copy(Bitmap.Config.ARGB_8888, false);
Mat m32 = new Mat();
Utils.bitmapToMat(bmp32, m32);
assertTrue(m16.rows() == m32.rows() && m16.cols() == m32.cols() && m16.type() == m32.type());
double maxDiff = Core.norm(m16, m32, Core.NORM_INF);
Log.d("Bmp->Mat", "bmp16->Mat vs bmp32->Mat diff = " + maxDiff);
assertTrue(maxDiff <= 8 /* 8 == 2^8 / 2^5 */);
}
public void testExportResourceContextInt() {
fail("Not yet implemented");
}
public void testExportResourceContextIntString() {
fail("Not yet implemented");
}
public void testLoadResourceContextInt() {
fail("Not yet implemented");
}
public void testLoadResourceContextIntInt() {
fail("Not yet implemented");
}
public void testMatToBitmap() {
Mat imgBGR = Imgcodecs.imread( OpenCVTestRunner.LENA_PATH );
assertTrue(imgBGR != null && !imgBGR.empty() && imgBGR.channels() == 3);
Mat m16 = new Mat(imgBGR.rows(), imgBGR.cols(), CvType.CV_8UC4);
Mat m32 = new Mat(imgBGR.rows(), imgBGR.cols(), CvType.CV_8UC4);
Bitmap bmp16 = Bitmap.createBitmap(imgBGR.cols(), imgBGR.rows(), Bitmap.Config.RGB_565);
Bitmap bmp32 = Bitmap.createBitmap(imgBGR.cols(), imgBGR.rows(), Bitmap.Config.ARGB_8888);
double maxDiff;
Scalar s0 = new Scalar(0);
Scalar s255 = Scalar.all(255);
// RGBA
Mat imgRGBA = new Mat();
Imgproc.cvtColor(imgBGR, imgRGBA, Imgproc.COLOR_BGR2RGBA);
assertFalse(imgRGBA.empty() && imgRGBA.channels() == 4);
bmp16.eraseColor(Color.BLACK); m16.setTo(s0);
Utils.matToBitmap(imgRGBA, bmp16); Utils.bitmapToMat(bmp16, m16);
maxDiff = Core.norm(imgRGBA, m16, Core.NORM_INF);
Log.d("RGBA->bmp16->RGBA", "maxDiff = " + maxDiff);
assertTrue(maxDiff <= 8 /* 8 == 2^8 / 2^5 */);
bmp32.eraseColor(Color.WHITE); m32.setTo(s255);
Utils.matToBitmap(imgRGBA, bmp32); Utils.bitmapToMat(bmp32, m32);
maxDiff = Core.norm(imgRGBA, m32, Core.NORM_INF);
Log.d("RGBA->bmp32->RGBA", "maxDiff = " + maxDiff);
assertTrue(maxDiff == 0);
// RGB
Mat imgRGB = new Mat();
Imgproc.cvtColor(imgBGR, imgRGB, Imgproc.COLOR_BGR2RGB);
assertFalse(imgRGB.empty() && imgRGB.channels() == 3);
bmp16.eraseColor(Color.BLACK); m16.setTo(s0);
Utils.matToBitmap(imgRGB, bmp16); Utils.bitmapToMat(bmp16, m16);
maxDiff = Core.norm(imgRGBA, m16, Core.NORM_INF);
Log.d("RGB->bmp16->RGBA", "maxDiff = " + maxDiff);
assertTrue(maxDiff <= 8 /* 8 == 2^8 / 2^5 */);
bmp32.eraseColor(Color.WHITE); m32.setTo(s255);
Utils.matToBitmap(imgRGB, bmp32); Utils.bitmapToMat(bmp32, m32);
maxDiff = Core.norm(imgRGBA, m32, Core.NORM_INF);
Log.d("RGB->bmp32->RGBA", "maxDiff = " + maxDiff);
assertTrue(maxDiff == 0);
// Gray
Mat imgGray = new Mat();
Imgproc.cvtColor(imgBGR, imgGray, Imgproc.COLOR_BGR2GRAY);
assertFalse(imgGray.empty() && imgGray.channels() == 1);
Mat tmp = new Mat();
bmp16.eraseColor(Color.BLACK); m16.setTo(s0);
Utils.matToBitmap(imgGray, bmp16); Utils.bitmapToMat(bmp16, m16);
Core.extractChannel(m16, tmp, 0);
maxDiff = Core.norm(imgGray, tmp, Core.NORM_INF);
Log.d("Gray->bmp16->RGBA", "maxDiff = " + maxDiff);
assertTrue(maxDiff <= 8 /* 8 == 2^8 / 2^5 */);
bmp32.eraseColor(Color.WHITE); m32.setTo(s255);
Utils.matToBitmap(imgGray, bmp32); Utils.bitmapToMat(bmp32, m32);
tmp.setTo(s0);
Core.extractChannel(m32, tmp, 0);
maxDiff = Core.norm(imgGray, tmp, Core.NORM_INF);
Log.d("Gray->bmp32->RGBA", "maxDiff = " + maxDiff);
assertTrue(maxDiff == 0);
}
public void testAlphaPremultiplication() {
final int size = 256;
Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Mat mOrig = new Mat(size, size, CvType.CV_8UC4);
Mat mUnPre = new Mat(size, size, CvType.CV_8UC4);
for(int y=0; y<size; y++) {
int a = y;
for(int x=0; x<size; x++) {
int color = Color.argb(a, 0, x, y);
bmp.setPixel(x, y, color);
mOrig.put(y, x, Color.red(color), Color.green(color), Color.blue(color), Color.alpha(color));
int colorUnPre = bmp.getPixel(x, y);
mUnPre.put(y, x, Color.red(colorUnPre), Color.green(colorUnPre), Color.blue(colorUnPre), Color.alpha(colorUnPre));
}
}
// Bitmap -> Mat
Mat m1 = new Mat();
Mat m2 = new Mat();
Utils.bitmapToMat(bmp, m1, false);
Imgproc.cvtColor(mOrig, m2, Imgproc.COLOR_RGBA2mRGBA);
assertMatEqual(m1, m2, 1.1);
Utils.bitmapToMat(bmp, m1, true);
assertMatEqual(m1, mUnPre, 1.1);
// Mat -> Bitmap
Bitmap bmp1 = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mOrig, bmp1, true);
Utils.bitmapToMat(bmp1, m1, true);
//assertMatEqual(m1, mUnPre, 1.1);
Mat diff = new Mat();
Core.absdiff(m1, mUnPre, diff);
int numDiff = Core.countNonZero(diff.reshape(1));
assertTrue(numDiff < size * 4);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World!</string>
<string name="app_name">OpenCV_JavaAPI_Tests</string>
</resources>

View File

@ -0,0 +1,529 @@
package org.opencv.test.utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Point3;
import org.opencv.core.Size;
import org.opencv.core.Rect;
import org.opencv.core.RotatedRect;
import org.opencv.core.DMatch;
import org.opencv.core.KeyPoint;
import org.opencv.test.OpenCVTestCase;
import org.opencv.utils.Converters;
import java.util.ArrayList;
import java.util.List;
public class ConvertersTest extends OpenCVTestCase {
public void testMat_to_vector_char() {
Mat src = new Mat(3, 1, CvType.CV_8SC1);
src.put(0, 0, 2, 4, 3);
List<Byte> bs = new ArrayList<Byte>();
Converters.Mat_to_vector_char(src, bs);
List<Byte> truth = new ArrayList<Byte>();
byte value1 = 2;
byte value2 = 4;
byte value3 = 3;
truth.add(Byte.valueOf(value1));
truth.add(Byte.valueOf(value2));
truth.add(Byte.valueOf(value3));
assertEquals(truth, bs);
}
public void testMat_to_vector_DMatch() {
Mat src = new Mat(4, 1, CvType.CV_64FC4);
src.put(0, 0, 1, 4, 4, 10, 2, 3, 5, 6, 3, 1, 8, 12, 4, 9, 5, 15);
List<DMatch> matches = new ArrayList<DMatch>();
Converters.Mat_to_vector_DMatch(src, matches);
List<DMatch> truth = new ArrayList<DMatch>();
truth.add(new DMatch(1, 4, 4, 10));
truth.add(new DMatch(2, 3, 5, 6));
truth.add(new DMatch(3, 1, 8, 12));
truth.add(new DMatch(4, 9, 5, 15));
//assertListDMatchEquals(truth, matches, EPS);
fail("Not yet implemented");
}
public void testMat_to_vector_float() {
Mat src = new Mat(4, 1, CvType.CV_32FC1);
src.put(0, 0, 2, 4, 3, 9);
List<Float> fs = new ArrayList<Float>();
Converters.Mat_to_vector_float(src, fs);
List<Float> truth = new ArrayList<Float>();
truth.add(2.0f);
truth.add(4.0f);
truth.add(3.0f);
truth.add(9.0f);
assertListEquals(truth, fs, EPS);
}
public void testMat_to_vector_int() {
Mat src = new Mat(4, 1, CvType.CV_32SC1);
src.put(0, 0, 2, 4, 3, 9);
List<Integer> fs = new ArrayList<Integer>();
Converters.Mat_to_vector_int(src, fs);
List<Integer> truth = new ArrayList<Integer>();
truth.add(2);
truth.add(4);
truth.add(3);
truth.add(9);
assertListEquals(truth, fs);
}
public void testMat_to_vector_KeyPoint() {
Mat src = new Mat(1, 1, CvType.CV_64FC(7));
src.put(0, 0, 2, 4, 3, 9, 10, 12, 7);
List<KeyPoint> kps = new ArrayList<KeyPoint>();
Converters.Mat_to_vector_KeyPoint(src, kps);
List<KeyPoint> truth = new ArrayList<KeyPoint>();
truth.add(new KeyPoint(2, 4, 3, 9, 10, 12, 7));
assertListKeyPointEquals(truth, kps, EPS);
}
public void testMat_to_vector_Mat() {
// Mat src = new Mat(4, 1, CvType.CV_32SC2);
// src.put(0, 0, 2, 2, 3, 3, 4, 4, 5, 5);
//
// List<Mat> mats = new ArrayList<Mat>();
// Converters.Mat_to_vector_Mat(src, mats);
//
// List<Mat> truth = new ArrayList<Mat>();
// truth.add(new Mat(2, 1, CvType.CV_32SC1, Scalar.all(2.0)));
// truth.add(new Mat(2, 1, CvType.CV_32SC1, Scalar.all(3.0)));
// truth.add(new Mat(2, 1, CvType.CV_32SC1, Scalar.all(4.0)));
// truth.add(new Mat(2, 1, CvType.CV_32SC1, Scalar.all(5.0)));
// assertListEqualMat(truth, mats, EPS);
fail("Not yet implemented");
}
public void testMat_to_vector_Point() {
Mat src = new Mat(4, 1, CvType.CV_32SC2);
src.put(0, 0, 2, 4, 3, 9, 10, 4, 35, 54);
List<Point> points = new ArrayList<Point>();
Converters.Mat_to_vector_Point(src, points);
List<Point> truth = new ArrayList<Point>();
truth.add(new Point(2, 4));
truth.add(new Point(3, 9));
truth.add(new Point(10, 4));
truth.add(new Point(35, 54));
assertListPointEquals(truth, points, EPS);
}
public void testMat_to_vector_Point2d() {
Mat src = new Mat(4, 1, CvType.CV_64FC2);
src.put(0, 0, 12.0, 4.0, 3.0, 29.0, 10.0, 24.0, 35.0, 54.0);
List<Point> points = new ArrayList<Point>();
Converters.Mat_to_vector_Point2d(src, points);
List<Point> truth = new ArrayList<Point>();
truth.add(new Point(12.0, 4.0));
truth.add(new Point(3.0, 29.0));
truth.add(new Point(10.0, 24.0));
truth.add(new Point(35.0, 54.0));
assertListPointEquals(truth, points, EPS);
}
public void testMat_to_vector_Point2f() {
Mat src = new Mat(4, 1, CvType.CV_32FC2);
src.put(0, 0, 2, 14, 31, 19, 10, 44, 5, 41);
List<Point> points = new ArrayList<Point>();
Converters.Mat_to_vector_Point(src, points);
List<Point> truth = new ArrayList<Point>();
truth.add(new Point(2, 14));
truth.add(new Point(31, 19));
truth.add(new Point(10, 44));
truth.add(new Point(5, 41));
assertListPointEquals(truth, points, EPS);
}
public void testMat_to_vector_Point3() {
Mat src = new Mat(4, 1, CvType.CV_32SC3);
src.put(0, 0, 2, 14, 12, 31, 19, 22, 10, 44, 45, 5, 41, 31);
List<Point3> points = new ArrayList<Point3>();
Converters.Mat_to_vector_Point3(src, points);
List<Point3> truth = new ArrayList<Point3>();
truth.add(new Point3(2, 14, 12));
truth.add(new Point3(31, 19, 22));
truth.add(new Point3(10, 44, 45));
truth.add(new Point3(5, 41, 31));
assertListPoint3Equals(truth, points, EPS);
}
public void testMat_to_vector_Point3d() {
Mat src = new Mat(4, 1, CvType.CV_64FC3);
src.put(0, 0, 2.0, 4.0, 3.0, 5.0, 9.0, 12.0, 10.0, 14.0, 15.0, 5.0, 11.0, 31.0);
List<Point3> points = new ArrayList<Point3>();
Converters.Mat_to_vector_Point3(src, points);
List<Point3> truth = new ArrayList<Point3>();
truth.add(new Point3(2.0, 4.0, 3.0));
truth.add(new Point3(5.0, 9.0, 12.0));
truth.add(new Point3(10.0, 14.0, 15.0));
truth.add(new Point3(5.0, 11.0, 31.0));
assertListPoint3Equals(truth, points, EPS);
}
public void testMat_to_vector_Point3f() {
Mat src = new Mat(4, 1, CvType.CV_32FC3);
src.put(0, 0, 2.0, 4.0, 3.0, 5.0, 9.0, 12.0, 10.0, 14.0, 15.0, 5.0, 11.0, 31.0);
List<Point3> points = new ArrayList<Point3>();
Converters.Mat_to_vector_Point3(src, points);
List<Point3> truth = new ArrayList<Point3>();
truth.add(new Point3(2.0, 4.0, 3.0));
truth.add(new Point3(5.0, 9.0, 12.0));
truth.add(new Point3(10.0, 14.0, 15.0));
truth.add(new Point3(5.0, 11.0, 31.0));
assertListPoint3Equals(truth, points, EPS);
}
public void testMat_to_vector_Point3i() {
Mat src = new Mat(4, 1, CvType.CV_32SC3);
src.put(0, 0, 2, 14, 12, 31, 19, 22, 10, 44, 45, 5, 41, 31);
List<Point3> points = new ArrayList<Point3>();
Converters.Mat_to_vector_Point3(src, points);
List<Point3> truth = new ArrayList<Point3>();
truth.add(new Point3(2, 14, 12));
truth.add(new Point3(31, 19, 22));
truth.add(new Point3(10, 44, 45));
truth.add(new Point3(5, 41, 31));
assertListPoint3Equals(truth, points, EPS);
}
public void testMat_to_vector_Rect() {
Mat src = new Mat(2, 1, CvType.CV_32SC4);
src.put(0, 0, 2, 2, 5, 2, 0, 0, 6, 4);
List<Rect> rectangles = new ArrayList<Rect>();
Converters.Mat_to_vector_Rect(src, rectangles);
List<Rect> truth = new ArrayList<Rect>();
truth.add(new Rect(2, 2, 5, 2));
truth.add(new Rect(0, 0, 6, 4));
assertListRectEquals(truth, rectangles);
}
public void testMat_to_vector_RotatedRect() {
Mat src = new Mat(2, 1, CvType.CV_32FC(5));
src.put(0, 0, 2, 2, 5, 2, 7,
0, 6, 4, 1, 3);
List<RotatedRect> rectangles = new ArrayList<RotatedRect>();
Converters.Mat_to_vector_RotatedRect(src, rectangles);
List<RotatedRect> truth = new ArrayList<RotatedRect>();
truth.add(new RotatedRect(new Point(2, 2), new Size(5, 2), 7));
truth.add(new RotatedRect(new Point(0, 6), new Size(4, 1), 3));
assertListRotatedRectEquals(truth, rectangles);
}
public void testMat_to_vector_uchar() {
Mat src = new Mat(3, 1, CvType.CV_8UC1);
src.put(0, 0, 2, 4, 3);
List<Byte> bs = new ArrayList<Byte>();
Converters.Mat_to_vector_uchar(src, bs);
List<Byte> truth = new ArrayList<Byte>();
byte value1 = 2;
byte value2 = 4;
byte value3 = 3;
truth.add(Byte.valueOf(value1));
truth.add(Byte.valueOf(value2));
truth.add(Byte.valueOf(value3));
assertEquals(truth, bs);
}
public void testMat_to_vector_vector_char() {
fail("Not yet implemented");
}
public void testMat_to_vector_vector_DMatch() {
fail("Not yet implemented");
}
public void testMat_to_vector_vector_KeyPoint() {
fail("Not yet implemented");
}
public void testMat_to_vector_vector_Point2f() {
fail("Not yet implemented");
}
public void testVector_char_to_Mat() {
List<Byte> bytes = new ArrayList<Byte>();
byte value1 = 1;
byte value2 = 2;
byte value3 = 3;
byte value4 = 4;
bytes.add(Byte.valueOf(value1));
bytes.add(Byte.valueOf(value2));
bytes.add(Byte.valueOf(value3));
bytes.add(Byte.valueOf(value4));
dst = Converters.vector_char_to_Mat(bytes);
truth = new Mat(4, 1, CvType.CV_8SC1);
truth.put(0, 0, 1, 2, 3, 4);
assertMatEqual(truth, dst);
}
public void testVector_DMatch_to_Mat() {
List<DMatch> matches = new ArrayList<DMatch>();
matches.add(new DMatch(1, 4, 4, 10));
matches.add(new DMatch(2, 3, 5, 6));
matches.add(new DMatch(3, 1, 8, 12));
matches.add(new DMatch(4, 9, 5, 15));
dst = Converters.vector_DMatch_to_Mat(matches);
Mat truth = new Mat(4, 1, CvType.CV_64FC4);
truth.put(0, 0, 1, 4, 4, 10, 2, 3, 5, 6, 3, 1, 8, 12, 4, 9, 5, 15);
assertMatEqual(truth, dst, EPS);
}
public void testVector_double_to_Mat() {
List<Double> inputVector = new ArrayList<Double>();
inputVector.add(2.0);
inputVector.add(4.0);
inputVector.add(3.0);
inputVector.add(9.0);
dst = Converters.vector_double_to_Mat(inputVector);
truth = new Mat(4, 1, CvType.CV_64FC1);
truth.put(0, 0, 2, 4, 3, 9);
assertMatEqual(truth, dst, EPS);
}
public void testVector_float_to_Mat() {
List<Float> inputVector = new ArrayList<Float>();
inputVector.add(2.0f);
inputVector.add(4.0f);
inputVector.add(3.0f);
inputVector.add(9.0f);
dst = Converters.vector_float_to_Mat(inputVector);
truth = new Mat(4, 1, CvType.CV_32FC1);
truth.put(0, 0, 2, 4, 3, 9);
assertMatEqual(truth, dst, EPS);
}
public void testVector_int_to_Mat() {
List<Integer> inputVector = new ArrayList<Integer>();
inputVector.add(2);
inputVector.add(4);
inputVector.add(3);
inputVector.add(9);
dst = Converters.vector_int_to_Mat(inputVector);
truth = new Mat(4, 1, CvType.CV_32SC1);
truth.put(0, 0, 2, 4, 3, 9);
assertMatEqual(truth, dst);
}
public void testVector_KeyPoint_to_Mat() {
List<KeyPoint> kps = new ArrayList<KeyPoint>();
kps.add(new KeyPoint(2, 4, 3, 9, 10, 12, 7));
dst = Converters.vector_KeyPoint_to_Mat(kps);
Mat truth = new Mat(1, 1, CvType.CV_64FC(7));
truth.put(0, 0, 2, 4, 3, 9, 10, 12, 7);
assertMatEqual(truth, dst, EPS);
}
public void testVector_Mat_to_Mat() {
// List<Mat> mats = new ArrayList<Mat>();
// mats.add(new Mat(2, 1, CvType.CV_32SC1, Scalar.all(2.0)));
// mats.add(new Mat(2, 1, CvType.CV_32SC1, Scalar.all(2.0)));
// mats.add(new Mat(2, 1, CvType.CV_32SC1, Scalar.all(2.0)));
// mats.add(new Mat(2, 1, CvType.CV_32SC1, Scalar.all(2.0)));
// mats.add(gray0);
// mats.add(gray255);
//
// dst = Converters.vector_Mat_to_Mat(mats);
fail("Not yet implemented");
}
public void testVector_Point_to_Mat() {
List<Point> points = new ArrayList<Point>();
points.add(new Point(2, 4));
points.add(new Point(3, 9));
points.add(new Point(10, 4));
points.add(new Point(35, 54));
dst = Converters.vector_Point_to_Mat(points);
truth = new Mat(4, 1, CvType.CV_32SC2);
truth.put(0, 0, 2, 4, 3, 9, 10, 4, 35, 54);
assertMatEqual(truth, dst);
}
public void testVector_Point_to_MatListOfPoint() {
fail("Not yet implemented");
}
public void testVector_Point_to_MatListOfPointInt() {
fail("Not yet implemented");
}
public void testVector_Point2d_to_Mat() {
List<Point> points = new ArrayList<Point>();
points.add(new Point(12.0, 4.0));
points.add(new Point(3.0, 9.0));
points.add(new Point(1.0, 2.0));
dst = Converters.vector_Point2d_to_Mat(points);
truth = new Mat(3, 1, CvType.CV_64FC2);
truth.put(0, 0, 12.0, 4.0, 3.0, 9.0, 1.0, 2.0);
assertMatEqual(truth, dst, EPS);
}
public void testVector_Point2f_to_Mat() {
List<Point> points = new ArrayList<Point>();
points.add(new Point(2.0, 3.0));
points.add(new Point(1.0, 2.0));
points.add(new Point(1.0, 4.0));
dst = Converters.vector_Point2f_to_Mat(points);
truth = new Mat(3, 1, CvType.CV_32FC2);
truth.put(0, 0, 2.0, 3.0, 1.0, 2.0, 1.0, 4.0);
assertMatEqual(truth, dst, EPS);
}
public void testVector_Point3_to_Mat() {
List<Point3> points = new ArrayList<Point3>();
points.add(new Point3(2, 4, 3));
points.add(new Point3(5, 9, 12));
points.add(new Point3(10, 14, 15));
points.add(new Point3(5, 11, 31));
dst = Converters.vector_Point3_to_Mat(points, CvType.CV_32S);
truth = new Mat(4, 1, CvType.CV_32SC3);
truth.put(0, 0, 2.0, 4.0, 3.0, 5.0, 9.0, 12.0, 10.0, 14.0, 15.0, 5.0, 11.0, 31.0);
assertMatEqual(truth, dst);
}
public void testVector_Point3d_to_Mat() {
List<Point3> points = new ArrayList<Point3>();
points.add(new Point3(2.0, 4.0, 3.0));
points.add(new Point3(5.0, 9.0, 12.0));
points.add(new Point3(10.0, 14.0, 15.0));
points.add(new Point3(5.0, 11.0, 31.0));
dst = Converters.vector_Point3d_to_Mat(points);
truth = new Mat(4, 1, CvType.CV_64FC3);
truth.put(0, 0, 2.0, 4.0, 3.0, 5.0, 9.0, 12.0, 10.0, 14.0, 15.0, 5.0, 11.0, 31.0);
assertMatEqual(truth, dst, EPS);
}
public void testVector_Point3f_to_Mat() {
List<Point3> points = new ArrayList<Point3>();
points.add(new Point3(2.0, 4.0, 3.0));
points.add(new Point3(5.0, 9.0, 12.0));
points.add(new Point3(10.0, 14.0, 15.0));
points.add(new Point3(5.0, 11.0, 31.0));
dst = Converters.vector_Point3f_to_Mat(points);
truth = new Mat(4, 1, CvType.CV_32FC3);
truth.put(0, 0, 2.0, 4.0, 3.0, 5.0, 9.0, 12.0, 10.0, 14.0, 15.0, 5.0, 11.0, 31.0);
assertMatEqual(truth, dst, EPS);
}
public void testVector_Point3i_to_Mat() {
List<Point3> points = new ArrayList<Point3>();
points.add(new Point3(2, 4, 3));
points.add(new Point3(5, 6, 2));
points.add(new Point3(0, 4, 5));
points.add(new Point3(5, 1, 3));
dst = Converters.vector_Point3i_to_Mat(points);
truth = new Mat(4, 1, CvType.CV_32SC3);
truth.put(0, 0, 2, 4, 3, 5, 6, 2, 0, 4, 5, 5, 1, 3);
assertMatEqual(truth, dst);
}
public void testVector_Rect_to_Mat() {
List<Rect> rectangles = new ArrayList<Rect>();
rectangles.add(new Rect(2, 2, 5, 2));
rectangles.add(new Rect(0, 0, 6, 4));
dst = Converters.vector_Rect_to_Mat(rectangles);
truth = new Mat(2, 1, CvType.CV_32SC4);
truth.put(0, 0, 2, 2, 5, 2, 0, 0, 6, 4);
assertMatEqual(truth, dst);
}
public void testVector_RotatedRect_to_Mat() {
List<RotatedRect> rectangles = new ArrayList<RotatedRect>();
rectangles.add(new RotatedRect(new Point(2, 2), new Size(5, 2), 7));
rectangles.add(new RotatedRect(new Point(0, 0), new Size(6, 4), 3));
Mat dst = Converters.vector_RotatedRect_to_Mat(rectangles);
Mat truth = new Mat(2, 1, CvType.CV_32FC(5));
truth.put(0, 0, 2, 2, 5, 2, 7,
0, 0, 6, 4, 3);
assertMatEqual(truth, dst, EPS);
}
public void testVector_uchar_to_Mat() {
List<Byte> bytes = new ArrayList<Byte>();
byte value1 = 1;
byte value2 = 2;
byte value3 = 3;
byte value4 = 4;
bytes.add(Byte.valueOf(value1));
bytes.add(Byte.valueOf(value2));
bytes.add(Byte.valueOf(value3));
bytes.add(Byte.valueOf(value4));
dst = Converters.vector_uchar_to_Mat(bytes);
truth = new Mat(4, 1, CvType.CV_8UC1);
truth.put(0, 0, 1, 2, 3, 4);
assertMatEqual(truth, dst);
}
public void testVector_vector_char_to_Mat() {
fail("Not yet implemented");
}
public void testVector_vector_DMatch_to_Mat() {
fail("Not yet implemented");
}
public void testVector_vector_KeyPoint_to_Mat() {
fail("Not yet implemented");
}
public void testVector_vector_Point_to_Mat() {
fail("Not yet implemented");
}
}

View File

@ -0,0 +1,74 @@
if(NOT ANT_EXECUTABLE
OR NOT BUILD_opencv_imgcodecs
OR NOT BUILD_opencv_calib3d)
return()
endif()
project(opencv_test_java)
set(OPENCV_JAR_FILE "${OPENCV_JAR_FILE}")
get_filename_component(JAR_NAME "${OPENCV_JAR_FILE}" NAME)
set(OPENCV_JAVA_TEST_DIR "${OpenCV_BINARY_DIR}/java_test" CACHE INTERNAL "")
file(REMOVE_RECURSE "${OPENCV_JAVA_TEST_DIR}")
file(MAKE_DIRECTORY "${OPENCV_JAVA_TEST_DIR}")
file(REMOVE "${OPENCV_DEPHELPER}/${the_module}_test_source_copy")
set(test_dir ${CMAKE_CURRENT_SOURCE_DIR})
set(depends "")
# 1. gather and copy common test files (resources, utils, etc.)
copy_common_tests("${CMAKE_CURRENT_SOURCE_DIR}/../common_test" "${OPENCV_JAVA_TEST_DIR}" depends)
# 2. gather and copy tests from each module
ocv_copyfiles_append_dir(JAVA_TEST_SRC_COPY "${OPENCV_JAVA_BINDINGS_DIR}/gen/test" "${OPENCV_JAVA_TEST_DIR}/src")
list(APPEND depends gen_opencv_java_source "${OPENCV_DEPHELPER}/gen_opencv_java_source")
ocv_copyfiles_add_target(${the_module}_test_source_copy JAVA_TEST_SRC_COPY "Copy Java(Test) source files" ${depends})
set(depends ${the_module}_test_source_copy "${OPENCV_DEPHELPER}/${the_module}_test_source_copy")
# 3. gather and copy specific files for pure java
file(GLOB_RECURSE test_files RELATIVE "${test_dir}" "${test_dir}/src/*")
file(GLOB_RECURSE test_lib_files RELATIVE "${test_dir}" "${test_dir}/lib/*.jar")
foreach(f ${test_files} ${test_lib_files})
add_custom_command(OUTPUT "${OPENCV_JAVA_TEST_DIR}/${f}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${test_dir}/${f}" "${OPENCV_JAVA_TEST_DIR}/${f}"
DEPENDS "${test_dir}/${f}"
COMMENT "Copying ${f}"
)
list(APPEND depends "${test_dir}/${f}" "${OPENCV_JAVA_TEST_DIR}/${f}")
endforeach()
# Copy the OpenCV jar after it has been generated.
add_custom_command(OUTPUT "${OPENCV_JAVA_TEST_DIR}/bin/${JAR_NAME}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${OPENCV_JAR_FILE}" "${OPENCV_JAVA_TEST_DIR}/bin/${JAR_NAME}"
DEPENDS "${OPENCV_JAR_FILE}" "${OPENCV_DEPHELPER}/${the_module}_jar"
COMMENT "Copying the OpenCV jar"
)
add_custom_command(OUTPUT "${OPENCV_JAVA_TEST_DIR}/build.xml"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/build.xml" "${OPENCV_JAVA_TEST_DIR}/build.xml"
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/build.xml"
COMMENT "Copying build.xml"
)
add_custom_command(OUTPUT "${OPENCV_JAVA_TEST_DIR}/build/jar/opencv-test.jar"
COMMAND "${ANT_EXECUTABLE}" -noinput -k build
WORKING_DIRECTORY "${OPENCV_JAVA_TEST_DIR}"
DEPENDS ${depends} "${OPENCV_JAVA_TEST_DIR}/build.xml" "${CMAKE_CURRENT_SOURCE_DIR}/build.xml" "${OPENCV_JAR_FILE}" "${OPENCV_JAVA_TEST_DIR}/bin/${JAR_NAME}"
COMMENT "Build Java tests"
)
file(GENERATE OUTPUT "${OPENCV_JAVA_TEST_DIR}/ant-$<CONFIGURATION>.properties" CONTENT "opencv.lib.path=$<TARGET_FILE_DIR:${the_module}>")
add_custom_target(${PROJECT_NAME} ALL
DEPENDS ${the_module} "${OPENCV_JAVA_TEST_DIR}/build/jar/opencv-test.jar"
SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/build.xml"
)
if(ENABLE_SOLUTION_FOLDERS)
set_target_properties(${PROJECT_NAME} PROPERTIES FOLDER "tests accuracy")
endif()
add_dependencies(opencv_tests ${PROJECT_NAME})

View File

@ -0,0 +1,75 @@
<project name="OpenCV-Test">
<property environment="env"/>
<property file="ant-${opencv.build.type}.properties"/>
<property name="test.dir" value="testResults"/>
<property name="build.dir" value="build"/>
<property name="opencv.test.package" value="*"/>
<property name="opencv.test.class" value="*"/>
<property name="opencv.test.exclude" value=""/>
<path id="master-classpath">
<fileset dir="lib">
<include name="*.jar"/>
</fileset>
<fileset dir="bin">
<include name="*.jar"/>
</fileset>
</path>
<target name="clean">
<delete dir="build"/>
<delete dir="${test.dir}"/>
</target>
<target name="compile">
<mkdir dir="build/classes"/>
<javac sourcepath="" srcdir="src" destdir="build/classes" debug="on" includeantruntime="false" >
<include name="**/*.java"/>
<classpath refid="master-classpath"/>
</javac>
</target>
<target name="jar" depends="compile">
<mkdir dir="build/jar"/>
<jar destfile="build/jar/opencv-test.jar" basedir="build/classes">
<manifest>
<attribute name="Main-Class" value="org.opencv.test.OpenCVTestRunner"/>
</manifest>
</jar>
</target>
<target name="test" depends="jar">
<mkdir dir="${test.dir}"/>
<junit printsummary="withOutAndErr" haltonfailure="false" haltonerror="false" showoutput="true" logfailedtests="true" maxmemory="256m">
<sysproperty key="java.library.path" path="${opencv.lib.path}"/>
<env key="PATH" path="${opencv.lib.path}:${env.PATH}:${env.Path}"/>
<env key="DYLD_LIBRARY_PATH" path="${env.OPENCV_SAVED_DYLD_LIBRARY_PATH}"/> <!-- https://github.com/opencv/opencv/issues/14353 -->
<classpath refid="master-classpath"/>
<classpath>
<pathelement location="build/classes"/>
</classpath>
<formatter type="xml"/>
<batchtest fork="yes" todir="${test.dir}">
<zipfileset src="build/jar/opencv-test.jar" includes="**/${opencv.test.package}/${opencv.test.class}.class" excludes="**/OpenCVTest*, ${opencv.test.exclude}">
<exclude name="**/*$*.class"/>
</zipfileset>
</batchtest>
</junit>
<junitreport todir="${test.dir}">
<fileset dir="${test.dir}">
<include name="TEST-*.xml"/>
</fileset>
<report format="noframes" todir="${test.dir}"/>
</junitreport>
</target>
<target name="build" depends="jar">
</target>
<target name="buildAndTest" depends="test">
</target>
</project>

View File

@ -0,0 +1,660 @@
// TODO: This file is largely a duplicate of the one in android_test.
package org.opencv.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.List;
import junit.framework.TestCase;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Point3;
import org.opencv.core.Rect;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.core.DMatch;
import org.opencv.core.KeyPoint;
import org.opencv.imgcodecs.Imgcodecs;
public class OpenCVTestCase extends TestCase {
public static class TestSkipException extends RuntimeException {
public TestSkipException() {}
}
//change to 'true' to unblock fail on fail("Not yet implemented")
public static final boolean passNYI = true;
protected static boolean isTestCaseEnabled = true;
protected static final String XFEATURES2D = "org.opencv.xfeatures2d.";
protected static final String DEFAULT_FACTORY = "create";
protected static final int matSize = 10;
protected static final double EPS = 0.001;
protected static final double weakEPS = 0.5;
private static final String TAG = "OpenCVTestCase";
protected Mat dst;
protected Mat truth;
protected Scalar colorBlack;
protected Scalar colorWhite;
// Naming notation: <channels info>_[depth]_[dimensions]_value
// examples: gray0 - single channel 8U 2d Mat filled with 0
// grayRnd - single channel 8U 2d Mat filled with random numbers
// gray0_32f_1d
// TODO: OpenCVTestCase refactorings
// - rename matrices
// - create methods gray0() and create src1 explicitly
// - create some masks
// - use truth member everywhere - remove truth from base class - each test
// fixture should use own truth filed
protected Mat gray0;
protected Mat gray1;
protected Mat gray2;
protected Mat gray3;
protected Mat gray9;
protected Mat gray127;
protected Mat gray128;
protected Mat gray255;
protected Mat grayRnd;
protected Mat gray_16u_256;
protected Mat gray_16s_1024;
protected Mat gray0_32f;
protected Mat gray1_32f;
protected Mat gray3_32f;
protected Mat gray9_32f;
protected Mat gray255_32f;
protected Mat grayE_32f;
protected Mat grayRnd_32f;
protected Mat gray0_32f_1d;
protected Mat gray0_64f;
protected Mat gray0_64f_1d;
protected Mat rgba0;
protected Mat rgba128;
protected Mat rgbLena;
protected Mat grayChess;
protected Mat gray255_32f_3d;
protected Mat v1;
protected Mat v2;
@Override
protected void setUp() throws Exception {
super.setUp();
try {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
} catch (SecurityException e) {
System.out.println(e.toString());
System.exit(-1);
} catch (UnsatisfiedLinkError e) {
System.out.println(e.toString());
System.exit(-1);
}
Core.setErrorVerbosity(false);
String pwd;
try {
pwd = new File(".").getCanonicalPath() + File.separator;
} catch (IOException e) {
System.out.println(e);
return;
}
OpenCVTestRunner.LENA_PATH = pwd + "res/drawable/lena.png";
OpenCVTestRunner.CHESS_PATH = pwd + "res/drawable/chessboard.jpg";
OpenCVTestRunner.LBPCASCADE_FRONTALFACE_PATH = pwd + "res/raw/lbpcascade_frontalface.xml";
assert(new File(OpenCVTestRunner.LENA_PATH).exists());
assert(new File(OpenCVTestRunner.CHESS_PATH).exists());
assert(new File(OpenCVTestRunner.LBPCASCADE_FRONTALFACE_PATH).exists());
dst = new Mat();
assertTrue(dst.empty());
truth = null;
colorBlack = new Scalar(0);
colorWhite = new Scalar(255, 255, 255);
gray0 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(0));
gray1 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(1));
gray2 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(2));
gray3 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(3));
gray9 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(9));
gray127 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(127));
gray128 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(128));
gray255 = new Mat(matSize, matSize, CvType.CV_8U, new Scalar(255));
grayRnd = new Mat(matSize, matSize, CvType.CV_8U);
Core.randu(grayRnd, 0, 256);
gray_16u_256 = new Mat(matSize, matSize, CvType.CV_16U, new Scalar(256));
gray_16s_1024 = new Mat(matSize, matSize, CvType.CV_16S, new Scalar(1024));
gray0_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(0.0));
gray1_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(1.0));
gray3_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(3.0));
gray9_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(9.0));
gray255_32f = new Mat(matSize, matSize, CvType.CV_32F, new Scalar(255.0));
grayE_32f = new Mat(matSize, matSize, CvType.CV_32F);
grayE_32f = Mat.eye(matSize, matSize, CvType.CV_32FC1);
grayRnd_32f = new Mat(matSize, matSize, CvType.CV_32F);
Core.randu(grayRnd_32f, 0, 256);
gray0_64f = new Mat(matSize, matSize, CvType.CV_64F, new Scalar(0.0));
gray0_32f_1d = new Mat(1, matSize, CvType.CV_32F, new Scalar(0.0));
gray0_64f_1d = new Mat(1, matSize, CvType.CV_64F, new Scalar(0.0));
rgba0 = new Mat(matSize, matSize, CvType.CV_8UC4, Scalar.all(0));
rgba128 = new Mat(matSize, matSize, CvType.CV_8UC4, Scalar.all(128));
rgbLena = Imgcodecs.imread(OpenCVTestRunner.LENA_PATH);
grayChess = Imgcodecs.imread(OpenCVTestRunner.CHESS_PATH, 0);
gray255_32f_3d = new Mat(new int[]{matSize, matSize, matSize}, CvType.CV_32F, new Scalar(255.0));
v1 = new Mat(1, 3, CvType.CV_32F);
v1.put(0, 0, 1.0, 3.0, 2.0);
v2 = new Mat(1, 3, CvType.CV_32F);
v2.put(0, 0, 2.0, 1.0, 3.0);
}
@Override
protected void tearDown() throws Exception {
gray0.release();
gray1.release();
gray2.release();
gray3.release();
gray9.release();
gray127.release();
gray128.release();
gray255.release();
gray_16u_256.release();
gray_16s_1024.release();
grayRnd.release();
gray0_32f.release();
gray1_32f.release();
gray3_32f.release();
gray9_32f.release();
gray255_32f.release();
grayE_32f.release();
grayE_32f.release();
grayRnd_32f.release();
gray0_32f_1d.release();
gray0_64f.release();
gray0_64f_1d.release();
rgba0.release();
rgba128.release();
rgbLena.release();
grayChess.release();
gray255_32f_3d.release();
v1.release();
v2.release();
super.tearDown();
}
@Override
protected void runTest() throws Throwable {
// Do nothing if the precondition does not hold.
if (isTestCaseEnabled) {
try {
super.runTest();
} catch (TestSkipException ex) {
OpenCVTestRunner.Log(TAG + " :: " + "Test case \"" + this.getClass().getName() + "\" skipped!");
assertTrue(true);
}
} else {
OpenCVTestRunner.Log(TAG + " :: " + "Test case \"" + this.getClass().getName() + "\" disabled!");
}
}
public void runBare() throws Throwable {
Throwable exception = null;
try {
setUp();
} catch (TestSkipException ex) {
OpenCVTestRunner.Log(TAG + " :: " + "Test case \"" + this.getClass().getName() + "\" skipped!");
assertTrue(true);
return;
}
try {
runTest();
} catch (Throwable running) {
exception = running;
} finally {
try {
tearDown();
} catch (Throwable tearingDown) {
if (exception == null) exception = tearingDown;
}
}
if (exception != null) throw exception;
}
protected Mat getMat(int type, double... vals)
{
return new Mat(matSize, matSize, type, new Scalar(vals));
}
protected Mat makeMask(Mat m, double... vals)
{
m.submat(0, m.rows(), 0, m.cols() / 2).setTo(new Scalar(vals));
return m;
}
public static void fail(String msg) {
if(msg == "Not yet implemented" && passNYI)
return;
TestCase.fail(msg);
}
public static void assertGE(double v1, double v2) {
assertTrue("Failed: " + v1 + " >= " + v2, v1 >= v2);
}
public static <E extends Number> void assertListEquals(List<E> list1, List<E> list2) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
if (!list1.isEmpty())
{
if (list1.get(0) instanceof Float || list1.get(0) instanceof Double)
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertEquals(list1.get(i), list2.get(i));
}
public static <E extends Number> void assertListEquals(List<E> list1, List<E> list2, double epsilon) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertTrue(Math.abs(list1.get(i).doubleValue() - list2.get(i).doubleValue()) <= epsilon);
}
public static <E extends Number> void assertArrayEquals(E[] ar1, E[] ar2, double epsilon) {
assertEquals(ar1.length, ar2.length);
for (int i = 0; i < ar1.length; i++)
assertEquals(ar1[i].doubleValue(), ar2[i].doubleValue(), epsilon);
//assertTrue(Math.abs(ar1[i].doubleValue() - ar2[i].doubleValue()) <= epsilon);
}
public static void assertArrayEquals(byte[] ar1, byte[] ar2) {
assertEquals(ar1.length, ar2.length);
for (int i = 0; i < ar1.length; i++)
assertEquals(ar1[i], ar2[i]);
}
public static void assertArrayEquals(short[] ar1, short[] ar2) {
assertEquals(ar1.length, ar2.length);
for (int i = 0; i < ar1.length; i++)
assertEquals(ar1[i], ar2[i]);
}
public static void assertArrayEquals(double[] ar1, double[] ar2, double epsilon) {
assertEquals(ar1.length, ar2.length);
for (int i = 0; i < ar1.length; i++)
assertEquals(ar1[i], ar2[i], epsilon);
//assertTrue(Math.abs(ar1[i].doubleValue() - ar2[i].doubleValue()) <= epsilon);
}
public static void assertListMatEquals(List<Mat> list1, List<Mat> list2, double epsilon) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertMatEqual(list1.get(i), list2.get(i), epsilon);
}
public static void assertListPointEquals(List<Point> list1, List<Point> list2, double epsilon) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertPointEquals(list1.get(i), list2.get(i), epsilon);
}
public static void assertArrayPointsEquals(Point[] vp1, Point[] vp2, double epsilon) {
if (vp1.length != vp2.length) {
fail("Arrays have different sizes.");
}
for (int i = 0; i < vp1.length; i++)
assertPointEquals(vp1[i], vp2[i], epsilon);
}
public static void assertListPoint3Equals(List<Point3> list1, List<Point3> list2, double epsilon) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertPoint3Equals(list1.get(i), list2.get(i), epsilon);
}
public static void assertListRectEquals(List<Rect> list1, List<Rect> list2) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertRectEquals(list1.get(i), list2.get(i));
}
public static void assertListRotatedRectEquals(List<RotatedRect> list1, List<RotatedRect> list2) {
if (list1.size() != list2.size()) {
throw new UnsupportedOperationException();
}
for (int i = 0; i < list1.size(); i++)
assertRotatedRectEquals(list1.get(i), list2.get(i));
}
public static void assertRectEquals(Rect expected, Rect actual) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.x, actual.x);
assertEquals(msg, expected.y, actual.y);
assertEquals(msg, expected.width, actual.width);
assertEquals(msg, expected.height, actual.height);
}
public static void assertRotatedRectEquals(RotatedRect expected, RotatedRect actual) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.center.x, actual.center.x);
assertEquals(msg, expected.center.y, actual.center.y);
assertEquals(msg, expected.size.width, actual.size.width);
assertEquals(msg, expected.size.height, actual.size.height);
assertEquals(msg, expected.angle, actual.angle);
}
public static void assertMatEqual(Mat m1, Mat m2) {
compareMats(m1, m2, true);
}
public static void assertMatNotEqual(Mat m1, Mat m2) {
compareMats(m1, m2, false);
}
public static void assertMatEqual(Mat expected, Mat actual, double eps) {
compareMats(expected, actual, eps, true);
}
public static void assertMatNotEqual(Mat expected, Mat actual, double eps) {
compareMats(expected, actual, eps, false);
}
public static void assertKeyPointEqual(KeyPoint expected, KeyPoint actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertTrue(msg, Math.hypot(expected.pt.x - actual.pt.x, expected.pt.y - actual.pt.y) < eps);
assertTrue(msg, Math.abs(expected.size - actual.size) < eps);
assertTrue(msg, Math.abs(expected.angle - actual.angle) < eps);
assertTrue(msg, Math.abs(expected.response - actual.response) < eps);
assertEquals(msg, expected.octave, actual.octave);
assertEquals(msg, expected.class_id, actual.class_id);
}
public static void assertListKeyPointEquals(List<KeyPoint> expected, List<KeyPoint> actual, double epsilon) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++)
assertKeyPointEqual(expected.get(i), actual.get(i), epsilon);
}
public static void assertDMatchEqual(DMatch expected, DMatch actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.queryIdx, actual.queryIdx);
assertEquals(msg, expected.trainIdx, actual.trainIdx);
assertEquals(msg, expected.imgIdx, actual.imgIdx);
assertTrue(msg, Math.abs(expected.distance - actual.distance) < eps);
}
public static void assertScalarEqual(Scalar expected, Scalar actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertTrue(msg, Math.abs(expected.val[0] - actual.val[0]) < eps);
assertTrue(msg, Math.abs(expected.val[1] - actual.val[1]) < eps);
assertTrue(msg, Math.abs(expected.val[2] - actual.val[2]) < eps);
assertTrue(msg, Math.abs(expected.val[3] - actual.val[3]) < eps);
}
public static void assertArrayDMatchEquals(DMatch[] expected, DMatch[] actual, double epsilon) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++)
assertDMatchEqual(expected[i], actual[i], epsilon);
}
public static void assertListDMatchEquals(List<DMatch> expected, List<DMatch> actual, double epsilon) {
DMatch expectedArray[] = expected.toArray(new DMatch[0]);
DMatch actualArray[] = actual.toArray(new DMatch[0]);
assertArrayDMatchEquals(expectedArray, actualArray, epsilon);
}
public static void assertPointEquals(Point expected, Point actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.x, actual.x, eps);
assertEquals(msg, expected.y, actual.y, eps);
}
public static void assertSizeEquals(Size expected, Size actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.width, actual.width, eps);
assertEquals(msg, expected.height, actual.height, eps);
}
public static void assertPoint3Equals(Point3 expected, Point3 actual, double eps) {
String msg = "expected:<" + expected + "> but was:<" + actual + ">";
assertEquals(msg, expected.x, actual.x, eps);
assertEquals(msg, expected.y, actual.y, eps);
assertEquals(msg, expected.z, actual.z, eps);
}
static private boolean dimensionsEqual(Mat expected, Mat actual) {
if (expected.dims() != actual.dims()) {
return false;
}
if (expected.dims() > 2) {
for (int i = 0; i < expected.dims(); i++) {
if (expected.size(i) != actual.size(i)) {
return false;
}
}
return true;
} else {
return expected.cols() == actual.cols() && expected.rows() == actual.rows();
}
}
static private void compareMats(Mat expected, Mat actual, boolean isEqualityMeasured) {
if (expected.type() != actual.type() || !dimensionsEqual(expected, actual)) {
throw new UnsupportedOperationException("Can not compare " + expected + " and " + actual);
}
if (expected.depth() == CvType.CV_32F || expected.depth() == CvType.CV_64F) {
if (isEqualityMeasured)
throw new UnsupportedOperationException(
"Floating-point Mats must not be checked for exact match. Use assertMatEqual(Mat expected, Mat actual, double eps) instead.");
else
throw new UnsupportedOperationException(
"Floating-point Mats must not be checked for exact match. Use assertMatNotEqual(Mat expected, Mat actual, double eps) instead.");
}
Mat diff = new Mat();
Core.absdiff(expected, actual, diff);
Mat reshaped = diff.reshape(1);
int mistakes = Core.countNonZero(reshaped);
reshaped.release();
diff.release();
if (isEqualityMeasured)
assertTrue("Mats are different in " + mistakes + " points", 0 == mistakes);
else
assertFalse("Mats are equal", 0 == mistakes);
}
static private void compareMats(Mat expected, Mat actual, double eps, boolean isEqualityMeasured) {
if (expected.type() != actual.type() || !dimensionsEqual(expected, actual)) {
throw new UnsupportedOperationException("Can not compare " + expected + " and " + actual);
}
Mat diff = new Mat();
Core.absdiff(expected, actual, diff);
double maxDiff = Core.norm(diff, Core.NORM_INF);
if (isEqualityMeasured)
assertTrue("Max difference between expected and actual Mats is "+ maxDiff + ", that bigger than " + eps,
maxDiff <= eps);
else
assertFalse("Max difference between expected and actual Mats is "+ maxDiff + ", that less than " + eps,
maxDiff <= eps);
}
protected static String readFile(String path) {
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
StringBuffer result = new StringBuffer();
while ((line = br.readLine()) != null) {
result.append(line);
result.append("\n");
}
return result.toString();
} catch (IOException e) {
OpenCVTestRunner.Log("Failed to read file \"" + path
+ "\". Exception is thrown: " + e);
return null;
}
}
protected static void writeFile(String path, String content) {
FileOutputStream stream = null;
try {
stream = new FileOutputStream(new File(path));
FileChannel fc = stream.getChannel();
fc.write(Charset.defaultCharset().encode(content));
} catch (IOException e) {
OpenCVTestRunner.Log("Failed to write file \"" + path
+ "\". Exception is thrown: " + e);
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
OpenCVTestRunner.Log("Exception is thrown: " + e);
}
}
}
protected <T> T createClassInstance(String cname, String factoryName, Class cParams[], Object oValues[]) {
T instance = null;
assertFalse("Class name should not be empty", "".equals(cname));
String message="";
try {
Class algClass = getClassForName(cname);
Method factory = null;
if(cParams!=null && cParams.length>0) {
if(!"".equals(factoryName)) {
factory = algClass.getDeclaredMethod(factoryName, cParams);
instance = (T) factory.invoke(null, oValues);
}
else {
instance = (T) algClass.getConstructor(cParams).newInstance(oValues);
}
}
else {
if(!"".equals(factoryName)) {
factory = algClass.getDeclaredMethod(factoryName);
instance = (T) factory.invoke(null);
}
else {
instance = (T) algClass.getConstructor().newInstance();
}
}
}
catch(Exception ex) {
if (cname.startsWith(XFEATURES2D))
{
throw new TestSkipException();
}
message = TAG + " :: " + "could not instantiate " + cname + "! Exception: " + ex.getMessage();
}
assertNotNull(message, instance);
return instance;
}
protected <T> void setProperty(T instance, String propertyName, String propertyType, Object propertyValue) {
String message = "";
try {
String smethod = "set" + propertyName.substring(0,1).toUpperCase() + propertyName.substring(1);
Method setter = instance.getClass().getMethod(smethod, getClassForName(propertyType));
setter.invoke(instance, propertyValue);
}
catch(Exception ex) {
message = "Error when setting property [" + propertyName + "]: " + ex.getMessage();
}
assertTrue(message, "".equals(message));
}
protected Class getClassForName(String sclass) throws ClassNotFoundException{
if("int".equals(sclass))
return Integer.TYPE;
else if("long".equals(sclass))
return Long.TYPE;
else if("double".equals(sclass))
return Double.TYPE;
else if("float".equals(sclass))
return Float.TYPE;
else if("boolean".equals(sclass))
return Boolean.TYPE;
else if("char".equals(sclass))
return Character.TYPE;
else if("byte".equals(sclass))
return Byte.TYPE;
else if("short".equals(sclass))
return Short.TYPE;
else
return Class.forName(sclass);
}
}

View File

@ -0,0 +1,43 @@
package org.opencv.test;
import java.io.File;
import java.io.IOException;
import org.opencv.core.Mat;
public class OpenCVTestRunner {
public static String LENA_PATH = "";
public static String CHESS_PATH = "";
public static String LBPCASCADE_FRONTALFACE_PATH = "";
private static String TAG = "opencv_test_java";
public static String getTempFileName(String extension)
{
if (!extension.startsWith("."))
extension = "." + extension;
try {
File tmp = File.createTempFile("OpenCV", extension);
String path = tmp.getAbsolutePath();
tmp.delete();
return path;
} catch (IOException e) {
Log("Failed to get temp file name. Exception is thrown: " + e);
}
return null;
}
static public void Log(String message) {
System.out.println(TAG + " :: " + message);
}
static public void Log(Mat m) {
System.out.println(TAG + " :: " + m + "\n " + m.dump());
}
public static String getOutputFileName(String name)
{
return getTempFileName(name);
}
}