nareshmlx/opencv-pr huggingface dataset:
**File:** modules/video/test/ocl/test_optflowpyrlk.cpp
**Change Type:** modified
**Context:** PR #8609: Fix pyrlk.cl's wrong output of calcOpticalFlowPyrLK function's output vect… - resolves #8608 I set the max error of the output err between c...

**Code Changes:**
```diff
@@ -77,6 +77,7 @@ OCL_TEST_P(PyrLKOpticalFlow, Mat)
 {
     static const int npoints = 1000;
     static const float eps = 0.03f;
+    static const float erreps = 0.1f;
 
     cv::Mat frame0 = readImage("optflow/RubberWhale1.png", cv::IMREAD_GRAYSCALE);
     ASSERT_FALSE(frame0.empty());
@@ -104,6 +105,8 @@ OCL_TEST_P(PyrLKOpticalFlow, Mat)
     ASSERT_EQ(cpuStatusCPU.size(), status.size());
```

Review comment:
> This test not only works for OpenCL, but also works for the CUDA and any other optimized version code. CUDA has own API. Available code path for this function is: CPU, CPU optimized with intrinsic (SSE/NEON), OpenCL, OpenVX (disabled due accuracy). > How about that I add a new test specifically for OpenCL No, you should not do this. At least you can't force OpenCL code path, especially if there is no OpenCL device or something is not supported (like `ocl::Image2D::isFormatSupported(CV_32F, 1, false)`). This test is intended to check function output. It is launched on many platforms and we check that result is valid on all of them. > In this kernel, the input winSize bigger than 24*24 will be referred as 24*24, the input winSize smaller than 16*16 will be referred as 16*16. If OpenCL kernel doesn't support some `winSize` values (or other parameters)), then "host" code should check for these cases and bailout to other implementations.
**File:** modules/video/test/ocl/test_optflowpyrlk.cpp
**Change Type:** modified
**Context:** PR #8609: Fix pyrlk.cl's wrong output of calcOpticalFlowPyrLK function's output vect… - resolves #8608 I set the max error of the output err between c...

**Code Changes:**
```diff
@@ -77,6 +77,7 @@ OCL_TEST_P(PyrLKOpticalFlow, Mat)
 {
     static const int npoints = 1000;
     static const float eps = 0.03f;
+    static const float erreps = 0.1f;
 
     cv::Mat frame0 = readImage("optflow/RubberWhale1.png", cv::IMREAD_GRAYSCALE);
     ASSERT_FALSE(frame0.empty());
@@ -104,6 +105,8 @@ OCL_TEST_P(PyrLKOpticalFlow, Mat)
     ASSERT_EQ(cpuStatusCPU.size(), status.size());
```

Review comment:
So, How about that I add a new OpenCL kernel file in modules/video/src/opencl/ directory? When the host code check winSize within `16*16` to `24*24`, the new kernel will be called. Otherwise, the old kernel - pyrlk.cl - will be used. Is that OK?
**File:** modules/video/test/ocl/test_optflowpyrlk.cpp
**Change Type:** modified
**Context:** PR #8609: Fix pyrlk.cl's wrong output of calcOpticalFlowPyrLK function's output vect… - resolves #8608 I set the max error of the output err between c...

**Code Changes:**
```diff
@@ -77,6 +77,7 @@ OCL_TEST_P(PyrLKOpticalFlow, Mat)
 {
     static const int npoints = 1000;
     static const float eps = 0.03f;
+    static const float erreps = 0.1f;
 
     cv::Mat frame0 = readImage("optflow/RubberWhale1.png", cv::IMREAD_GRAYSCALE);
     ASSERT_FALSE(frame0.empty());
@@ -104,6 +105,8 @@ OCL_TEST_P(PyrLKOpticalFlow, Mat)
     ASSERT_EQ(cpuStatusCPU.size(), status.size());
```

Review comment:
1) I mean there is no reason to call some implementation (for example, OpenCL kernel) with unsupported parameters. You state this: > In this kernel, the input winSize bigger than 24x24 will be referred as 24x24, the input winSize smaller than 16x16 will be referred as 16x16. if this is true, then appropriate parameters check should be added. 2) All OpenCV tests should not rely on concrete implementation. So this strange condition should be eliminated, because its justification is related to concrete OpenCL implementation and it will not be accepted.
**File:** modules/core/include/opencv2/core/fast_math.hpp
**Change Type:** modified
**Context:** PR #7462: CMake: add support for dispatched CPU optimization - Related issue: #6990 Wiki page: https://github.com/alalek/opencv/wiki/CPU-optimizations...
**Review Line:** 133

