From 7868733002e1d7418e4c3e223de2594a2f9cfbf2 Mon Sep 17 00:00:00 2001
From: Seunghoon Park <pclove1@gmail.com>
Date: Sat, 28 Dec 2013 14:45:41 -0500
Subject: [PATCH] fixing bug #3345 (cherry picked from commit
 b036fc756a65c8be5b9b0e4d77d94b6f8099fc20)

---
 modules/imgproc/src/smooth.cpp       |  2 +-
 modules/imgproc/test/test_filter.cpp | 30 ++++++++++++++++++++++++++++
 2 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/modules/imgproc/src/smooth.cpp b/modules/imgproc/src/smooth.cpp
index bbce3deedf..ae14ca9e11 100644
--- a/modules/imgproc/src/smooth.cpp
+++ b/modules/imgproc/src/smooth.cpp
@@ -718,7 +718,7 @@ void cv::boxFilter( InputArray _src, OutputArray _dst, int ddepth,
         ddepth = sdepth;
     _dst.create( src.size(), CV_MAKETYPE(ddepth, cn) );
     Mat dst = _dst.getMat();
-    if( borderType != BORDER_CONSTANT && normalize )
+    if( borderType != BORDER_CONSTANT && normalize && (borderType & BORDER_ISOLATED) != 0 )
     {
         if( src.rows == 1 )
             ksize.height = 1;
diff --git a/modules/imgproc/test/test_filter.cpp b/modules/imgproc/test/test_filter.cpp
index efbad99749..d1e45b0414 100644
--- a/modules/imgproc/test/test_filter.cpp
+++ b/modules/imgproc/test/test_filter.cpp
@@ -1886,3 +1886,33 @@ protected:
 };
 
 TEST(Imgproc_Filtering, supportedFormats) { CV_FilterSupportedFormatsTest test; test.safe_run(); }
+
+TEST(Imgproc_Blur, borderTypes)
+{
+    Size kernelSize(3, 3);
+
+    /// ksize > src_roi.size()
+    Mat src(3, 3, CV_8UC1, cv::Scalar::all(255)), dst;
+    Mat src_roi = src(Rect(1, 1, 1, 1));
+    src_roi.setTo(cv::Scalar::all(0));
+
+    // should work like !BORDER_ISOLATED
+    blur(src_roi, dst, kernelSize, Point(-1, -1), BORDER_REPLICATE);
+    EXPECT_EQ(227, dst.at<uchar>(0, 0));
+
+    // should work like BORDER_ISOLATED
+    blur(src_roi, dst, kernelSize, Point(-1, -1), BORDER_ISOLATED);
+    EXPECT_EQ(0, dst.at<uchar>(0, 0));
+
+    /// ksize <= src_roi.size()
+    src = Mat(5, 5, CV_8UC1, cv::Scalar(255));
+    src_roi = src(Rect(1, 1, 3, 3));
+    src_roi.setTo(0);
+    src.at<uchar>(2, 2) = 255;
+
+    // should work like !BORDER_ISOLATED
+    blur(src_roi, dst, kernelSize, Point(-1, -1), BORDER_REPLICATE);
+    Mat expected_dst =
+            (Mat_<uchar>(3, 3) << 170, 113, 170, 113, 28, 113, 170, 113, 170);
+    EXPECT_EQ(9 * 255, cv::sum(expected_dst == dst).val[0]);
+}
-- 
2.18.0