def test_compilation(): PYTHON_INCLUDES = gp()["include"] PYBIND_INCLUDES = pybind11.get_include() out = subprocess.run( "echo $(python3-config --extension-suffix)", shell=True, capture_output=True, text=True, ) SUFFIX = out.stdout.strip("\n") assert out.returncode == 0 env = os.environ.copy() env["PYTHON_INCLUDES"] = PYTHON_INCLUDES env["PYBIND_INCLUDES"] = PYBIND_INCLUDES env["SUFFIX"] = SUFFIX out = subprocess.run("cmake .", shell=True, env=env) assert out.returncode == 0 out = subprocess.run("make all", shell=True) assert out.returncode == 0
def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) # These are neede for source fetching cmake_source_dir = "opencv" build_contrib = get_build_env_var_by_name("contrib") # headless flag to skip GUI deps if needed build_headless = get_build_env_var_by_name("headless") # Only import 3rd-party modules after having installed all the build dependencies: # any of them, or their dependencies, can be updated during that process, # leading to version conflicts minimum_supported_numpy = "1.11.1" if sys.version_info[:2] >= (3, 6): minimum_supported_numpy = "1.11.3" if sys.version_info[:2] >= (3, 7): minimum_supported_numpy = "1.14.5" if sys.version_info[:2] >= (3, 8): minimum_supported_numpy = "1.17.3" numpy_version = get_or_install("numpy", minimum_supported_numpy) get_or_install("scikit-build") import skbuild if os.path.exists('.git'): import pip._internal.vcs.git as git g = git.Git() # NOTE: pip API's are internal, this has to be refactored g.run_command(["submodule", "sync"]) g.run_command(["submodule", "update", "--init", "--recursive", cmake_source_dir]) if build_contrib: g.run_command(["submodule", "update", "--init", "--recursive", "opencv_contrib"]) # https://stackoverflow.com/questions/1405913/python-32bit-or-64bit-mode x64 = sys.maxsize > 2**32 package_name = "opencv-python" if build_contrib and not build_headless: package_name = "opencv-contrib-python" if build_contrib and build_headless: package_name = "opencv-contrib-python-headless" if build_headless and not build_contrib: package_name = "opencv-python-headless" long_description = io.open('README.md', encoding="utf-8").read() package_version = get_opencv_version() packages = ['cv2', 'cv2.data'] package_data = { 'cv2': ['*%s' % sysconfig.get_config_vars().get('SO')] + (['*.dll'] if os.name == 'nt' else []) + ["LICENSE.txt", "LICENSE-3RD-PARTY.txt"], 'cv2.data': ["*.xml"] } # Files from CMake output to copy to package. # Path regexes with forward slashes relative to CMake install dir. rearrange_cmake_output_data = { 'cv2': ([r'bin/opencv_videoio_ffmpeg\d{3}%s\.dll' % ('_64' if x64 else '')] if os.name == 'nt' else []) + # In Windows, in python/X.Y/<arch>/; in Linux, in just python/X.Y/. # Naming conventions vary so widely between versions and OSes # had to give up on checking them. ['python/cv2[^/]*%(ext)s' % {'ext': re.escape(sysconfig.get_config_var('SO'))}], 'cv2.data': [ # OPENCV_OTHER_INSTALL_PATH ('etc' if os.name == 'nt' else 'share/opencv4') + r'/haarcascades/.*\.xml' ] } # Files in sourcetree outside package dir that should be copied to package. # Raw paths relative to sourcetree root. files_outside_package_dir = { 'cv2': ['LICENSE.txt', 'LICENSE-3RD-PARTY.txt'] } cmake_args = ([ "-G", "Visual Studio 14" + (" Win64" if x64 else '') ] if os.name == 'nt' else [ "-G", "Unix Makefiles" # don't make CMake try (and fail) Ninja first ]) + [ # skbuild inserts PYTHON_* vars. That doesn't satisfy opencv build scripts in case of Py3 "-DPYTHON_DEFAULT_EXECUTABLE=%s" % sys.executable, "-DPYTHON3_INCLUDE_DIR=%s" % gp()['include'], "-DBUILD_opencv_python3=ON", "-DBUILD_opencv_python2=OFF", # When off, adds __init__.py and a few more helper .py's. We use our own helper files with a different structure. "-DOPENCV_SKIP_PYTHON_LOADER=ON", # Relative dir to install the built module to in the build tree. # The default is generated from sysconfig, we'd rather have a constant for simplicity "-DOPENCV_PYTHON3_INSTALL_PATH=python", # Otherwise, opencv scripts would want to install `.pyd' right into site-packages, # and skbuild bails out on seeing that "-DINSTALL_CREATE_DISTRIB=ON", # See opencv/CMakeLists.txt for options and defaults "-DBUILD_opencv_apps=OFF", "-DBUILD_SHARED_LIBS=OFF", "-DBUILD_TESTS=OFF", "-DBUILD_PERF_TESTS=OFF", "-DBUILD_DOCS=OFF" ] + \ (["-DPYTHON3_LIBRARY=%s" % os.path.join(*[sysconfig.get_config_var('BINDIR'), "libs","python{}.lib".format("".join(str(v) for v in sys.version_info[:2]))])] if sys.platform.startswith('win') else ["-DPYTHON3_LIBRARY=%s" % os.path.join('/usr/lib/x86_64-linux-gnu/', sysconfig.get_config_var('LDLIBRARY'))]) + \ (["-DOPENCV_EXTRA_MODULES_PATH=" + os.path.abspath("opencv_contrib/modules")] if build_contrib else []) # OS-specific components if sys.platform.startswith('linux') and not build_headless: cmake_args.append("-DWITH_QT=4") if sys.platform == 'darwin' and not build_headless: cmake_args.append("-DWITH_QT=5") rearrange_cmake_output_data['cv2.qt.plugins.platforms'] = [(r'lib/qt/plugins/platforms/libqcocoa\.dylib')] if build_headless: # it seems that cocoa cannot be disabled so on macOS the package is not truly headless cmake_args.append("-DWITH_WIN32UI=OFF") cmake_args.append("-DWITH_QT=OFF") if sys.platform.startswith('linux'): cmake_args.append("-DWITH_V4L=ON") cmake_args.append("-DENABLE_PRECOMPILED_HEADERS=OFF") # Fixes for macOS builds if sys.platform == 'darwin': cmake_args.append("-DWITH_LAPACK=OFF") # Some OSX LAPACK fns are incompatible, see # https://github.com/skvark/opencv-python/issues/21 cmake_args.append("-DCMAKE_CXX_FLAGS=-stdlib=libc++") cmake_args.append("-DCMAKE_OSX_DEPLOYMENT_TARGET:STRING=10.9") subprocess.check_call("patch -p1 < patches/patchQtPlugins", shell=True) if sys.platform.startswith('linux'): cmake_args.append("-DWITH_IPP=OFF") # tests fail with IPP compiled with # devtoolset-2 GCC 4.8.2 or vanilla GCC 4.9.4 # see https://github.com/skvark/opencv-python/issues/138 if sys.platform.startswith('linux') and not x64: cmake_args.append("-DCMAKE_CXX_FLAGS=-U__STRICT_ANSI__") # patch openEXR when building on i386, see: https://github.com/openexr/openexr/issues/128 subprocess.check_call("patch -p0 < patches/patchOpenEXR", shell=True) if 'CMAKE_ARGS' in os.environ: import shlex cmake_args.extend(shlex.split(os.environ['CMAKE_ARGS'])) del shlex # ABI config variables are introduced in PEP 425 if sys.version_info[:2] < (3, 2): import warnings warnings.filterwarnings('ignore', r"Config variable '[^']+' is unset, " r"Python ABI tag may be incorrect", category=RuntimeWarning) del warnings # works via side effect RearrangeCMakeOutput(rearrange_cmake_output_data, files_outside_package_dir, package_data.keys()) skbuild.setup( name=package_name, version=package_version, url='https://github.com/skvark/opencv-python', license='MIT', description='Wrapper package for OpenCV python bindings.', long_description=long_description, long_description_content_type="text/markdown", packages=packages, package_data=package_data, maintainer="Olli-Pekka Heinisuo", include_package_data=True, ext_modules=EmptyListWithLength(), install_requires="numpy>=%s" % numpy_version, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: MacOS', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: C++', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Image Recognition', 'Topic :: Software Development', ], cmake_args=cmake_args, cmake_source_dir=cmake_source_dir, )
def get_python_include_dir() -> str: return gp()['include']
"""Prints the include path for the current Python interpreter.""" from sysconfig import get_paths as gp print(gp()['include'])
import os, sys from distutils.core import setup, Extension import numpy as np from sysconfig import get_paths as gp from pathlib import Path static_libraries = ['pygeometrictools'] static_lib_dir = os.path.join(os.getcwd(), 'lib') libraries = ['cudart', 'python3.6m', 'pthread', 'dl', 'util', 'rt', 'm'] library_dirs = ['/usr/local/cuda/lib64', str(Path(gp()['stdlib']).parent)] include_dirs = [ os.getcwd(), os.path.join(os.getcwd(), 'indicators', 'include'), gp()['include'], np.get_include(), '/usr/local/cuda/include' ] if sys.platform == 'win32': libraries.extend(static_libraries) library_dirs.append(static_lib_dir) extra_objects = [] else: # POSIX extra_objects = [ '{}/lib{}.a'.format(static_lib_dir, l) for l in static_libraries ] ext = Extension('geometrictools', sources=['pygeometrictools.cpp'], libraries=libraries, library_dirs=library_dirs, include_dirs=include_dirs,