3 import sys, re, os.path
4 from string import Template
7 from cStringIO import StringIO
9 from StringIO import StringIO
13 "FileNode", "FileStorage", "KDTree",
20 "CV_CAP_PROP_OPENNI_",
31 #the following constants are added to this list using code automatic generation
32 #TODO: should be checked
53 "CV_CAP_PROP_DC1394_OFF",
54 "CV_CAP_PROP_DC1394_MODE_MANUAL",
55 "CV_CAP_PROP_DC1394_MODE_AUTO",
56 "CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO",
57 "CV_CAP_PROP_POS_MSEC",
58 "CV_CAP_PROP_POS_FRAMES",
59 "CV_CAP_PROP_POS_AVI_RATIO",
62 "CV_CAP_PROP_FRAME_COUNT",
65 "CV_CAP_PROP_BRIGHTNESS",
66 "CV_CAP_PROP_CONTRAST",
67 "CV_CAP_PROP_SATURATION",
70 "CV_CAP_PROP_EXPOSURE",
71 "CV_CAP_PROP_CONVERT_RGB",
72 "CV_CAP_PROP_WHITE_BALANCE_BLUE_U",
73 "CV_CAP_PROP_RECTIFICATION",
74 "CV_CAP_PROP_MONOCROME",
75 "CV_CAP_PROP_SHARPNESS",
76 "CV_CAP_PROP_AUTO_EXPOSURE",
78 "CV_CAP_PROP_TEMPERATURE",
79 "CV_CAP_PROP_TRIGGER",
80 "CV_CAP_PROP_TRIGGER_DELAY",
81 "CV_CAP_PROP_WHITE_BALANCE_RED_V",
82 "CV_CAP_PROP_MAX_DC1394",
83 "CV_CAP_GSTREAMER_QUEUE_LENGTH",
84 "CV_CAP_PROP_PVAPI_MULTICASTIP",
85 "CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING",
87 "CV_L?(BGRA?|RGBA?|GRAY|XYZ|YCrCb|Luv|Lab|HLS|YUV|HSV)\d*2L?(BGRA?|RGBA?|GRAY|XYZ|YCrCb|Luv|Lab|HLS|YUV|HSV).*",
90 "CV_YUV420(i|sp|p)2.+",
93 "CV_ADAPTIVE_THRESH_.+",
98 const_private_list = (
104 "CV_CHAIN_APPROX_.+",
111 # { Module : { public : [[name, val],...], private : [[]...] } }
118 ('CV_8U', 0 ), ('CV_8S', 1 ),
119 ('CV_16U', 2 ), ('CV_16S', 3 ),
121 ('CV_32F', 5 ), ('CV_64F', 6 ),
126 ('SVD_MODIFY_A', 1), ('SVD_NO_UV', 2), ('SVD_FULL_UV', 4),
128 ('LINE_AA', 16), ('LINE_8', 8), ('LINE_4', 4),
129 ('REDUCE_SUM', 0), ('REDUCE_AVG', 1), ('REDUCE_MAX', 2), ('REDUCE_MIN', 3),
137 ('IPL_BORDER_CONSTANT', 0 ),
138 ('IPL_BORDER_REPLICATE', 1 ),
139 ('IPL_BORDER_REFLECT', 2 ),
140 ('IPL_BORDER_WRAP', 3 ),
141 ('IPL_BORDER_REFLECT_101', 4 ),
142 ('IPL_BORDER_TRANSPARENT', 5 ),
152 ('CV_FM_LMEDS', 'CV_LMEDS'),
153 ('CV_FM_RANSAC','CV_RANSAC'),
156 ('CV_CALIB_USE_INTRINSIC_GUESS', 1),
157 ('CV_CALIB_FIX_ASPECT_RATIO', 2),
158 ('CV_CALIB_FIX_PRINCIPAL_POINT', 4),
159 ('CV_CALIB_ZERO_TANGENT_DIST', 8),
160 ('CV_CALIB_FIX_FOCAL_LENGTH', 16),
161 ('CV_CALIB_FIX_K1', 32),
162 ('CV_CALIB_FIX_K2', 64),
163 ('CV_CALIB_FIX_K3', 128),
164 ('CV_CALIB_FIX_K4', 2048),
165 ('CV_CALIB_FIX_K5', 4096),
166 ('CV_CALIB_FIX_K6', 8192),
167 ('CV_CALIB_RATIONAL_MODEL', 16384),
168 ('CV_CALIB_FIX_INTRINSIC', 256),
169 ('CV_CALIB_SAME_FOCAL_LENGTH', 512),
170 ('CV_CALIB_ZERO_DISPARITY', 1024),
178 ('CV_LKFLOW_INITIAL_GUESSES', 4 ),
179 ('CV_LKFLOW_GET_MIN_EIGENVALS', 8 ),
186 # c_type : { java/jni correspondence }
188 # "simple" : { j_type : "?", jn_type : "?", jni_type : "?", suffix : "?" },
189 "" : { "j_type" : "", "jn_type" : "long", "jni_type" : "jlong" }, # c-tor ret_type
190 "void" : { "j_type" : "void", "jn_type" : "void", "jni_type" : "void" },
191 "env" : { "j_type" : "", "jn_type" : "", "jni_type" : "JNIEnv*"},
192 "cls" : { "j_type" : "", "jn_type" : "", "jni_type" : "jclass"},
193 "bool" : { "j_type" : "boolean", "jn_type" : "boolean", "jni_type" : "jboolean", "suffix" : "Z" },
194 "int" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },
195 "long" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },
196 "float" : { "j_type" : "float", "jn_type" : "float", "jni_type" : "jfloat", "suffix" : "F" },
197 "double" : { "j_type" : "double", "jn_type" : "double", "jni_type" : "jdouble", "suffix" : "D" },
198 "size_t" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
199 "__int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
200 "int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
201 "double[]": { "j_type" : "double[]", "jn_type" : "double[]", "jni_type" : "jdoubleArray", "suffix" : "_3D" },
203 # "complex" : { j_type : "?", jn_args : (("", ""),), jn_name : "", jni_var : "", jni_name : "", "suffix" : "?" },
205 "vector_Point" : { "j_type" : "MatOfPoint", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point> %(n)s", "suffix" : "J" },
206 "vector_Point2f" : { "j_type" : "MatOfPoint2f", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point2f> %(n)s", "suffix" : "J" },
207 #"vector_Point2d" : { "j_type" : "MatOfPoint2d", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point2d> %(n)s", "suffix" : "J" },
208 "vector_Point3i" : { "j_type" : "MatOfPoint3", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point3i> %(n)s", "suffix" : "J" },
209 "vector_Point3f" : { "j_type" : "MatOfPoint3f", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point3f> %(n)s", "suffix" : "J" },
210 #"vector_Point3d" : { "j_type" : "MatOfPoint3d", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point3d> %(n)s", "suffix" : "J" },
211 "vector_KeyPoint" : { "j_type" : "MatOfKeyPoint", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<KeyPoint> %(n)s", "suffix" : "J" },
212 "vector_DMatch" : { "j_type" : "MatOfDMatch", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<DMatch> %(n)s", "suffix" : "J" },
213 "vector_Rect" : { "j_type" : "MatOfRect", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Rect> %(n)s", "suffix" : "J" },
214 "vector_uchar" : { "j_type" : "MatOfByte", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<uchar> %(n)s", "suffix" : "J" },
215 "vector_char" : { "j_type" : "MatOfByte", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<char> %(n)s", "suffix" : "J" },
216 "vector_int" : { "j_type" : "MatOfInt", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<int> %(n)s", "suffix" : "J" },
217 "vector_float" : { "j_type" : "MatOfFloat", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<float> %(n)s", "suffix" : "J" },
218 "vector_double" : { "j_type" : "MatOfDouble", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<double> %(n)s", "suffix" : "J" },
219 "vector_Vec4i" : { "j_type" : "MatOfInt4", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Vec4i> %(n)s", "suffix" : "J" },
220 "vector_Vec4f" : { "j_type" : "MatOfFloat4", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Vec4f> %(n)s", "suffix" : "J" },
221 "vector_Vec6f" : { "j_type" : "MatOfFloat6", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Vec6f> %(n)s", "suffix" : "J" },
223 "vector_Mat" : { "j_type" : "List<Mat>", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Mat> %(n)s", "suffix" : "J" },
225 "vector_vector_KeyPoint": { "j_type" : "List<MatOfKeyPoint>", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<KeyPoint> > %(n)s" },
226 "vector_vector_DMatch" : { "j_type" : "List<MatOfDMatch>", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<DMatch> > %(n)s" },
227 "vector_vector_char" : { "j_type" : "List<MatOfByte>", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<char> > %(n)s" },
228 "vector_vector_Point" : { "j_type" : "List<MatOfPoint>", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<Point> > %(n)s" },
229 "vector_vector_Point2f" : { "j_type" : "List<MatOfPoint2f>", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<Point2f> > %(n)s" },
230 "vector_vector_Point3f" : { "j_type" : "List<MatOfPoint3f>", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<Point3f> > %(n)s" },
232 "Mat" : { "j_type" : "Mat", "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
233 "jni_var" : "Mat& %(n)s = *((Mat*)%(n)s_nativeObj)",
234 "jni_type" : "jlong", #"jni_name" : "*%(n)s",
237 "Point" : { "j_type" : "Point", "jn_args" : (("double", ".x"), ("double", ".y")),
238 "jni_var" : "Point %(n)s((int)%(n)s_x, (int)%(n)s_y)", "jni_type" : "jdoubleArray",
240 "Point2f" : { "j_type" : "Point", "jn_args" : (("double", ".x"), ("double", ".y")),
241 "jni_var" : "Point2f %(n)s((float)%(n)s_x, (float)%(n)s_y)", "jni_type" : "jdoubleArray",
243 "Point2d" : { "j_type" : "Point", "jn_args" : (("double", ".x"), ("double", ".y")),
244 "jni_var" : "Point2d %(n)s(%(n)s_x, %(n)s_y)", "jni_type" : "jdoubleArray",
246 "Point3i" : { "j_type" : "Point3", "jn_args" : (("double", ".x"), ("double", ".y"), ("double", ".z")),
247 "jni_var" : "Point3i %(n)s((int)%(n)s_x, (int)%(n)s_y, (int)%(n)s_z)", "jni_type" : "jdoubleArray",
249 "Point3f" : { "j_type" : "Point3", "jn_args" : (("double", ".x"), ("double", ".y"), ("double", ".z")),
250 "jni_var" : "Point3f %(n)s((float)%(n)s_x, (float)%(n)s_y, (float)%(n)s_z)", "jni_type" : "jdoubleArray",
252 "Point3d" : { "j_type" : "Point3", "jn_args" : (("double", ".x"), ("double", ".y"), ("double", ".z")),
253 "jni_var" : "Point3d %(n)s(%(n)s_x, %(n)s_y, %(n)s_z)", "jni_type" : "jdoubleArray",
255 "KeyPoint": { "j_type" : "KeyPoint", "jn_args" : (("float", ".x"), ("float", ".y"), ("float", ".size"),
256 ("float", ".angle"), ("float", ".response"), ("int", ".octave"), ("int", ".class_id")),
257 "jni_var" : "KeyPoint %(n)s(%(n)s_x, %(n)s_y, %(n)s_size, %(n)s_angle, %(n)s_response, %(n)s_octave, %(n)s_class_id)",
258 "jni_type" : "jdoubleArray",
259 "suffix" : "FFFFFII"},
260 "DMatch" : { "j_type" : "DMatch", "jn_args" : ( ('int', 'queryIdx'), ('int', 'trainIdx'),
261 ('int', 'imgIdx'), ('float', 'distance'), ),
262 "jni_var" : "DMatch %(n)s(%(n)s_queryIdx, %(n)s_trainIdx, %(n)s_imgIdx, %(n)s_distance)",
263 "jni_type" : "jdoubleArray",
265 "Rect" : { "j_type" : "Rect", "jn_args" : (("int", ".x"), ("int", ".y"), ("int", ".width"), ("int", ".height")),
266 "jni_var" : "Rect %(n)s(%(n)s_x, %(n)s_y, %(n)s_width, %(n)s_height)", "jni_type" : "jdoubleArray",
268 "Size" : { "j_type" : "Size", "jn_args" : (("double", ".width"), ("double", ".height")),
269 "jni_var" : "Size %(n)s((int)%(n)s_width, (int)%(n)s_height)", "jni_type" : "jdoubleArray",
271 "Size2f" : { "j_type" : "Size", "jn_args" : (("double", ".width"), ("double", ".height")),
272 "jni_var" : "Size2f %(n)s((float)%(n)s_width, (float)%(n)s_height)", "jni_type" : "jdoubleArray",
274 "RotatedRect": { "j_type" : "RotatedRect", "jn_args" : (("double", ".center.x"), ("double", ".center.y"), ("double", ".size.width"), ("double", ".size.height"), ("double", ".angle")),
275 "jni_var" : "RotatedRect %(n)s(cv::Point2f(%(n)s_center_x, %(n)s_center_y), cv::Size2f(%(n)s_size_width, %(n)s_size_height), %(n)s_angle)",
276 "jni_type" : "jdoubleArray", "suffix" : "DDDDD"},
277 "Scalar" : { "j_type" : "Scalar", "jn_args" : (("double", ".val[0]"), ("double", ".val[1]"), ("double", ".val[2]"), ("double", ".val[3]")),
278 "jni_var" : "Scalar %(n)s(%(n)s_val0, %(n)s_val1, %(n)s_val2, %(n)s_val3)", "jni_type" : "jdoubleArray",
280 "Range" : { "j_type" : "Range", "jn_args" : (("int", ".start"), ("int", ".end")),
281 "jni_var" : "Range %(n)s(%(n)s_start, %(n)s_end)", "jni_type" : "jdoubleArray",
283 "CvSlice" : { "j_type" : "Range", "jn_args" : (("int", ".start"), ("int", ".end")),
284 "jni_var" : "Range %(n)s(%(n)s_start, %(n)s_end)", "jni_type" : "jdoubleArray",
286 "string" : { "j_type" : "String", "jn_type" : "String",
287 "jni_type" : "jstring", "jni_name" : "n_%(n)s",
288 "jni_var" : 'const char* utf_%(n)s = env->GetStringUTFChars(%(n)s, 0); std::string n_%(n)s( utf_%(n)s ? utf_%(n)s : "" ); env->ReleaseStringUTFChars(%(n)s, utf_%(n)s)',
289 "suffix" : "Ljava_lang_String_2"},
290 "String" : { "j_type" : "String", "jn_type" : "String",
291 "jni_type" : "jstring", "jni_name" : "n_%(n)s",
292 "jni_var" : 'const char* utf_%(n)s = env->GetStringUTFChars(%(n)s, 0); String n_%(n)s( utf_%(n)s ? utf_%(n)s : "" ); env->ReleaseStringUTFChars(%(n)s, utf_%(n)s)',
293 "suffix" : "Ljava_lang_String_2"},
294 "c_string": { "j_type" : "String", "jn_type" : "String",
295 "jni_type" : "jstring", "jni_name" : "n_%(n)s.c_str()",
296 "jni_var" : 'const char* utf_%(n)s = env->GetStringUTFChars(%(n)s, 0); std::string n_%(n)s( utf_%(n)s ? utf_%(n)s : "" ); env->ReleaseStringUTFChars(%(n)s, utf_%(n)s)',
297 "suffix" : "Ljava_lang_String_2"},
298 "TermCriteria": { "j_type" : "TermCriteria", "jn_args" : (("int", ".type"), ("int", ".maxCount"), ("double", ".epsilon")),
299 "jni_var" : "TermCriteria %(n)s(%(n)s_type, %(n)s_maxCount, %(n)s_epsilon)", "jni_type" : "jdoubleArray",
301 "CvTermCriteria": { "j_type" : "TermCriteria", "jn_args" : (("int", ".type"), ("int", ".maxCount"), ("double", ".epsilon")),
302 "jni_var" : "TermCriteria %(n)s(%(n)s_type, %(n)s_maxCount, %(n)s_epsilon)", "jni_type" : "jdoubleArray",
304 "Vec2d" : { "j_type" : "double[]", "jn_args" : (("double", ".val[0]"), ("double", ".val[1]")),
305 "jn_type" : "double[]",
306 "jni_var" : "Vec2d %(n)s(%(n)s_val0, %(n)s_val1)", "jni_type" : "jdoubleArray",
308 "Vec3d" : { "j_type" : "double[]", "jn_args" : (("double", ".val[0]"), ("double", ".val[1]"), ("double", ".val[2]")),
309 "jn_type" : "double[]",
310 "jni_var" : "Vec3d %(n)s(%(n)s_val0, %(n)s_val1, %(n)s_val2)", "jni_type" : "jdoubleArray",
315 # { class : { func : {j_code, jn_code, cpp_code} } }
322 public static class MinMaxLocResult {
323 public double minVal;
324 public double maxVal;
328 public MinMaxLocResult() {
335 // C++: minMaxLoc(Mat src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArray mask=noArray())
337 //javadoc: minMaxLoc(src, mask)
338 public static MinMaxLocResult minMaxLoc(Mat src, Mat mask) {
339 MinMaxLocResult res = new MinMaxLocResult();
340 long maskNativeObj=0;
342 maskNativeObj=mask.nativeObj;
344 double resarr[] = n_minMaxLocManual(src.nativeObj, maskNativeObj);
345 res.minVal=resarr[0];
346 res.maxVal=resarr[1];
347 res.minLoc.x=resarr[2];
348 res.minLoc.y=resarr[3];
349 res.maxLoc.x=resarr[4];
350 res.maxLoc.y=resarr[5];
354 //javadoc: minMaxLoc(src)
355 public static MinMaxLocResult minMaxLoc(Mat src) {
356 return minMaxLoc(src, null);
361 """ private static native double[] n_minMaxLocManual(long src_nativeObj, long mask_nativeObj);\n""",
364 // C++: minMaxLoc(Mat src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArray mask=noArray())
365 JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Core_n_1minMaxLocManual (JNIEnv*, jclass, jlong, jlong);
367 JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Core_n_1minMaxLocManual
368 (JNIEnv* env, jclass, jlong src_nativeObj, jlong mask_nativeObj)
371 LOGD("Core::n_1minMaxLoc()");
373 result = env->NewDoubleArray(6);
374 if (result == NULL) {
375 return NULL; /* out of memory error thrown */
378 Mat& src = *((Mat*)src_nativeObj);
380 double minVal, maxVal;
381 Point minLoc, maxLoc;
382 if (mask_nativeObj != 0) {
383 Mat& mask = *((Mat*)mask_nativeObj);
384 minMaxLoc(src, &minVal, &maxVal, &minLoc, &maxLoc, mask);
386 minMaxLoc(src, &minVal, &maxVal, &minLoc, &maxLoc);
397 env->SetDoubleArrayRegion(result, 0, 6, fill);
401 } catch(cv::Exception e) {
402 LOGD("Core::n_1minMaxLoc() catched cv::Exception: %s", e.what());
403 jclass je = env->FindClass("org/opencv/core/CvException");
404 if(!je) je = env->FindClass("java/lang/Exception");
405 env->ThrowNew(je, e.what());
408 LOGD("Core::n_1minMaxLoc() catched unknown exception (...)");
409 jclass je = env->FindClass("java/lang/Exception");
410 env->ThrowNew(je, "Unknown exception in JNI code {core::minMaxLoc()}");
422 // C++: Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine);
423 //javadoc:getTextSize(text, fontFace, fontScale, thickness, baseLine)
424 public static Size getTextSize(String text, int fontFace, double fontScale, int thickness, int[] baseLine) {
425 if(baseLine != null && baseLine.length != 1)
426 throw new java.lang.IllegalArgumentException("'baseLine' must be 'int[1]' or 'null'.");
427 Size retVal = new Size(n_getTextSize(text, fontFace, fontScale, thickness, baseLine));
432 """ private static native double[] n_getTextSize(String text, int fontFace, double fontScale, int thickness, int[] baseLine);\n""",
435 // C++: Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine);
436 JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Core_n_1getTextSize (JNIEnv*, jclass, jstring, jint, jdouble, jint, jintArray);
438 JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Core_n_1getTextSize
439 (JNIEnv* env, jclass, jstring text, jint fontFace, jdouble fontScale, jint thickness, jintArray baseLine)
442 LOGD("Core::n_1getTextSize()");
444 result = env->NewDoubleArray(2);
445 if (result == NULL) {
446 return NULL; /* out of memory error thrown */
449 const char* utf_text = env->GetStringUTFChars(text, 0);
450 std::string n_text( utf_text ? utf_text : "" );
451 env->ReleaseStringUTFChars(text, utf_text);
456 if (baseLine != NULL)
457 pbaseLine = &_baseLine;
459 cv::Size rsize = cv::getTextSize(n_text, (int)fontFace, (double)fontScale, (int)thickness, pbaseLine);
463 fill[1]=rsize.height;
465 env->SetDoubleArrayRegion(result, 0, 2, fill);
467 if (baseLine != NULL) {
468 jint jbaseLine = (jint)(*pbaseLine);
469 env->SetIntArrayRegion(baseLine, 0, 1, &jbaseLine);
474 } catch(cv::Exception e) {
475 LOGD("Core::n_1getTextSize() catched cv::Exception: %s", e.what());
476 jclass je = env->FindClass("org/opencv/core/CvException");
477 if(!je) je = env->FindClass("java/lang/Exception");
478 env->ThrowNew(je, e.what());
481 LOGD("Core::n_1getTextSize() catched unknown exception (...)");
482 jclass je = env->FindClass("java/lang/Exception");
483 env->ThrowNew(je, "Unknown exception in JNI code {core::getTextSize()}");
490 ## "checkRange" : #TBD
491 ## {'j_code' : '/* TBD: checkRange() */', 'jn_code' : '', 'cpp_code' : '' },
493 "checkHardwareSupport" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
494 "setUseOptimized" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
495 "useOptimized" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
501 "namedWindow" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
502 "destroyWindow" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
503 "destroyAllWindows" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
504 "startWindowThread" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
505 "setWindowProperty" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
506 "getWindowProperty" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
507 "getTrackbarPos" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
508 "setTrackbarPos" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
509 "imshow" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
510 "waitKey" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
511 "moveWindow" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
512 "resizeWindow" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
517 "getSupportedPreviewSizes" :
521 public java.util.List<org.opencv.core.Size> getSupportedPreviewSizes()
523 String[] sizes_str = getSupportedPreviewSizes_0(nativeObj).split(",");
524 java.util.List<org.opencv.core.Size> sizes = new java.util.ArrayList<org.opencv.core.Size>(sizes_str.length);
526 for (String str : sizes_str) {
527 String[] wh = str.split("x");
528 sizes.add(new org.opencv.core.Size(Double.parseDouble(wh[0]), Double.parseDouble(wh[1])));
536 """\n private static native String getSupportedPreviewSizes_0(long nativeObj);\n""",
539 JNIEXPORT jstring JNICALL Java_org_opencv_highgui_VideoCapture_getSupportedPreviewSizes_10
540 (JNIEnv *env, jclass, jlong self);
542 JNIEXPORT jstring JNICALL Java_org_opencv_highgui_VideoCapture_getSupportedPreviewSizes_10
543 (JNIEnv *env, jclass, jlong self)
545 static const char method_name[] = "highgui::VideoCapture_getSupportedPreviewSizes_10()";
547 LOGD(%s, method_name);
548 VideoCapture* me = (VideoCapture*) self; //TODO: check for NULL
549 union {double prop; const char* name;} u;
550 u.prop = me->get(CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING);
551 return env->NewStringUTF(u.name);
552 } catch(const std::exception &e) {
553 throwJavaException(env, &e, method_name);
555 throwJavaException(env, 0, method_name);
557 return env->NewStringUTF("");
561 }, # getSupportedPreviewSizes
565 # { class : { func : {arg_name : ctype} } }
568 'randu' : { 'low' : 'double', 'high' : 'double', },
569 'randn' : { 'mean' : 'double', 'stddev' : 'double', },
570 'inRange' : { 'lowerb' : 'Scalar', 'upperb' : 'Scalar', },
571 'goodFeaturesToTrack' : { 'corners' : 'vector_Point', },
572 'findFundamentalMat' : { 'points1' : 'vector_Point2f', 'points2' : 'vector_Point2f', },
573 'cornerSubPix' : { 'corners' : 'vector_Point2f', },
574 'minEnclosingCircle' : { 'points' : 'vector_Point2f', },
575 'findHomography' : { 'srcPoints' : 'vector_Point2f', 'dstPoints' : 'vector_Point2f', },
576 'solvePnP' : { 'objectPoints' : 'vector_Point3f', 'imagePoints' : 'vector_Point2f',
577 'distCoeffs' : 'vector_double' },
578 'solvePnPRansac' : { 'objectPoints' : 'vector_Point3f', 'imagePoints' : 'vector_Point2f',
579 'distCoeffs' : 'vector_double' },
580 'calcOpticalFlowPyrLK' : { 'prevPts' : 'vector_Point2f', 'nextPts' : 'vector_Point2f',
581 'status' : 'vector_uchar', 'err' : 'vector_float', },
582 'fitEllipse' : { 'points' : 'vector_Point2f', },
583 'fillPoly' : { 'pts' : 'vector_vector_Point', },
584 'polylines' : { 'pts' : 'vector_vector_Point', },
585 'fillConvexPoly' : { 'points' : 'vector_Point', },
586 'boundingRect' : { 'points' : 'vector_Point', },
587 'approxPolyDP' : { 'curve' : 'vector_Point2f', 'approxCurve' : 'vector_Point2f', },
588 'arcLength' : { 'curve' : 'vector_Point2f', },
589 'pointPolygonTest' : { 'contour' : 'vector_Point2f', },
590 'minAreaRect' : { 'points' : 'vector_Point2f', },
591 'getAffineTransform' : { 'src' : 'vector_Point2f', 'dst' : 'vector_Point2f', },
592 'hconcat' : { 'src' : 'vector_Mat', },
593 'vconcat' : { 'src' : 'vector_Mat', },
594 'undistortPoints' : { 'src' : 'vector_Point2f', 'dst' : 'vector_Point2f' },
595 'checkRange' : {'pos' : '*'},
596 'meanStdDev' : {'mean' : 'vector_double', 'stddev' : 'vector_double'},
597 'drawContours' : {'contours' : 'vector_vector_Point'},
598 'findContours' : {'contours' : 'vector_vector_Point'},
599 'convexityDefects' : {'contour' : 'vector_Point', 'convexhull' : 'vector_int', 'convexityDefects' : 'vector_Vec4i'},
600 'isContourConvex' : { 'contour' : 'vector_Point', },
601 'convexHull' : {'points' : 'vector_Point', 'hull' : 'vector_int', 'returnPoints' : ''},
602 'projectPoints' : { 'objectPoints' : 'vector_Point3f', 'imagePoints' : 'vector_Point2f',
603 'distCoeffs' : 'vector_double' },
604 'initCameraMatrix2D' : {'objectPoints' : 'vector_vector_Point3f', 'imagePoints' : 'vector_vector_Point2f', },
605 'findChessboardCorners' : { 'corners' : 'vector_Point2f' },
606 'drawChessboardCorners' : { 'corners' : 'vector_Point2f' },
607 }, # '', i.e. no class
611 def getLibVersion(version_hpp_path):
612 version_file = open(version_hpp_path, "rt").read()
613 epoch = re.search("^W*#\W*define\W+CV_VERSION_EPOCH\W+(\d+)\W*$", version_file, re.MULTILINE).group(1)
614 major = re.search("^W*#\W*define\W+CV_VERSION_MAJOR\W+(\d+)\W*$", version_file, re.MULTILINE).group(1)
615 minor = re.search("^W*#\W*define\W+CV_VERSION_MINOR\W+(\d+)\W*$", version_file, re.MULTILINE).group(1)
616 revision = re.search("^W*#\W*define\W+CV_VERSION_REVISION\W+(\d+)\W*$", version_file, re.MULTILINE).group(1)
617 return (epoch, major, minor, revision)
619 class ConstInfo(object):
620 def __init__(self, cname, name, val, addedManually=False):
622 self.name = re.sub(r"^Cv", "", name)
624 self.addedManually = addedManually
627 class ClassPropInfo(object):
628 def __init__(self, decl): # [f_ctype, f_name, '', '/RW']
631 self.rw = "/RW" in decl[3]
633 class ClassInfo(object):
634 def __init__(self, decl): # [ 'class/struct cname', ': base', [modlist] ]
636 name = name[name.find(" ")+1:].strip()
637 self.cname = self.name = self.jname = re.sub(r"^cv\.", "", name)
638 self.cname = self.cname.replace(".", "::")
640 self.methods_suffixes = {}
641 self.consts = [] # using a list to save the occurence order
642 self.private_consts = []
645 self.jname = self.name
647 if m.startswith("="):
651 #self.base = re.sub(r"\b"+self.jname+r"\b", "", decl[1].replace(":", "")).strip()
652 self.base = re.sub(r"^.*:", "", decl[1].split(",")[0]).strip().replace(self.jname, "")
654 class ArgInfo(object):
655 def __init__(self, arg_tuple): # [ ctype, name, def val, [mod], argno ]
658 if ctype.endswith("*"):
661 if ctype == 'vector_Point2d':
662 ctype = 'vector_Point2f'
663 elif ctype == 'vector_Point3d':
664 ctype = 'vector_Point3f'
666 self.name = arg_tuple[1]
667 self.defval = arg_tuple[2]
669 if "/O" in arg_tuple[3]:
671 if "/IO" in arg_tuple[3]:
675 class FuncInfo(object):
676 def __init__(self, decl): # [ funcname, return_ctype, [modifiers], [args] ]
677 name = re.sub(r"^cv\.", "", decl[0])
678 self.cname = name.replace(".", "::")
680 dpos = name.rfind(".")
682 classname = name[:dpos]
684 self.classname = classname
685 self.jname = self.name = name
687 self.jname = "getelem"
689 if m.startswith("="):
691 self.static = ["","static"][ "/S" in decl[2] ]
692 self.ctype = re.sub(r"^CvTermCriteria", "TermCriteria", decl[1] or "")
694 arg_fix_map = func_arg_fix.get(classname, {}).get(self.jname, {})
697 arg[0] = arg_fix_map.get(arg[1], arg[0])
703 class FuncFamilyInfo(object):
704 def __init__(self, decl): # [ funcname, return_ctype, [modifiers], [args] ]
706 self.funcs.append( FuncInfo(decl) )
707 self.jname = self.funcs[0].jname
708 self.isconstructor = self.funcs[0].name == self.funcs[0].classname
712 def add_func(self, fi):
713 self.funcs.append( fi )
716 class JavaWrapperGenerator(object):
721 self.classes = { "Mat" : ClassInfo([ 'class Mat', '', [], [] ]) }
724 self.java_code= {} # { class : {j_code, jn_code} }
726 self.ported_func_list = []
727 self.skipped_func_list = []
728 self.def_args_hist = {} # { def_args_cnt : funcs_cnt }
729 self.classes_map = []
730 self.classes_simple = []
732 def add_class_code_stream(self, class_name, cls_base = ''):
733 jname = self.classes[class_name].jname
734 self.java_code[class_name] = { "j_code" : StringIO(), "jn_code" : StringIO(), }
735 if class_name != self.Module:
737 self.java_code[class_name]["j_code"].write("""
739 // This file is auto-generated. Please don't modify it!
741 package org.opencv.%(m)s;
747 public class %(jc)s extends %(base)s {
749 protected %(jc)s(long addr) { super(addr); }
751 """ % { 'm' : self.module, 'c' : class_name, 'jc' : jname, 'base' : cls_base })
753 self.java_code[class_name]["j_code"].write("""
755 // This file is auto-generated. Please don't modify it!
757 package org.opencv.%(m)s;
763 public class %(jc)s {
765 protected final long nativeObj;
766 protected %(jc)s(long addr) { nativeObj = addr; }
768 """ % { 'm' : self.module, 'c' : class_name, 'jc' : jname })
769 else: # class_name == self.Module
770 self.java_code[class_name]["j_code"].write("""
772 // This file is auto-generated. Please don't modify it!
774 package org.opencv.%(m)s;
778 public class %(jc)s {
779 """ % { 'm' : self.module, 'jc' : jname } )
781 if class_name == 'Core':
782 (epoch, major, minor, revision) = getLibVersion(
783 (os.path.dirname(__file__) or '.') + '/../../core/include/opencv2/core/version.hpp')
784 version_str = '.'.join( (epoch, major, minor, revision) )
785 version_suffix = ''.join( (epoch, major, minor) )
786 self.classes[class_name].imports.add("java.lang.String")
787 self.java_code[class_name]["j_code"].write("""
788 public static final String VERSION = "%(v)s", NATIVE_LIBRARY_NAME = "opencv_java%(vs)s";
789 public static final int VERSION_EPOCH = %(ep)s, VERSION_MAJOR = %(ma)s, VERSION_MINOR = %(mi)s, VERSION_REVISION = %(re)s;
790 """ % { 'v' : version_str, 'vs' : version_suffix, 'ep' : epoch, 'ma' : major, 'mi' : minor, 're' : revision } )
793 def add_class(self, decl):
794 classinfo = ClassInfo(decl)
795 if classinfo.name in class_ignore_list:
797 name = classinfo.name
798 if name in self.classes:
799 print "Generator error: class %s (%s) is duplicated" % \
800 (name, classinfo.cname)
802 self.classes[name] = classinfo
803 if name in type_dict:
804 print "Duplicated class: " + name
806 if '/Simple' in decl[2]:
807 self.classes_simple.append(name)
808 if ('/Map' in decl[2]):
809 self.classes_map.append(name)
810 #adding default c-tor
811 ffi = FuncFamilyInfo(['cv.'+name+'.'+name, '', [], []])
812 classinfo.methods[ffi.jname] = ffi
814 { "j_type" : classinfo.jname,
815 "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
816 "jni_name" : "(*("+name+"*)%(n)s_nativeObj)", "jni_type" : "jlong",
818 type_dict[name+'*'] = \
819 { "j_type" : classinfo.jname,
820 "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
821 "jni_name" : "("+name+"*)%(n)s_nativeObj", "jni_type" : "jlong",
824 # missing_consts { Module : { public : [[name, val],...], private : [[]...] } }
825 if name in missing_consts:
826 if 'private' in missing_consts[name]:
827 for (n, val) in missing_consts[name]['private']:
828 classinfo.private_consts.append( ConstInfo(n, n, val, True) )
829 if 'public' in missing_consts[name]:
830 for (n, val) in missing_consts[name]['public']:
831 classinfo.consts.append( ConstInfo(n, n, val, True) )
835 if True: #"vector" not in p[0]:
836 classinfo.props.append( ClassPropInfo(p) )
838 print "Skipped property: [%s]" % name, p
840 self.add_class_code_stream(name, classinfo.base)
842 self.get_imports(name, classinfo.base)
845 def add_const(self, decl): # [ "const cname", val, [], [] ]
846 name = decl[0].replace("const ", "").strip()
847 name = re.sub(r"^cv\.", "", name)
848 cname = name.replace(".", "::")
849 for c in const_ignore_list:
850 if re.match(c, name):
853 dpos = name.rfind(".")
855 classname = name[:dpos]
858 classname = self.Module
859 if classname not in self.classes:
860 # this class isn't wrapped
861 # skipping this const
864 consts = self.classes[classname].consts
865 for c in const_private_list:
866 if re.match(c, name):
867 consts = self.classes[classname].private_consts
870 constinfo = ConstInfo(cname, name, decl[1])
871 # checking duplication
872 for list in self.classes[classname].consts, self.classes[classname].private_consts:
874 if c.name == constinfo.name:
877 print "Generator error: constant %s (%s) is duplicated" \
878 % (constinfo.name, constinfo.cname)
881 consts.append(constinfo)
883 def add_func(self, decl):
884 ffi = FuncFamilyInfo(decl)
885 classname = ffi.funcs[0].classname or self.Module
886 if classname in class_ignore_list:
888 if classname in ManualFuncs and ffi.jname in ManualFuncs[classname]:
890 if classname not in self.classes:
891 print "Generator error: the class %s for method %s is missing" % \
892 (classname, ffi.jname)
894 func_map = self.classes[classname].methods
895 if ffi.jname in func_map:
896 func_map[ffi.jname].add_func(ffi.funcs[0])
898 func_map[ffi.jname] = ffi
899 # calc args with def val
900 cnt = len([a for a in ffi.funcs[0].args if a.defval])
901 self.def_args_hist[cnt] = self.def_args_hist.get(cnt, 0) + 1
903 def save(self, path, buf):
908 def gen(self, srcfiles, module, output_path):
911 self.Module = module.capitalize()
912 parser = hdr_parser.CppHeaderParser()
914 self.add_class( ['class ' + self.Module, '', [], []] ) # [ 'class/struct cname', ':bases', [modlist] [props] ]
916 # scan the headers and build more descriptive maps of classes, consts, functions
918 decls = parser.parse(hdr)
921 if name.startswith("struct") or name.startswith("class"):
923 elif name.startswith("const"):
928 self.cpp_code = StringIO()
929 self.cpp_code.write(Template("""
931 // This file is auto-generated, please don't edit!
934 #define LOG_TAG "org.opencv.$m"
938 #include "opencv2/opencv_modules.hpp"
939 #ifdef HAVE_OPENCV_$M
940 #include "opencv2/$m/$m.hpp"
944 /// throw java exception
945 static void throwJavaException(JNIEnv *env, const std::exception *e, const char *method) {
946 std::string what = "unknown exception";
950 std::string exception_type = "std::exception";
952 if(dynamic_cast<const cv::Exception*>(e)) {
953 exception_type = "cv::Exception";
954 je = env->FindClass("org/opencv/core/CvException");
957 what = exception_type + ": " + e->what();
960 if(!je) je = env->FindClass("java/lang/Exception");
961 env->ThrowNew(je, what.c_str());
963 LOGE("%s caught %s", method, what.c_str());
964 (void)method; // avoid "unused" warning
970 """).substitute( m = module, M = module.upper() ) )
972 # generate code for the classes
973 for name in self.classes.keys():
977 # saving code streams
978 imports = "\n".join([ "import %s;" % c for c in \
979 sorted(self.classes[name].imports) if not c.startswith('org.opencv.'+self.module) ])
980 self.java_code[name]["j_code"].write("\n\n%s\n}\n" % self.java_code[name]["jn_code"].getvalue())
981 java_code = self.java_code[name]["j_code"].getvalue()
982 java_code = Template(java_code).substitute(imports = imports)
983 self.save("%s/%s+%s.java" % (output_path, module, self.classes[name].jname), java_code)
985 self.cpp_code.write( '\n} // extern "C"\n\n#endif // HAVE_OPENCV_%s\n' % module.upper() )
986 self.save(output_path+"/"+module+".cpp", self.cpp_code.getvalue())
990 report.write("PORTED FUNCs LIST (%i of %i):\n\n" % \
991 (len(self.ported_func_list), len(self.ported_func_list)+ len(self.skipped_func_list))
993 report.write("\n".join(self.ported_func_list))
994 report.write("\n\nSKIPPED FUNCs LIST (%i of %i):\n\n" % \
995 (len(self.skipped_func_list), len(self.ported_func_list)+ len(self.skipped_func_list))
997 report.write("".join(self.skipped_func_list))
999 for i in self.def_args_hist.keys():
1000 report.write("\n%i def args - %i funcs" % (i, self.def_args_hist[i]))
1002 report.write("\n\nclass as MAP:\n\t" + "\n\t".join(self.classes_map))
1003 report.write("\n\nclass SIMPLE:\n\t" + "\n\t".join(self.classes_simple))
1005 self.save(output_path+"/"+module+".txt", report.getvalue())
1007 #print "Done %i of %i funcs." % (len(self.ported_func_list), len(self.ported_func_list)+ len(self.skipped_func_list))
1011 def get_imports(self, scope_classname, ctype):
1012 imports = self.classes[scope_classname or self.Module].imports
1013 if ctype.startswith('vector_vector'):
1014 imports.add("org.opencv.core.Mat")
1015 imports.add("java.util.List")
1016 imports.add("org.opencv.utils.Converters")
1017 self.get_imports(scope_classname, ctype.replace('vector_vector', 'vector'))
1019 if ctype.startswith('vector'):
1020 imports.add("org.opencv.core.Mat")
1021 if type_dict[ctype]['j_type'].startswith('MatOf'):
1022 imports.add("org.opencv.core." + type_dict[ctype]['j_type'])
1025 imports.add("java.util.List")
1026 imports.add("org.opencv.utils.Converters")
1027 self.get_imports(scope_classname, ctype.replace('vector_', ''))
1030 if ctype in type_dict:
1031 j_type = type_dict[ctype]['j_type']
1032 elif ctype in ("Algorithm"):
1034 if j_type in ( "CvType", "Mat", "Point", "Point3", "Range", "Rect", "RotatedRect", "Scalar", "Size", "TermCriteria", "Algorithm" ):
1035 imports.add("org.opencv.core." + j_type)
1036 if j_type == 'String':
1037 imports.add("java.lang.String")
1042 def gen_func(self, fi, prop_name=''):
1043 j_code = self.java_code[fi.classname or self.Module]["j_code"]
1044 jn_code = self.java_code[fi.classname or self.Module]["jn_code"]
1045 cpp_code = self.cpp_code
1048 # e.g: void add(Mat src1, Mat src2, Mat dst, Mat mask = Mat(), int dtype = -1)
1050 c_decl = "%s %s::%s" % (fi.ctype, fi.classname, prop_name)
1054 s = a.ctype or ' _hidden_ '
1063 c_decl = "%s %s %s(%s)" % ( fi.static, fi.ctype, fi.cname, ", ".join(decl_args) )
1066 j_code.write( "\n //\n // C++: %s\n //\n\n" % c_decl )
1067 # check if we 'know' all the types
1068 if fi.ctype not in type_dict: # unsupported ret type
1069 msg = "// Return type '%s' is not supported, skipping the function\n\n" % fi.ctype
1070 self.skipped_func_list.append(c_decl + "\n" + msg)
1071 j_code.write( " "*4 + msg )
1072 print "SKIP:", c_decl.strip(), "\t due to RET type", fi.ctype
1075 if a.ctype not in type_dict:
1076 msg = "// Unknown type '%s' (%s), skipping the function\n\n" % (a.ctype, a.out or "I")
1077 self.skipped_func_list.append(c_decl + "\n" + msg)
1078 j_code.write( " "*4 + msg )
1079 print "SKIP:", c_decl.strip(), "\t due to ARG type", a.ctype, "/" + (a.out or "I")
1082 self.ported_func_list.append(c_decl)
1085 jn_code.write( "\n // C++: %s\n" % c_decl )
1086 cpp_code.write( "\n//\n// %s\n//\n" % c_decl )
1089 args = fi.args[:] # copy
1090 suffix_counter = int( self.classes[fi.classname or self.Module].methods_suffixes.get(fi.jname, -1) )
1093 self.classes[fi.classname or self.Module].methods_suffixes[fi.jname] = suffix_counter
1094 # java native method args
1096 # jni (cpp) function args
1097 jni_args = [ArgInfo([ "env", "env", "", [], "" ]), ArgInfo([ "cls", "", "", [], "" ])]
1102 if type_dict[fi.ctype]["jni_type"] == "jdoubleArray":
1103 fields = type_dict[fi.ctype]["jn_args"]
1104 c_epilogue.append( \
1105 ("jdoubleArray _da_retval_ = env->NewDoubleArray(%(cnt)i); " +
1106 "jdouble _tmp_retval_[%(cnt)i] = {%(args)s}; " +
1107 "env->SetDoubleArrayRegion(_da_retval_, 0, %(cnt)i, _tmp_retval_);") %
1108 { "cnt" : len(fields), "args" : ", ".join(["_retval_" + f[1] for f in fields]) } )
1109 if fi.classname and fi.ctype and not fi.static: # non-static class method except c-tor
1111 jn_args.append ( ArgInfo([ "__int64", "nativeObj", "", [], "" ]) )
1112 jni_args.append( ArgInfo([ "__int64", "self", "", [], "" ]) )
1113 self.get_imports(fi.classname, fi.ctype)
1115 if not a.ctype: # hidden
1117 self.get_imports(fi.classname, a.ctype)
1118 if "vector" in a.ctype: # pass as Mat
1119 jn_args.append ( ArgInfo([ "__int64", "%s_mat.nativeObj" % a.name, "", [], "" ]) )
1120 jni_args.append ( ArgInfo([ "__int64", "%s_mat_nativeObj" % a.name, "", [], "" ]) )
1121 c_prologue.append( type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";" )
1122 c_prologue.append( "Mat& %(n)s_mat = *((Mat*)%(n)s_mat_nativeObj)" % {"n" : a.name} + ";" )
1123 if "I" in a.out or not a.out:
1124 if a.ctype.startswith("vector_vector_"):
1125 self.classes[fi.classname or self.Module].imports.add("java.util.ArrayList")
1126 j_prologue.append( "List<Mat> %(n)s_tmplm = new ArrayList<Mat>((%(n)s != null) ? %(n)s.size() : 0);" % {"n" : a.name } )
1127 j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s, %(n)s_tmplm);" % {"n" : a.name, "t" : a.ctype} )
1129 if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
1130 j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s);" % {"n" : a.name, "t" : a.ctype} )
1132 j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )
1133 c_prologue.append( "Mat_to_%(t)s( %(n)s_mat, %(n)s );" % {"n" : a.name, "t" : a.ctype} )
1135 if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
1136 j_prologue.append( "Mat %s_mat = new Mat();" % a.name )
1138 j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )
1140 if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
1141 j_epilogue.append("Converters.Mat_to_%(t)s(%(n)s_mat, %(n)s);" % {"t" : a.ctype, "n" : a.name})
1142 c_epilogue.append( "%(t)s_to_Mat( %(n)s, %(n)s_mat );" % {"n" : a.name, "t" : a.ctype} )
1144 fields = type_dict[a.ctype].get("jn_args", ((a.ctype, ""),))
1145 if "I" in a.out or not a.out or a.ctype in self.classes: # input arg, pass by primitive fields
1147 jn_args.append ( ArgInfo([ f[0], a.name + f[1], "", [], "" ]) )
1148 jni_args.append( ArgInfo([ f[0], a.name + f[1].replace(".","_").replace("[","").replace("]",""), "", [], "" ]) )
1149 if a.out and a.ctype not in self.classes: # out arg, pass as double[]
1150 jn_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) )
1151 jni_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) )
1152 j_prologue.append( "double[] %s_out = new double[%i];" % (a.name, len(fields)) )
1153 c_epilogue.append( \
1154 "jdouble tmp_%(n)s[%(cnt)i] = {%(args)s}; env->SetDoubleArrayRegion(%(n)s_out, 0, %(cnt)i, tmp_%(n)s);" %
1155 { "n" : a.name, "cnt" : len(fields), "args" : ", ".join([a.name + f[1] for f in fields]) } )
1156 if a.ctype in ('bool', 'int', 'long', 'float', 'double'):
1157 j_epilogue.append('if(%(n)s!=null) %(n)s[0] = (%(t)s)%(n)s_out[0];' % {'n':a.name,'t':a.ctype})
1162 set_vals.append( "%(n)s%(f)s = %(t)s%(n)s_out[%(i)i]" %
1163 {"n" : a.name, "t": ("("+type_dict[f[0]]["j_type"]+")", "")[f[0]=="double"], "f" : f[1], "i" : i}
1166 j_epilogue.append( "if("+a.name+"!=null){ " + "; ".join(set_vals) + "; } ")
1170 # private java NATIVE method decl
1172 # private static native void add_0(long src1, long src2, long dst, long mask, int dtype);
1173 jn_code.write( Template(\
1174 " private static native $type $name($args);\n").substitute(\
1175 type = type_dict[fi.ctype].get("jn_type", "double[]"), \
1176 name = fi.jname + '_' + str(suffix_counter), \
1177 args = ", ".join(["%s %s" % (type_dict[a.ctype]["jn_type"], a.name.replace(".","_").replace("[","").replace("]","")) for a in jn_args])
1185 f_name = fi.classname + "::" + fi.name
1186 java_doc = "//javadoc: " + f_name + "(%s)" % ", ".join([a.name for a in args if a.ctype])
1187 j_code.write(" "*4 + java_doc + "\n")
1189 # public java wrapper method impl (calling native one above)
1191 # public static void add( Mat src1, Mat src2, Mat dst, Mat mask, int dtype )
1192 # { add_0( src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj, dtype ); }
1194 if fi.ctype.endswith('*'):
1195 ret_type = ret_type[:-1]
1196 ret_val = type_dict[ret_type]["j_type"] + " retVal = "
1198 ret = "return retVal;"
1199 if ret_type.startswith('vector'):
1201 j_type = type_dict[ret_type]["j_type"]
1202 if j_type.startswith('MatOf'):
1203 ret_val += j_type + ".fromNativeAddr("
1205 ret_val = "Mat retValMat = new Mat("
1206 j_prologue.append( j_type + ' retVal = new Array' + j_type+'();')
1207 self.classes[fi.classname or self.Module].imports.add('java.util.ArrayList')
1208 j_epilogue.append('Converters.Mat_to_' + ret_type + '(retValMat, retVal);')
1209 elif ret_type == "void":
1212 elif ret_type == "": # c-tor
1213 if fi.classname and self.classes[fi.classname].base:
1217 ret_val = "nativeObj = "
1219 elif ret_type in self.classes: # wrapped class
1220 ret_val = type_dict[ret_type]["j_type"] + " retVal = new " + self.classes[ret_type].jname + "("
1222 elif "jn_type" not in type_dict[ret_type]:
1223 ret_val = type_dict[fi.ctype]["j_type"] + " retVal = new " + type_dict[ret_type]["j_type"] + "("
1232 if not a.ctype: #hidden
1234 jt = type_dict[a.ctype]["j_type"]
1235 if a.out and a.ctype in ('bool', 'int', 'long', 'float', 'double'):
1237 j_args.append( jt + ' ' + a.name )
1239 j_code.write( Template(\
1240 """ public $static $j_type $j_name($j_args)
1243 $ret_val$jn_name($jn_args_call)$tail;
1251 ret_val = ret_val, \
1253 prologue = "\n ".join(j_prologue), \
1254 epilogue = "\n ".join(j_epilogue), \
1256 j_type=type_dict[fi.ctype]["j_type"], \
1258 j_args=", ".join(j_args), \
1259 jn_name=fi.jname + '_' + str(suffix_counter), \
1260 jn_args_call=", ".join( [a.name for a in jn_args] ),\
1266 # jni_func(..) { _retval_ = cv_func(..); return _retval_; }
1267 ret = "return _retval_;"
1268 default = "return 0;"
1269 if fi.ctype == "void":
1272 elif not fi.ctype: # c-tor
1273 ret = "return (jlong) _retval_;"
1274 elif fi.ctype.startswith('vector'): # c-tor
1275 ret = "return (jlong) _retval_;"
1276 elif fi.ctype == "string":
1277 ret = "return env->NewStringUTF(_retval_.c_str());"
1278 default = 'return env->NewStringUTF("");'
1279 elif fi.ctype in self.classes: # wrapped class:
1280 ret = "return (jlong) new %s(_retval_);" % fi.ctype
1281 elif ret_type in self.classes: # pointer to wrapped class:
1282 ret = "return (jlong) _retval_;"
1283 elif type_dict[fi.ctype]["jni_type"] == "jdoubleArray":
1284 ret = "return _da_retval_;"
1286 # hack: replacing func call with property set/get
1290 name = prop_name + " = "
1292 name = prop_name + ";//"
1294 cvname = "cv::" + name
1295 retval = fi.ctype + " _retval_ = "
1296 if fi.ctype == "void":
1298 elif fi.ctype.startswith('vector'):
1299 retval = type_dict[fi.ctype]['jni_var'] % {"n" : '_ret_val_vector_'} + " = "
1300 c_epilogue.append("Mat* _retval_ = new Mat();")
1301 c_epilogue.append(fi.ctype+"_to_Mat(_ret_val_vector_, *_retval_);")
1303 if not fi.ctype: # c-tor
1304 retval = fi.classname + "* _retval_ = "
1305 cvname = "new " + fi.classname
1307 cvname = "%s::%s" % (fi.classname, name)
1309 cvname = "me->" + name
1311 "%(cls)s* me = (%(cls)s*) self; //TODO: check for NULL" \
1312 % { "cls" : fi.classname} \
1320 if not a.out and not "jni_var" in type_dict[a.ctype]:
1321 # explicit cast to C type to avoid ambiguous call error on platforms (mingw)
1322 # where jni types are different from native types (e.g. jint is not the same as int)
1323 jni_name = "(%s)%s" % (a.ctype, jni_name)
1324 if not a.ctype: # hidden
1326 cvargs.append( type_dict[a.ctype].get("jni_name", jni_name) % {"n" : a.name})
1327 if "vector" not in a.ctype :
1328 if ("I" in a.out or not a.out or a.ctype in self.classes) and "jni_var" in type_dict[a.ctype]: # complex type
1329 c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";")
1330 if a.out and "I" not in a.out and a.ctype not in self.classes and a.ctype:
1331 c_prologue.append("%s %s;" % (a.ctype, a.name))
1333 rtype = type_dict[fi.ctype].get("jni_type", "jdoubleArray")
1336 clazz = self.classes[fi.classname].jname
1337 cpp_code.write ( Template( \
1339 JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname ($argst);
1341 JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname
1344 static const char method_name[] = "$module::$fname()";
1346 LOGD("%s", method_name);
1348 $retval$cvname( $cvargs );
1350 } catch(const std::exception &e) {
1351 throwJavaException(env, &e, method_name);
1353 throwJavaException(env, 0, method_name);
1361 module = self.module, \
1362 clazz = clazz.replace('_', '_1'), \
1363 fname = (fi.jname + '_' + str(suffix_counter)).replace('_', '_1'), \
1364 args = ", ".join(["%s %s" % (type_dict[a.ctype].get("jni_type"), a.name) for a in jni_args]), \
1365 argst = ", ".join([type_dict[a.ctype].get("jni_type") for a in jni_args]), \
1366 prologue = "\n ".join(c_prologue), \
1367 epilogue = " ".join(c_epilogue) + ("\n " if c_epilogue else ""), \
1370 cvargs = ", ".join(cvargs), \
1371 default = default, \
1375 # processing args with default values
1376 if not args or not args[-1].defval:
1378 while args and args[-1].defval:
1379 # 'smart' overloads filtering
1381 if a.name in ('mask', 'dtype', 'ddepth', 'lineType', 'borderType', 'borderMode', 'criteria'):
1386 def gen_class(self, name):
1387 # generate code for the class
1388 ci = self.classes[name]
1390 if ci.private_consts:
1391 self.java_code[name]['j_code'].write("""
1392 private static final int
1393 %s;\n\n""" % (",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in ci.private_consts])
1396 self.java_code[name]['j_code'].write("""
1397 public static final int
1398 %s;\n\n""" % (",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in ci.consts])
1401 fflist = ci.methods.items()
1403 for n, ffi in fflist:
1404 if ffi.isconstructor:
1405 for fi in ffi.funcs:
1409 for n, ffi in fflist:
1410 if not ffi.isconstructor:
1411 for fi in ffi.funcs:
1416 getter_name = name + ".get_" + pi.name
1418 fi = FuncInfo( [getter_name, pi.ctype, [], []] ) # [ funcname, return_ctype, [modifiers], [args] ]
1419 self.gen_func(fi, pi.name)
1422 setter_name = name + ".set_" + pi.name
1424 fi = FuncInfo( [ setter_name, "void", [], [ [pi.ctype, pi.name, "", [], ""] ] ] )
1425 self.gen_func(fi, pi.name)
1428 if name in ManualFuncs:
1429 for func in ManualFuncs[name].keys():
1430 self.java_code[name]["j_code"].write ( ManualFuncs[name][func]["j_code"] )
1431 self.java_code[name]["jn_code"].write( ManualFuncs[name][func]["jn_code"] )
1432 self.cpp_code.write( ManualFuncs[name][func]["cpp_code"] )
1434 if name != self.Module:
1436 self.java_code[name]["j_code"].write(
1439 protected void finalize() throws Throwable {
1444 self.java_code[name]["jn_code"].write(
1446 // native support for java finalize()
1447 private static native void delete(long nativeObj);
1450 # native support for java finalize()
1451 self.cpp_code.write( \
1454 // native support for java finalize()
1455 // static void %(cls)s::delete( __int64 self )
1457 JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete(JNIEnv*, jclass, jlong);
1459 JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete
1460 (JNIEnv*, jclass, jlong self)
1462 delete (%(cls)s*) self;
1465 """ % {"module" : module, "cls" : name, "j_cls" : ci.jname.replace('_', '_1')}
1469 if __name__ == "__main__":
1470 if len(sys.argv) < 4:
1472 os.path.basename(sys.argv[0]), \
1473 "<full path to hdr_parser.py> <module name> <C++ header> [<C++ header>...]"
1474 print "Current args are: ", ", ".join(["'"+a+"'" for a in sys.argv])
1478 hdr_parser_path = os.path.abspath(sys.argv[1])
1479 if hdr_parser_path.endswith(".py"):
1480 hdr_parser_path = os.path.dirname(hdr_parser_path)
1481 sys.path.append(hdr_parser_path)
1483 module = sys.argv[2]
1484 srcfiles = sys.argv[3:]
1485 #print "Generating module '" + module + "' from headers:\n\t" + "\n\t".join(srcfiles)
1486 generator = JavaWrapperGenerator()
1487 generator.gen(srcfiles, module, dstdir)