diff --git a/cmake/OpenCVUtils.cmake b/cmake/OpenCVUtils.cmake
index 72df4d4..7d45974 100644
--- a/cmake/OpenCVUtils.cmake
+++ b/cmake/OpenCVUtils.cmake
@@ -82,12 +82,42 @@ macro(ocv_check_environment_variables)
   endforeach()
 endmacro()
 
+# check if "sub" (file or dir) is below "dir"
+function(is_subdir res dir sub )
+  get_filename_component(dir "${dir}" ABSOLUTE)
+  get_filename_component(sub "${sub}" ABSOLUTE)
+  file(TO_CMAKE_PATH "${dir}" dir)
+  file(TO_CMAKE_PATH "${sub}" sub)
+  set(dir "${dir}/")
+  string(LENGTH "${dir}" len)
+  string(LENGTH "${sub}" len_sub)
+  if(NOT len GREATER len_sub)
+    string(SUBSTRING "${sub}" 0 ${len} prefix)
+  endif()
+  if(prefix AND prefix STREQUAL dir)
+    set(${res} TRUE PARENT_SCOPE)
+  else()
+    set(${res} FALSE PARENT_SCOPE)
+  endif()
+endfunction()
+
+function(ocv_is_opencv_directory result_var dir)
+  set(result FALSE)
+  foreach(parent ${OpenCV_SOURCE_DIR} ${OpenCV_BINARY_DIR} ${OPENCV_EXTRA_MODULES_PATH})
+    is_subdir(result "${parent}" "${dir}")
+    if(result)
+      break()
+    endif()
+  endforeach()
+  set(${result_var} ${result} PARENT_SCOPE)
+endfunction()
+
 # adds include directories in such a way that directories from the OpenCV source tree go first
 function(ocv_include_directories)
   set(__add_before "")
   foreach(dir ${ARGN})
-    get_filename_component(__abs_dir "${dir}" ABSOLUTE)
-    if("${__abs_dir}" MATCHES "^${OpenCV_SOURCE_DIR}" OR "${__abs_dir}" MATCHES "^${OpenCV_BINARY_DIR}")
+    ocv_is_opencv_directory(__is_opencv_dir "${dir}")
+    if(__is_opencv_dir)
       list(APPEND __add_before "${dir}")
     elseif(CMAKE_COMPILER_IS_GNUCXX AND NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS "6.0" AND
            dir MATCHES "/usr/include$")