**Code Changes:**
```diff
@@ -47,6 +47,12 @@
 
 #include "opencv2/core/cvdef.h"
 
+#if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ \
+    && defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__)
+#include <emmintrin.h>
+#endif
+
+
 //! @addtogroup core_utils
 //! @{
 
@@ -66,7 +72,7 @@
 #  include "tegra_round.hpp"
```

Review comment:
why is this part changed? cvFloor() and cvCeil() (together with cvRound) are some of the most performance-critical functions in the library; we want to keep them maximally efficient. Can you please revert the changes?
**File:** modules/core/include/opencv2/core/fast_math.hpp
**Change Type:** modified
**Context:** PR #7462: CMake: add support for dispatched CPU optimization - Related issue: #6990 Wiki page: https://github.com/alalek/opencv/wiki/CPU-optimizations...
**Review Line:** 133

**Code Changes:**
```diff
@@ -47,6 +47,12 @@
 
 #include "opencv2/core/cvdef.h"
 
+#if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ \
+    && defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__)
+#include <emmintrin.h>
+#endif
+
+
 //! @addtogroup core_utils
 //! @{
 
@@ -66,7 +72,7 @@
 #  include "tegra_round.hpp"
```

Review comment:
1) Modern compilers is able to apply more effective construction instead of proposed intrinsic code (`comiss+set<cond>` instead of `movmskps`). 2) In general, intrinsic code may block some compiler optimizations including loop unrolling and auto-vectorizer. 3) There is bug in some version of MSVC compiler with AVX code generation mode: it omits `_mm_set_*` statement ("value" is already stored as XMM register), so higher elements are not cleared to zero. As a result, "movemask" returns values in range 0-15, that is wrong (0-1 is expected). Related to [this code](https://github.com/opencv/opencv/blob/3.2.0/modules/video/src/lkpyramid.cpp#L466-L467). There are MSVS2015 times for "floor" processing of 1M float vector on i5-6300U: ``` Current: (samples = 100, mean = 1.46, median = 1.38, stddev = 0.20 (13.8%)) Proposed: (samples = 100, mean = 0.78, median = 0.79, stddev = 0.12 (15.2%)) ``` BTW, There are similar results for SSE4.2 and AVX2 compilation flags GCC on i5-6600: ``` Current: (samples = 10, mean = 5.82, median = 5.75, stddev = 0.15 (2.5%)) Proposed: (samples = 100, mean = 0.38, median = 0.37, stddev = 0.05 (13.8%)) ```
**File:** modules/video/src/bgfg_gaussmix2.cpp
**Change Type:** modified
**Context:** PR #8342: Update bgfg_gaussmix2.cpp to avoid divide by zero cases.

**Code Changes:**
```diff
@@ -693,11 +693,16 @@ class MOG2Invoker : public ParallelLoopBody
                 //go through all modes
                 //////
 
-                //renormalize weights
-                totalWeight = 1.f/totalWeight;
+                // Renormalize weights. In the special case that the pixel does
+                // not agree with any modes, set weights to zero (a new mode will be added below).
+                float invWeight = 0.f;
+                if (std::abs(totalWeight) > FLT_EPSILON) {
```

Review comment:
I think `DBL_EPSILON` constant can be used here instead of `1e-12f`.
**File:** modules/video/src/bgfg_gaussmix2.cpp
**Change Type:** modified
**Context:** PR #8342: Update bgfg_gaussmix2.cpp to avoid divide by zero cases.

**Code Changes:**
```diff
@@ -693,11 +693,16 @@ class MOG2Invoker : public ParallelLoopBody
                 //go through all modes
                 //////
 
-                //renormalize weights
-                totalWeight = 1.f/totalWeight;
+                // Renormalize weights. In the special case that the pixel does
+                // not agree with any modes, set weights to zero (a new mode will be added below).
+                float invWeight = 0.f;
+                if (std::abs(totalWeight) > FLT_EPSILON) {
```

Review comment:
could you use std::abs() here and comparison with FLT_EPSILON or such? We don't want to use double precision unless it's not absolutely necessary.
**File:** cmake/OpenCVFindLibsVideo.cmake
**Change Type:** modified
**Context:** PR #5723: Windows gstreamer port - Gstreamer distributes windows binaries, it was fairly trivial to make it possible to modify the Linux gstreamer cod...
**Review Line:** 23

**Code Changes:**
```diff
+    SET(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH};${CMAKE_CURRENT_LIST_DIR}")
+    FIND_PACKAGE(GstreamerWindows)
+    IF(GSTREAMER_gstbase_LIBRARY AND GSTREAMER_gstvideo_LIBRARY AND GSTREAMER_gstapp_LIBRARY AND GSTREAMER_gstpbutils_LIBRARY AND GSTREAMER_gstriff_LIBRARY)
+      set(HAVE_GSTREAMER TRUE)
+      set(GSTREAMER_BASE_VERSION 1.0)
+      set(GSTREAMER_VIDEO_VERSION 1.0)
+      set(GSTREAMER_APP_VERSION 1.0)
+      set(GSTREAMER_RIFF_VERSION 1.0)
+      set(GSTREAMER_PBUTILS_VERSION 1.0)
+    ENDIF(GSTREAMER_gstbase_LIBRARY AND GSTREAMER_gstvideo_LIBRARY AND GSTREAMER_gstapp_LIBRARY AND GSTREAMER_gstpbutils_LIBRARY AND GSTREAMER_gstriff_LIBRARY)
 
```

Review comment:
there are 3 tabs on these lines
**File:** modules/cudaoptflow/src/cuda/pyrlk.cu
**Change Type:** modified
**Context:** PR #5771: Improve sparse pyrLK optical flow - Modified sparse pyrlk optical flow to allow input of an image pyramid, which thus allows caching of imag...

**Code Changes:**
```diff
@@ -48,6 +48,8 @@
 #include "opencv2/core/cuda/limits.hpp"
 #include "opencv2/core/cuda/vec_math.hpp"
 #include "opencv2/core/cuda/reduce.hpp"
+#include "opencv2/core/cuda/filters.hpp"
+#include "opencv2/core/cuda/border_interpolate.hpp"
 
 using namespace cv::cuda;
 using namespace cv::cuda::device;
@@ -60,53 +62,240 @@ namespace pyrlk
```

Review comment:
It should be `I(y, x)`, here and below. `PtrStepSz` uses `(y, x)` coordinates order.
**File:** modules/cudaoptflow/src/cuda/pyrlk.cu
**Change Type:** modified
**Context:** PR #5771: Improve sparse pyrLK optical flow - Modified sparse pyrlk optical flow to allow input of an image pyramid, which thus allows caching of imag...

**Code Changes:**
```diff
@@ -48,6 +48,8 @@
 #include "opencv2/core/cuda/limits.hpp"
 #include "opencv2/core/cuda/vec_math.hpp"
 #include "opencv2/core/cuda/reduce.hpp"
+#include "opencv2/core/cuda/filters.hpp"
+#include "opencv2/core/cuda/border_interpolate.hpp"
 
 using namespace cv::cuda;
 using namespace cv::cuda::device;
@@ -60,53 +62,240 @@ namespace pyrlk
```

Review comment:
I think there should be no space in CUDA triple brackets `<<< ... >>>`
**File:** modules/cudaoptflow/src/pyrlk.cpp
**Change Type:** modified
**Context:** PR #5771: Improve sparse pyrLK optical flow - Modified sparse pyrlk optical flow to allow input of an image pyramid, which thus allows caching of imag...

**Code Changes:**
```diff
@@ -56,14 +56,20 @@ Ptr<DensePyrLKOpticalFlow> cv::cuda::DensePyrLKOpticalFlow::create(Size, int, in
 namespace pyrlk
 {
     void loadConstants(int2 winSize, int iters, cudaStream_t stream);
+    template<typename T, int cn> struct pyrLK_caller
+    {
+        static void sparse(PtrStepSz<typename device::TypeVec<T, cn>::vec_type> I, PtrStepSz<typename device::TypeVec<T, cn>::vec_type> J, const float2* prevPts, float2* nextPts, uchar* status, float* err, int ptcount,
+            int level, dim3 block, dim3 patch, cudaStream_t stream);
 
-    void sparse1(PtrStepSzf I, PtrStepSzf J, const float2* prevPts, float2* nextPts, uchar* status, float* err, int ptcount,
```

Review comment:
Please remove commented code.
**File:** modules/cudaoptflow/src/cuda/pyrlk.cu
**Change Type:** modified
**Context:** PR #5771: Improve sparse pyrLK optical flow - Modified sparse pyrlk optical flow to allow input of an image pyramid, which thus allows caching of imag...

**Code Changes:**
```diff
@@ -48,6 +48,8 @@
 #include "opencv2/core/cuda/limits.hpp"
 #include "opencv2/core/cuda/vec_math.hpp"
 #include "opencv2/core/cuda/reduce.hpp"
+#include "opencv2/core/cuda/filters.hpp"
+#include "opencv2/core/cuda/border_interpolate.hpp"
 
 using namespace cv::cuda;
 using namespace cv::cuda::device;
@@ -60,53 +62,240 @@ namespace pyrlk
```

Review comment:
Shouldn't you convert the value to `[0, 1]` range to match `cudaReadModeNormalizedFloat` behavior?
**File:** modules/cudaoptflow/src/cuda/pyrlk.cu
**Change Type:** modified
**Context:** PR #5771: Improve sparse pyrLK optical flow - Modified sparse pyrlk optical flow to allow input of an image pyramid, which thus allows caching of imag...

**Code Changes:**
```diff
@@ -48,6 +48,8 @@
 #include "opencv2/core/cuda/limits.hpp"
 #include "opencv2/core/cuda/vec_math.hpp"
 #include "opencv2/core/cuda/reduce.hpp"
+#include "opencv2/core/cuda/filters.hpp"
+#include "opencv2/core/cuda/border_interpolate.hpp"
 
 using namespace cv::cuda;
 using namespace cv::cuda::device;
@@ -60,53 +62,240 @@ namespace pyrlk
```

Review comment:
I think you can remove textures that are not used (`ushort`, `int` and `int4`).
**File:** modules/cudaoptflow/src/cuda/pyrlk.cu
**Change Type:** modified
**Context:** PR #5771: Improve sparse pyrLK optical flow - Modified sparse pyrlk optical flow to allow input of an image pyramid, which thus allows caching of imag...

**Code Changes:**
```diff
@@ -48,6 +48,8 @@
 #include "opencv2/core/cuda/limits.hpp"
 #include "opencv2/core/cuda/vec_math.hpp"
 #include "opencv2/core/cuda/reduce.hpp"
+#include "opencv2/core/cuda/filters.hpp"
+#include "opencv2/core/cuda/border_interpolate.hpp"
 
 using namespace cv::cuda;
 using namespace cv::cuda::device;
@@ -60,53 +62,240 @@ namespace pyrlk
```

Review comment:
Please don't use C++11 features, not all compilers support it.
**File:** modules/cudaoptflow/src/cuda/pyrlk.cu
**Change Type:** modified
**Context:** PR #5771: Improve sparse pyrLK optical flow - Modified sparse pyrlk optical flow to allow input of an image pyramid, which thus allows caching of imag...

**Code Changes:**
```diff
@@ -48,6 +48,8 @@
 #include "opencv2/core/cuda/limits.hpp"
 #include "opencv2/core/cuda/vec_math.hpp"
 #include "opencv2/core/cuda/reduce.hpp"
+#include "opencv2/core/cuda/filters.hpp"
+#include "opencv2/core/cuda/border_interpolate.hpp"
 
 using namespace cv::cuda;
 using namespace cv::cuda::device;
@@ -60,53 +62,240 @@ namespace pyrlk
```

Review comment:
Please do not use default template parameters for functions (`typename T = float`). It is C++0x feature. Just remove `= float`, the code should compile without it.
**File:** modules/cudaoptflow/src/pyrlk.cpp
**Change Type:** modified
**Context:** PR #5771: Improve sparse pyrLK optical flow - Modified sparse pyrlk optical flow to allow input of an image pyramid, which thus allows caching of imag...

**Code Changes:**
```diff
@@ -56,14 +56,20 @@ Ptr<DensePyrLKOpticalFlow> cv::cuda::DensePyrLKOpticalFlow::create(Size, int, in
 namespace pyrlk
 {
     void loadConstants(int2 winSize, int iters, cudaStream_t stream);
+    template<typename T, int cn> struct pyrLK_caller
+    {
+        static void sparse(PtrStepSz<typename device::TypeVec<T, cn>::vec_type> I, PtrStepSz<typename device::TypeVec<T, cn>::vec_type> J, const float2* prevPts, float2* nextPts, uchar* status, float* err, int ptcount,
+            int level, dim3 block, dim3 patch, cudaStream_t stream);
 
-    void sparse1(PtrStepSzf I, PtrStepSzf J, const float2* prevPts, float2* nextPts, uchar* status, float* err, int ptcount,
```

Review comment:
This line generates signed/unsigned comparison warning. Please cast `maxLevel_ + 1` to `size_t` to fix it: ``` if (prevPyr.size() != size_t(maxLevel_ + 1) || nextPyr.size() != size_t(maxLevel_ + 1)) ```
**File:** modules/java/generator/src/java/android+JavaCameraView.java
**Change Type:** modified
**Context:** PR #8168: Use the YV12 format in the Android emulator to avoid image issues - resolves #8166 ### This pullrequest changes This change forces the Andro...
**Review Line:** 317

**Code Changes:**
```diff
         public Mat rgba() {
-            Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
+            if (mPreviewFormat == ImageFormat.NV21)
+                Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
+            else if (mPreviewFormat == ImageFormat.YV12)
+                Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGB_I420, 4);  // COLOR_YUV2RGBA_YV12 produces inverted colors
+            else
+                throw new IllegalArgumentException("Preview Format can be NV21 or YV12");
+
             return mRgba;
         }
```

Review comment:
what about the "else" branch?
**File:** modules/java/generator/src/java/android+JavaCameraView.java
**Change Type:** modified
**Context:** PR #8168: Use the YV12 format in the Android emulator to avoid image issues - resolves #8166 ### This pullrequest changes This change forces the Andro...
**Review Line:** 317

**Code Changes:**
```diff
         public Mat rgba() {
-            Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
+            if (mPreviewFormat == ImageFormat.NV21)
+                Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
+            else if (mPreviewFormat == ImageFormat.YV12)
+                Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGB_I420, 4);  // COLOR_YUV2RGBA_YV12 produces inverted colors
+            else
+                throw new IllegalArgumentException("Preview Format can be NV21 or YV12");
+
             return mRgba;
         }
```

Review comment:
Is there a need for an else branch? On initialisation, the previewFormat is always set to NV21 or YV12: ``` if (Build.BRAND.equalsIgnoreCase("generic") || Build.BRAND.equalsIgnoreCase("Android")) params.setPreviewFormat(ImageFormat.YV12); // "generic" or "android" = android emulator else params.setPreviewFormat(ImageFormat.NV21); ``` I still kept the " if (mPreviewFormat == ImageFormat.YV12)" condition because I thought it looked more informative, but that part can be safely removed.
**File:** modules/java/generator/src/java/android+JavaCameraView.java
**Change Type:** modified
**Context:** PR #8168: Use the YV12 format in the Android emulator to avoid image issues - resolves #8166 ### This pullrequest changes This change forces the Andro...
**Review Line:** 317

**Code Changes:**
```diff
         public Mat rgba() {
-            Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
+            if (mPreviewFormat == ImageFormat.NV21)
+                Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
+            else if (mPreviewFormat == ImageFormat.YV12)
+                Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGB_I420, 4);  // COLOR_YUV2RGBA_YV12 produces inverted colors
+            else
+                throw new IllegalArgumentException("Preview Format can be NV21 or YV12");
+
             return mRgba;
         }
```

Review comment:
Al least we need here `else` branch with exception for non-implemented support.
**File:** modules/java/generator/src/java/android+JavaCameraView.java
**Change Type:** modified
**Context:** PR #8168: Use the YV12 format in the Android emulator to avoid image issues - resolves #8166 ### This pullrequest changes This change forces the Andro...
**Review Line:** 317

**Code Changes:**
```diff
         public Mat rgba() {
-            Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
+            if (mPreviewFormat == ImageFormat.NV21)
+                Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
+            else if (mPreviewFormat == ImageFormat.YV12)
+                Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGB_I420, 4);  // COLOR_YUV2RGBA_YV12 produces inverted colors
+            else
+                throw new IllegalArgumentException("Preview Format can be NV21 or YV12");
+
             return mRgba;
         }
```

Review comment:
the purpose of having "else" branch and "default" case in switch statement is to add some protection for possible mistakes during further modifcations, refactoring.
**File:** modules/core/src/matrix.cpp
**Change Type:** modified
**Context:** PR #8064: Fix for SGBM compute() buffer allocation failure on big images - resolves #8038 ### This pullrequest changes Fixed buffer allocation for siz...

**Code Changes:**
```diff
@@ -830,6 +830,32 @@ void Mat::reserve(size_t nelems)
     dataend = data + step.p[0]*r;
 }
 
+void Mat::reserveBuffer(size_t nbytes)
+{
+    size_t esz = 1;
+    int mtype = CV_8UC1;
+    if (!empty())
+    {
```

Review comment:
`elemSize()` is undefined for empty Mat, so you shouldn't use it.
**File:** modules/core/src/matrix.cpp
**Change Type:** modified
**Context:** PR #8064: Fix for SGBM compute() buffer allocation failure on big images - resolves #8038 ### This pullrequest changes Fixed buffer allocation for siz...

**Code Changes:**
```diff
@@ -830,6 +830,32 @@ void Mat::reserve(size_t nelems)
     dataend = data + step.p[0]*r;
 }
 
+void Mat::reserveBuffer(size_t nbytes)
+{
+    size_t esz = 1;
+    int mtype = CV_8UC1;
+    if (!empty())
+    {
```

Review comment:
`type()` is undefined for empty Mat, so you shouldn't use it.
**File:** modules/core/src/matrix.cpp
**Change Type:** modified
**Context:** PR #8064: Fix for SGBM compute() buffer allocation failure on big images - resolves #8038 ### This pullrequest changes Fixed buffer allocation for siz...

**Code Changes:**
```diff
@@ -830,6 +830,32 @@ void Mat::reserve(size_t nelems)
     dataend = data + step.p[0]*r;
 }
 
+void Mat::reserveBuffer(size_t nbytes)
+{
+    size_t esz = 1;
+    int mtype = CV_8UC1;
+    if (!empty())
+    {
```

Review comment:
`isSubmatrix()` is undefined for empty Mat, so you shouldn't use it.
**File:** modules/core/src/matrix.cpp
**Change Type:** modified
**Context:** PR #8064: Fix for SGBM compute() buffer allocation failure on big images - resolves #8038 ### This pullrequest changes Fixed buffer allocation for siz...

**Code Changes:**
```diff
@@ -830,6 +830,32 @@ void Mat::reserve(size_t nelems)
     dataend = data + step.p[0]*r;
 }
 
+void Mat::reserveBuffer(size_t nbytes)
+{
+    size_t esz = 1;
+    int mtype = CV_8UC1;
+    if (!empty())
+    {
```

Review comment:
this is incorrect assert in 32-bit case
**File:** modules/ml/src/rtrees.cpp
**Change Type:** modified
**Context:** PR #8004: RTrees: Add wrapper for RTrees_load method to enable loading trained … - …RTrees  resolves http://answers.opencv.org/question/122375/how-to-...

**Code Changes:**
```diff
@@ -41,7 +41,6 @@
 //M*/
 
 #include "precomp.hpp"
-
 namespace cv {
 namespace ml {
 
@@ -422,6 +421,12 @@ Ptr<RTrees> RTrees::create()
     return makePtr<RTreesImpl>();
```

Review comment:
Please, use the following implementation ``` FileStorage fs(filepath, FileStorage::READ); Ptr<RTrees> rtree = Algorithm::read<RTrees>(fs.root()); ``` to prevent problems like in https://github.com/opencv/opencv/issues/6662
**File:** modules/ml/src/rtrees.cpp
**Change Type:** modified
**Context:** PR #8004: RTrees: Add wrapper for RTrees_load method to enable loading trained … - …RTrees  resolves http://answers.opencv.org/question/122375/how-to-...

**Code Changes:**
```diff
@@ -41,7 +41,6 @@
 //M*/
 
 #include "precomp.hpp"
-
 namespace cv {
 namespace ml {
 
@@ -422,6 +421,12 @@ Ptr<RTrees> RTrees::create()
     return makePtr<RTreesImpl>();
```

Review comment:
Yes, it will be useful.
**File:** modules/ml/src/rtrees.cpp
**Change Type:** modified
**Context:** PR #8004: RTrees: Add wrapper for RTrees_load method to enable loading trained … - …RTrees  resolves http://answers.opencv.org/question/122375/how-to-...

**Code Changes:**
```diff
@@ -41,7 +41,6 @@
 //M*/
 
 #include "precomp.hpp"
-
 namespace cv {
 namespace ml {
 
@@ -422,6 +421,12 @@ Ptr<RTrees> RTrees::create()
     return makePtr<RTreesImpl>();
```

Review comment:
I see the problem. We can use `getFirstTopLevelNode()` to have compliance with the `write()` method, but generally this code won't work in case if FirstTopLevelNode doesn't contain the classifier. In `read()` we can use any node and I think It's needed to introduce `nodeName` parameter into `load()` method. If it's not provided FirstTopLevelNode can be used by default.