diff --git a/.github/issue_template.md b/.github/issue_template.md
index a9091557..79146689 100644
--- a/.github/issue_template.md
+++ b/.github/issue_template.md
@@ -13,3 +13,30 @@ Write here what went wrong.
 - architecture (e.g. x86)
 - opencv-python version
 
+##### Issue submission checklist
+
+ - [ ] This is not a generic OpenCV usage question (looking for help for coding, other usage questions, homework etc.)
+   <!--
+
+   Use Q&A forums such as https://answers.opencv.org/questions/ and https://stackoverflow.com/ and other communities
+   to discuss problems. Tickets without real issue statements related to this build toolchain will be closed.
+
+   -->
+ - [ ] I have read the README of this repository and understand that this repository provides only an automated build toolchain for OpenCV Python packages (there is no actual OpenCV code here)
+   <!--
+
+   If you have some OpenCV bug report which needs to fixed in the C++ code, 
+   please report issue to the OpenCV repository: 
+
+   https://github.com/opencv/opencv/issues
+
+   See also:
+
+   * OpenCV documentation: https://docs.opencv.org
+   * OpenCV FAQ page: https://github.com/opencv/opencv/wiki/FAQ
+   * OpenCV forum: https://answers.opencv.org
+   * Stack Overflow branch: https://stackoverflow.com/questions/tagged/opencv
+
+   -->
+ - [ ] The issue is related to the build scripts in this repository, to the pre-built binaries or is a feature request (such as "please enable this additional dependency")
+ - [ ] I'm using the latest version of ``opencv-python``
diff --git a/.github/workflows/build_wheels_linux.yml b/.github/workflows/build_wheels_linux.yml
new file mode 100644
index 00000000..98ad3dc8
--- /dev/null
+++ b/.github/workflows/build_wheels_linux.yml
@@ -0,0 +1,224 @@
+name: Build PYPI wheels for opencv-python on Linux x86_64
+
+on:
+  pull_request:
+    branches:
+      - master
+      - 3.4
+    paths-ignore:
+      - '.github/workflows/build_wheels_linux_arm.yml'
+      - '.github/workflows/build_wheels_windows*'
+      - '.github/workflows/build_wheels_macos*'
+  release:
+    types: [published, edited]
+
+
+jobs:
+  build:
+    runs-on: ubuntu-20.04
+    defaults:
+      run:
+        shell: bash
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ['3.6']
+        platform: [x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+    env:
+      ACTIONS_ALLOW_UNSECURE_COMMANDS: true
+      REPO_DIR: .
+      BUILD_COMMIT: master
+      PROJECT_SPEC: opencv-python
+      MB_PYTHON_VERSION: ${{ matrix.python-version }}
+      TRAVIS_PYTHON_VERSION: ${{ matrix.python-version }}
+      MB_ML_VER: 2014
+      TRAVIS_BUILD_DIR: ${{ github.workspace }}
+      CONFIG_PATH: travis_config.sh
+      DOCKER_IMAGE: quay.io/opencv-ci/opencv-python-manylinux2014-x86-64:20220628
+      USE_CCACHE: 0
+      UNICODE_WIDTH: 32
+      PLAT: x86_64
+      SDIST: ${{ matrix.build_sdist || 0 }}
+      ENABLE_HEADLESS: ${{ matrix.without_gui }}
+      ENABLE_CONTRIB: ${{ matrix.with_contrib }}
+    steps:
+    - name: Cleanup
+      run: find . -mindepth 1 -delete
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: false
+        fetch-depth: 0
+    - name: Update submodules
+      if: github.event_name == 'pull_request'
+      run: git submodule update --remote
+    - name: Build a package
+      run: source scripts/build.sh
+    - name: Saving all wheels
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheels
+        path: wheelhouse/opencv*.whl
+    - name: Saving a wheel accordingly to matrix
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}
+        path: wheelhouse/opencv*.whl
+
+  test:
+    needs: [build]
+    runs-on: ubuntu-20.04
+    defaults:
+      run:
+        shell: bash
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ['3.6', '3.7', '3.8', '3.9', '3.10']
+        platform: [x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+    env:
+      ACTIONS_ALLOW_UNSECURE_COMMANDS: true
+      MB_PYTHON_VERSION: ${{ matrix.python-version }}
+      NP_TEST_DEP: numpy==1.19.4
+      NP_TEST_DEP_LATEST: numpy==1.21.2
+      CONFIG_PATH: travis_config.sh
+      PLAT: x86_64
+    steps:
+    - name: Cleanup
+      run: find . -mindepth 1 -delete
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: true
+        fetch-depth: 0
+    - name: Setup Environment variables
+      run: if [ "3.10" == "${{ matrix.python-version }}" ]; then echo "TEST_DEPENDS=$(echo $NP_TEST_DEP_LATEST)" >> $GITHUB_ENV; else echo "TEST_DEPENDS=$(echo $NP_TEST_DEP)" >> $GITHUB_ENV; fi
+    - name: Download a wheel accordingly to matrix
+      uses: actions/download-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}
+        path: wheelhouse/
+    - name: Package installation and run tests
+      run: source scripts/install.sh
+
+  build_sdist:
+    runs-on: ubuntu-20.04
+    defaults:
+      run:
+        shell: bash
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: [3.8]
+        platform: [x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [1]
+    env:
+      ACTIONS_ALLOW_UNSECURE_COMMANDS: true
+      REPO_DIR: .
+      BUILD_COMMIT: master
+      PROJECT_SPEC: opencv-python
+      PLAT: x86_64
+      MB_PYTHON_VERSION: ${{ matrix.python-version }}
+      TRAVIS_PYTHON_VERSION: ${{ matrix.python-version }}
+      MB_ML_VER: 2014
+      NP_TEST_DEP: numpy==1.19.4
+      TRAVIS_BUILD_DIR: ${{ github.workspace }}
+      CONFIG_PATH: travis_config.sh
+      DOCKER_IMAGE: quay.io/opencv-ci/opencv-python-manylinux2014-x86-64:20220628
+      USE_CCACHE: 1
+      UNICODE_WIDTH: 32
+      SDIST: ${{ matrix.build_sdist || 0 }}
+      ENABLE_HEADLESS: ${{ matrix.without_gui || 0 }}
+      ENABLE_CONTRIB: ${{ matrix.with_contrib || 0 }}
+    steps:
+    - name: Cleanup
+      run: find . -mindepth 1 -delete
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: false
+        fetch-depth: 0
+    - name: Update submodules
+      if: github.event_name == 'pull_request'
+      run: git submodule update --remote
+    - name: Set up Python ${{ matrix.python-version }}
+      uses: actions/setup-python@v2
+      with:
+        python-version: ${{ matrix.python-version }}
+        architecture: ${{ matrix.platform }}
+    - name: Build a package
+      run: |
+        set -e
+        # Build and package
+        set -x
+          python -m pip install --upgrade pip
+          python -m pip install scikit-build
+          python setup.py sdist --formats=gztar
+        set +x
+        # Install and run tests
+        set -x
+        echo "skipping tests because of sdist"
+    - name: saving artifacts
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheels
+        path: dist/opencv*.tar.gz
+
+  test_release_opencv_python:
+    if: github.event_name == 'release' && github.event.release.prerelease
+    needs: [build, build_sdist, test]
+    runs-on: ubuntu-20.04
+    environment: test-opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+      - name: Upload all wheels
+        run: |
+          python -m pip install twine
+          python -m twine upload --repository testpypi -u ${{ secrets.PYPI_USERNAME }} -p ${{ secrets.PYPI_PASSWORD }} --skip-existing wheelhouse/opencv_* wheelhouse/opencv-*
+
+  release_opencv_python:
+    if: github.event_name == 'release' && !github.event.release.prerelease
+    needs: [build, build_sdist, test]
+    runs-on: ubuntu-20.04
+    environment: opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+      - name: Upload wheels for opencv_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_python-* wheelhouse/opencv-python-[^h]*
+      - name: Upload wheels for opencv_contrib_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python-* wheelhouse/opencv-contrib-python-[^h]*
+      - name: Upload wheels for opencv_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_python_headless-* wheelhouse/opencv-python-headless-*
+      - name: Upload wheels for opencv_contrib_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python_headless-* wheelhouse/opencv-contrib-python-headless-*
diff --git a/.github/workflows/build_wheels_linux_arm.yml b/.github/workflows/build_wheels_linux_arm.yml
new file mode 100644
index 00000000..4d0c3daf
--- /dev/null
+++ b/.github/workflows/build_wheels_linux_arm.yml
@@ -0,0 +1,159 @@
+name: Build PYPI wheels for opencv-python on Linux ARM
+
+on:
+  pull_request:
+    branches:
+      - master
+      - 3.4
+    paths-ignore:
+      - '.github/workflows/build_wheels_linux.yml'
+      - '.github/workflows/build_wheels_windows*'
+      - '.github/workflows/build_wheels_macos*'
+  release:
+    types: [published, edited]
+
+
+jobs:
+  build_arm:
+    runs-on: opencv-cn-lin-arm64
+    defaults:
+      run:
+        shell: bash
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ['3.6']
+        platform: [x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+    env:
+      ACTIONS_ALLOW_UNSECURE_COMMANDS: true
+      REPO_DIR: .
+      BUILD_COMMIT: master
+      PROJECT_SPEC: opencv-python
+      MB_PYTHON_VERSION: ${{ matrix.python-version }}
+      TRAVIS_PYTHON_VERSION: ${{ matrix.python-version }}
+      PLAT: aarch64
+      MB_ML_VER: 2014
+      TRAVIS_BUILD_DIR: ${{ github.workspace }}
+      CONFIG_PATH: travis_config.sh
+      DOCKER_IMAGE: quay.io/opencv-ci/opencv-python-manylinux2014-aarch64:20220628
+      USE_CCACHE: 0
+      UNICODE_WIDTH: 32
+      SDIST: ${{ matrix.build_sdist || 0 }}
+      ENABLE_HEADLESS: ${{ matrix.without_gui }}
+      ENABLE_CONTRIB: ${{ matrix.with_contrib }}
+    steps:
+    - name: UID
+      run: id -u
+    - name: Cleanup
+      run: find . -mindepth 1 -delete
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: false
+        fetch-depth: 0
+    - name: Build a package
+      run: source scripts/build.sh
+    - name: Saving all wheels
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheels
+        path: wheelhouse/opencv*.whl
+    - name: Saving a wheel accordingly to matrix
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}
+        path: wheelhouse/opencv*.whl
+
+  test:
+    needs: [build_arm]
+    runs-on: opencv-cn-lin-arm64
+    defaults:
+      run:
+        shell: bash
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ['3.6', '3.7', '3.8', '3.9', '3.10']
+        platform: [x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+    env:
+      ACTIONS_ALLOW_UNSECURE_COMMANDS: true
+      MB_PYTHON_VERSION: ${{ matrix.python-version }}
+      PLAT: aarch64
+      NP_TEST_DEP: numpy==1.19.4
+      NP_TEST_DEP_LATEST: numpy==1.21.4
+      CONFIG_PATH: travis_config.sh
+      DOCKER_TEST_IMAGE: multibuild/focal_arm64v8
+      UNICODE_WIDTH: 32
+    steps:
+    - name: Cleanup
+      run: find . -mindepth 1 -delete
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: true
+        fetch-depth: 0
+    - name: Setup Environment variables
+      run: if [ "3.10" == "${{ matrix.python-version }}" ]; then echo "TEST_DEPENDS=$(echo $NP_TEST_DEP_LATEST)" >> $GITHUB_ENV; else echo "TEST_DEPENDS=$(echo $NP_TEST_DEP)" >> $GITHUB_ENV; fi
+    - name: Download a wheel accordingly to matrix
+      uses: actions/download-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}
+        path: wheelhouse/
+    - name: Package installation and run tests
+      run: source scripts/install.sh
+
+  test_release_opencv_python:
+    if: github.event_name == 'release' && github.event.release.prerelease
+    needs: [build_arm, test]
+    runs-on: ubuntu-20.04
+    environment: test-opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+      - name: Upload all wheels
+        run: |
+          python -m pip install twine
+          python -m twine upload --repository testpypi -u ${{ secrets.PYPI_USERNAME }} -p ${{ secrets.PYPI_PASSWORD }} --skip-existing wheelhouse/opencv_*
+
+  release_opencv_python:
+    if: github.event_name == 'release' && !github.event.release.prerelease
+    needs: [build_arm, test]
+    runs-on: ubuntu-20.04
+    environment: opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+      - name: Upload wheels for opencv_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_python-*
+      - name: Upload wheels for opencv_contrib_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python-*
+      - name: Upload wheels for opencv_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_python_headless-*
+      - name: Upload wheels for opencv_contrib_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python_headless-*
diff --git a/.github/workflows/build_wheels_macos.yml b/.github/workflows/build_wheels_macos.yml
new file mode 100644
index 00000000..af892101
--- /dev/null
+++ b/.github/workflows/build_wheels_macos.yml
@@ -0,0 +1,218 @@
+name: Build PYPI wheels for opencv-python on Macos
+
+on:
+  pull_request:
+    branches:
+      - master
+      - 3.4
+    paths-ignore:
+      - '.github/workflows/build_wheels_linux*'
+      - '.github/workflows/build_wheels_windows*'
+      - '.github/workflows/build_wheels_macos_m1.yml'
+  release:
+    types: [published, edited]
+
+
+jobs:
+  build:
+    runs-on: ${{ matrix.os }}
+    defaults:
+      run:
+        shell: bash
+    strategy:
+      fail-fast: false
+      matrix:
+        os: [macos-10.15, macos-11]
+        python-version: ['3.6']
+        platform: [x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+        exclude:
+          - os: macos-10.15
+            python-version: '3.10'
+          - os: macos-11
+            python-version: '3.6'
+          - os: macos-11
+            python-version: '3.7'
+          - os: macos-11
+            python-version: '3.8'
+          - os: macos-11
+            python-version: '3.9'
+    env:
+      ACTIONS_ALLOW_UNSECURE_COMMANDS: true
+      REPO_DIR: .
+      BUILD_COMMIT: master
+      PROJECT_SPEC: opencv-python
+      MB_PYTHON_VERSION: ${{ matrix.python-version }}
+      TRAVIS_PYTHON_VERSION: ${{ matrix.python-version }}
+      MB_ML_VER: 2014
+      TRAVIS_BUILD_DIR: ${{ github.workspace }}
+      TRAVIS_OS_NAME: osx
+      CONFIG_PATH: travis_config.sh
+      DOCKER_IMAGE: quay.io/asenyaev/manylinux2014_${PLAT}
+      USE_CCACHE: 1
+      UNICODE_WIDTH: 32
+      PLAT: x86_64
+      FFMPEG_FORMULA_VERSION: '@4'
+      SDIST: ${{ matrix.build_sdist || 0 }}
+      ENABLE_HEADLESS: ${{ matrix.without_gui }}
+      ENABLE_CONTRIB: ${{ matrix.with_contrib }}
+    steps:
+    - name: Cleanup
+      run: find . -mindepth 1 -delete
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: false
+        fetch-depth: 0
+    - name: Update submodules
+      if: github.event_name == 'pull_request'
+      run: git submodule update --remote
+    - name: Build a package
+      run: |
+        set -e
+        # Check out and prepare the source
+        # Multibuild doesn't have releases, so --depth would break eventually (see
+        # https://superuser.com/questions/1240216/server-does-not-allow-request-for-unadvertised)
+        git submodule update --init multibuild
+        source multibuild/common_utils.sh
+        # https://github.com/matthew-brett/multibuild/issues/116
+        if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then export ARCH_FLAGS=" "; fi
+        source multibuild/travis_steps.sh
+        # This sets -x
+        # source travis_multibuild_customize.sh
+        echo $ENABLE_CONTRIB > contrib.enabled
+        echo $ENABLE_HEADLESS > headless.enabled
+        set -x
+        build_wheel $REPO_DIR $PLAT
+    - name: Saving all wheels
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheels
+        path: wheelhouse/opencv*.whl
+    - name: Saving a wheel accordingly to matrix
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}
+        path: wheelhouse/opencv*.whl
+
+  test:
+    needs: [build]
+    runs-on: ${{ matrix.os }}
+    defaults:
+      run:
+        shell: bash
+    strategy:
+      fail-fast: false
+      matrix:
+        os: [macos-10.15, macos-11]
+        python-version: ['3.6', '3.7', '3.8', '3.9', '3.10']
+        platform: [x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+        exclude:
+          - os: macos-10.15
+            python-version: '3.10'
+          - os: macos-11
+            python-version: '3.6'
+          - os: macos-11
+            python-version: '3.7'
+          - os: macos-11
+            python-version: '3.8'
+          - os: macos-11
+            python-version: '3.9'
+    env:
+      ACTIONS_ALLOW_UNSECURE_COMMANDS: true
+      MB_PYTHON_VERSION: ${{ matrix.python-version }}
+      NP_TEST_DEP: numpy==1.19.4
+      NP_TEST_DEP_LATEST: numpy==1.21.4
+      CONFIG_PATH: travis_config.sh
+      PLAT: x86_64
+      OPENCV_TEST_DATA_PATH: ${{ github.workspace }}/opencv_extra/testdata
+      PYLINT_TEST_FILE: ${{ github.workspace }}/opencv/samples/python/squares.py
+    steps:
+    - name: Cleanup
+      run: find . -mindepth 1 -delete
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: true
+        fetch-depth: 0
+    - name: Set up Python ${{ matrix.python-version }}
+      uses: actions/setup-python@v2
+      with:
+        python-version: ${{ matrix.python-version }}
+        architecture: ${{ matrix.platform }}
+    - name: Setup Environment variables
+      run: if [ "3.10" == "${{ matrix.python-version }}" ]; then echo "TEST_DEPENDS=$(echo $NP_TEST_DEP_LATEST)" >> $GITHUB_ENV; else echo "TEST_DEPENDS=$(echo $NP_TEST_DEP)" >> $GITHUB_ENV; fi
+    - name: Download a wheel accordingly to matrix
+      uses: actions/download-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}
+        path: wheelhouse/
+    - name: Package installation
+      run: |
+        python -m pip install wheelhouse/opencv*.whl
+        cd ${{ github.workspace }}/tests
+        python get_build_info.py
+    - name: Run tests
+      run: |
+        cd ${{ github.workspace }}/opencv
+        python modules/python/test/test.py -v --repo .
+    - name: Pylint test
+      run: |
+        python -m pip install pylint==2.12.2
+        cd ${{ github.workspace }}/tests
+        python -m pylint $PYLINT_TEST_FILE
+
+  test_release_opencv_python:
+    if: github.event_name == 'release' && github.event.release.prerelease
+    needs: [build, test]
+    runs-on: ubuntu-20.04
+    environment: test-opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+      - name: Upload all wheels
+        run: |
+          python -m pip install twine
+          python -m twine upload --repository testpypi -u ${{ secrets.PYPI_USERNAME }} -p ${{ secrets.PYPI_PASSWORD }} --skip-existing wheelhouse/opencv_*
+
+  release_opencv_python:
+    if: github.event_name == 'release' && !github.event.release.prerelease
+    needs: [build, test]
+    runs-on: ubuntu-20.04
+    environment: opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+      - name: Upload wheels for opencv_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_python-*
+      - name: Upload wheels for opencv_contrib_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python-*
+      - name: Upload wheels for opencv_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_python_headless-*
+      - name: Upload wheels for opencv_contrib_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python_headless-*
diff --git a/.github/workflows/build_wheels_macos_m1.yml b/.github/workflows/build_wheels_macos_m1.yml
new file mode 100644
index 00000000..a1d7c924
--- /dev/null
+++ b/.github/workflows/build_wheels_macos_m1.yml
@@ -0,0 +1,154 @@
+name: Build PYPI wheels for opencv-python on Macos M1
+
+on:
+  pull_request:
+    branches:
+      - master
+      - 3.4
+    paths-ignore:
+      - '.github/workflows/build_wheels_linux*'
+      - '.github/workflows/build_wheels_windows*'
+      - '.github/workflows/build_wheels_macos.yml'
+  release:
+    types: [published, edited]
+
+
+jobs:
+  build:
+    runs-on: opencv-cn-mac-arm64
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ['3.7']
+        platform: [x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+    env:
+      CI_BUILD: 1
+      SDIST: ${{ matrix.build_sdist || 0 }}
+      ENABLE_HEADLESS: ${{ matrix.without_gui }}
+      ENABLE_CONTRIB: ${{ matrix.with_contrib }}
+    steps:
+    - name: Cleanup
+      run: find . -mindepth 1 -delete
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: false
+        fetch-depth: 0
+    - name: Update submodules
+      if: github.event_name == 'pull_request'
+      run: git submodule update --remote
+    - name: Build a package
+      run: |
+        git submodule update --init multibuild
+        echo $ENABLE_CONTRIB > contrib.enabled
+        echo $ENABLE_HEADLESS > headless.enabled
+        export MACOSX_DEPLOYMENT_TARGET=11.0
+        arch -arm64 python${{ matrix.python-version }} -m pip install toml && python${{ matrix.python-version }} -c 'import toml; c = toml.load("pyproject.toml"); print("\n".join(c["build-system"]["requires"]))' | python${{ matrix.python-version }} -m pip install -r /dev/stdin
+        arch -arm64 python${{ matrix.python-version }} setup.py bdist_wheel --py-limited-api=cp37 --dist-dir=wheelhouse -v
+        delocate-wheel ${{ github.workspace }}/wheelhouse/opencv*
+    - name: Saving all wheels
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheels
+        path: wheelhouse/opencv*.whl
+    - name: Saving a wheel accordingly to matrix
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}
+        path: wheelhouse/opencv*.whl
+
+  test:
+    needs: [build]
+    runs-on: opencv-cn-mac-arm64-tests
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ['3.7', '3.8', '3.9', '3.10']
+        platform: [x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+    env:
+      OPENCV_TEST_DATA_PATH: ${{ github.workspace }}/opencv_extra/testdata
+      PYLINT_TEST_FILE: ${{ github.workspace }}/opencv/samples/python/squares.py
+    steps:
+    - name: Cleanup
+      run: find . -mindepth 1 -delete
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: true
+        fetch-depth: 0
+    - name: Download a wheel accordingly to matrix
+      uses: actions/download-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}
+        path: wheelhouse/
+    - name: Package installation
+      run: |
+        arch -arm64 python${{ matrix.python-version }} -m pip install --user --no-cache --force-reinstall wheelhouse/opencv*.whl
+        cd ${{ github.workspace }}/tests
+        arch -arm64 python${{ matrix.python-version }} get_build_info.py
+    - name: Run tests
+      run: |
+        cd ${{ github.workspace }}/opencv
+        arch -arm64 python${{ matrix.python-version }} modules/python/test/test.py -v --repo .
+    - name: Pylint test
+      run: |
+        arch -arm64 python${{ matrix.python-version }} -m pip install pylint==2.12.2
+        cd ${{ github.workspace }}/tests
+        arch -arm64 python${{ matrix.python-version }} -m pylint $PYLINT_TEST_FILE
+
+  test_release_opencv_python:
+    if: github.event_name == 'release' && github.event.release.prerelease
+    needs: [build, test]
+    runs-on: ubuntu-20.04
+    environment: test-opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+
+      - name: Upload all wheels
+        run: |
+          python -m pip install twine
+          python -m twine upload --repository testpypi -u ${{ secrets.PYPI_USERNAME }} -p ${{ secrets.PYPI_PASSWORD }} --skip-existing wheelhouse/opencv_*
+
+  release_opencv_python:
+    if: github.event_name == 'release' && !github.event.release.prerelease
+    needs: [build, test]
+    runs-on: ubuntu-20.04
+    environment: opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+      - name: Upload wheels for opencv_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_python-*
+      - name: Upload wheels for opencv_contrib_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python-*
+      - name: Upload wheels for opencv_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_python_headless-*
+      - name: Upload wheels for opencv_contrib_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python_headless-*
diff --git a/.github/workflows/build_wheels_windows.yml b/.github/workflows/build_wheels_windows.yml
new file mode 100644
index 00000000..087efc04
--- /dev/null
+++ b/.github/workflows/build_wheels_windows.yml
@@ -0,0 +1,176 @@
+name: Build PYPI wheels for opencv-python on Windows
+
+on:
+  pull_request:
+    branches:
+      - master
+      - 3.4
+    paths-ignore:
+      - '.github/workflows/build_wheels_linux*'
+      - '.github/workflows/build_wheels_macos*'
+  release:
+    types: [published, edited]
+
+
+jobs:
+  build-windows-x86_64:
+    runs-on: windows-2019
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ['3.6']
+        platform: [x86, x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+    env:
+      ACTIONS_ALLOW_UNSECURE_COMMANDS: true
+      SDIST: ${{ matrix.build_sdist || 0 }}
+      ENABLE_HEADLESS: ${{ matrix.without_gui }}
+      ENABLE_CONTRIB: ${{ matrix.with_contrib }}
+      OPENCV_TEST_DATA_PATH: ${{ github.workspace }}\opencv_extra\testdata
+    steps:
+    - name: Cleanup
+      shell: bash
+      run: |
+        rm -rf ./* || true
+        rm -rf ./.??* || true
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: false
+        fetch-depth: 0
+    - name: Update submodules
+      if: github.event_name == 'pull_request'
+      run: git submodule update --remote
+    - name: Set up Python ${{ matrix.python-version }}
+      uses: actions/setup-python@v2
+      with:
+        python-version: ${{ matrix.python-version }}
+        architecture: ${{ matrix.platform }}
+    - name: Setup MSBuild.exe
+      uses: microsoft/setup-msbuild@v1.1
+    - name: Build a package
+      run: |
+        python --version
+        python -m pip install --upgrade pip
+        python -m pip install --upgrade setuptools
+        python -m pip install toml && python -c "import toml; c = toml.load('pyproject.toml'); print('\n'.join(c['build-system']['requires']))" >> requirements.txt | python -m pip install -r requirements.txt
+        set "CI_BUILD=1" && python setup.py bdist_wheel --py-limited-api=cp36 --dist-dir=%cd%\wheelhouse -v
+      shell: cmd
+    - name: Saving all wheels
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheels
+        path: wheelhouse/opencv*.whl
+    - name: Saving a wheel accordingly to matrix
+      uses: actions/upload-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}-${{ matrix.platform }}
+        path: wheelhouse/opencv*
+
+  test:
+    needs: [build-windows-x86_64]
+    runs-on: windows-2019
+    defaults:
+      run:
+        shell: cmd
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ['3.6', '3.7', '3.8', '3.9', '3.10']
+        platform: [x86, x64]
+        with_contrib: [0, 1]
+        without_gui: [0, 1]
+        build_sdist: [0]
+    env:
+      ACTIONS_ALLOW_UNSECURE_COMMANDS: true
+      OPENCV_TEST_DATA_PATH: ${{ github.workspace }}\opencv_extra\testdata
+      PYLINT_TEST_FILE: ${{ github.workspace }}\opencv\samples\python\squares.py
+    steps:
+    - name: Cleanup
+      shell: bash
+      run: |
+        rm -rf ./* || true
+        rm -rf ./.??* || true
+      working-directory: ${{ github.workspace }}
+    - name: Checkout
+      uses: actions/checkout@v2
+      with:
+        submodules: true
+        fetch-depth: 0
+    - name: Set up Python ${{ matrix.python-version }}
+      uses: actions/setup-python@v2
+      with:
+        python-version: ${{ matrix.python-version }}
+        architecture: ${{ matrix.platform }}
+    - name: Download a wheel accordingly to matrix
+      uses: actions/download-artifact@v2
+      with:
+        name: wheel-${{ matrix.with_contrib }}-${{ matrix.without_gui }}-${{ matrix.build_sdist }}-${{ matrix.platform }}
+        path: wheelhouse/
+    - name: Package installation
+      run: |
+        cd ${{ github.workspace }}/tests
+        &python -m pip install --user --no-warn-script-location (ls "../wheelhouse/opencv*.whl")
+        if ($LastExitCode -ne 0) {throw $LastExitCode}
+        python get_build_info.py
+      shell: powershell
+    - name: Run tests
+      run: |
+        cd ${{ github.workspace }}/opencv
+        python modules\python\test\test.py -v --repo .
+    - name: Pylint test
+      run: |
+        python -m pip install pylint==2.12.2
+        cd ${{ github.workspace }}\tests
+        python -m pylint $PYLINT_TEST_FILE
+
+  test_release_opencv_python:
+    if: github.event_name == 'release' && github.event.release.prerelease
+    needs: [build-windows-x86_64, test]
+    runs-on: ubuntu-20.04
+    environment: test-opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+      - name: Upload all wheels
+        run: |
+          python -m pip install twine
+          python -m twine upload --repository testpypi -u ${{ secrets.PYPI_USERNAME }} -p ${{ secrets.PYPI_PASSWORD }} --skip-existing wheelhouse/opencv_*
+
+  release_opencv_python:
+    if: github.event_name == 'release' && !github.event.release.prerelease
+    needs: [build-windows-x86_64, test]
+    runs-on: ubuntu-20.04
+    environment: opencv-python-release
+    defaults:
+      run:
+        shell: bash
+    steps:
+      - uses: actions/download-artifact@v2
+        with:
+          name: wheels
+          path: wheelhouse/
+      - name: Upload wheels for opencv_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_python-*
+      - name: Upload wheels for opencv_contrib_python
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python-*
+      - name: Upload wheels for opencv_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_python_headless-*
+      - name: Upload wheels for opencv_contrib_python_headless
+        run: |
+          python -m pip install twine
+          python -m twine upload -u ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_USERNAME }} -p ${{ secrets.OPENCV_CONTRIB_PYTHON_HEADLESS_PASSWORD }} --skip-existing wheelhouse/opencv_contrib_python_headless-*
diff --git a/.gitignore b/.gitignore
index 87caa5f8..15079e07 100644
--- a/.gitignore
+++ b/.gitignore
@@ -67,3 +67,5 @@ target/
 # Build temporary files
 /contrib.enabled
 /cv_version.py
+/cv2/version.py
+_skbuild/
diff --git a/.gitmodules b/.gitmodules
index ce3da2e1..7193d3b9 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,10 +1,12 @@
 [submodule "opencv"]
 	path = opencv
-	url = https://github.com/Itseez/opencv.git
-[submodule "multibuild"]
-	path = multibuild
-	url = https://github.com/matthew-brett/multibuild.git
-    branch = devel
+	url = https://github.com/opencv/opencv.git
 [submodule "opencv_contrib"]
 	path = opencv_contrib
 	url = https://github.com/opencv/opencv_contrib.git
+[submodule "multibuild"]
+	path = multibuild
+	url = https://github.com/multi-build/multibuild.git
+[submodule "opencv_extra"]
+	path = opencv_extra
+	url = https://github.com/opencv/opencv_extra.git
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index ea3293e7..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,238 +0,0 @@
-env:
-    global:
-        - "PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'"
-        # pip dependencies to _test_ your project
-        - TEST_DEPENDS="numpy==1.11.1"
-
-        - PLAT=x86_64
-        - UNICODE_WIDTH=32
-        - secure: "mU040XIYWtDjRms27deQy5fNg9HBFF9fiLfSteBaMjopZKXFUBsdMTKYGEVvX8DA879guMdjG8Prw1aCFhTTYlWgJ0Afm4YucRC0vAD4HLNhqLJ2lIpRceR3+2qPX+Oz5ATVVRi3ghBeJ20LLtNgOgf6esQVjdrYNC+YqmguClHKEYAxS7ngW42iQP8HX2anRcz9q9H7exZ9fX/D1PJfMNka/mNaB5KXZu5zdLuk/E0VbWU2tMWVIDUvx4uBlpE1d8HixEV5LHnuVE/QI36BcyucYxstTNKW6pGYgrhkYf+0PX4BphZXwY7EUBwzXsYLmyge6yH8W6NfvTW0ZasFF6xzQc9bsj+gAZN7H+hN2a42VQqIpkoJw9sU0hqzCOQf6ZvWUQgwFdAHJRHqe/zk4456WxnF0kAgbZdKaGOl0/n0WvgHNqD5bgO8Zzb1XyJTKoR+eAtYKXuz3KgpxKvZMMQVr8wMlI1cFEuGjIm+7ZrYB5jPvQrVzV/DgOq4gkPHOjjhu478UFlhGA9/XWwcyidC3b7zuBN2E7xVuTMlKdk7URB3AHXfG5bZgUG80vllQDGXQDpHVnv4Qi8bGCzI4iKTpp4fCibbqxFLxW1jhjmgePseGcie7Avpe+zXznkbmM2BqMCu3QRmtmFL3eCifwMf3rCNlAs0Sd3iLmEvyos="
-        - secure: "omn6B+H6s0g1p9rhLGhFtFN1bSB80HCsNUUD9ROEpUirk7Sj7Wxms4CDi1f7aACANsZPXD7YZ72oNpWDJ6hSfTBf2yN1/d1iPILs7F5jt0yeratkDEOXkys1QpfMNO7r3DZ17X3IwvUGy9Mm+Sv15k+DaBdQ/65qwQ4ORIbHZRv3/lwkQ7Z88utjx6DLa9Jwc8fnEjjzIry51lO3OGJoWrjOZlOi2HV9MZ69PuuBdEEuicwfeLnV64QWRle++B51TQZC/3HF5+BBvYXm0LdvV4nSQVa9nTXaOWYcBROPNZizktJI91G6vG6gghWmI1cDR53n9LgCbA3YkPTJm/5Gjn9D+gfU5F16WQ4PFOHfzPZD8nTVmlUDUiuQ30W9QZ+O2ct7wi/xF4/Ff7V+0RIqGSnjhX6SGWk7UziQyGgCjBvYiRIQzfUyGu+86vrqNVXCyBlKOz6rWStTyq/Z0KEIXZFqop+ddeYdsEem5ZxCQ51uTpRMynVgEdKj++1Hn5411Rhntw0Am7RWdDEbFJ65OUyIpNtvlcHVM7ur03oz0hGcZIIkxWHJrCdr80Nw9r/s6KXYvidCNsu4SPx0XYo8KiTA6E2lkIAa5Ct6dZR6m5gjG2vmvlKzRmoD/7byJZN66usNxBh2LuKlgNFuHfG6iR+I6f3XCNmSUOJfm7KZYVI="
-
-
-# Host Python is never used
-language: generic
-# Required to invoke docker ourselves as per https://docs.travis-ci.com/user/docker/
-sudo: required
-services: docker
-# https://docs.travis-ci.com/user/reference/trusty/
-dist: trusty
-
-# Save some time, we and setup check them out on demand instead
-# https://docs.travis-ci.com/user/customizing-the-build/#Git-Clone-Depth
-git:
-    submodules: false
-
-
-matrix:
-  fast_finish: true
-  include:
-
-    # default builds for MacOS
-    - os: osx
-      osx_image: xcode7.3
-      env:
-        - MB_PYTHON_VERSION=2.7
-        - ENABLE_CONTRIB=0
-    - os: osx
-      osx_image: xcode7.3
-      env:
-        - MB_PYTHON_VERSION=3.4
-        - ENABLE_CONTRIB=0
-    - os: osx
-      osx_image: xcode7.3
-      env:
-        - MB_PYTHON_VERSION=3.5
-        - ENABLE_CONTRIB=0
-    - os: osx
-      osx_image: xcode7.3
-      env:
-        - MB_PYTHON_VERSION=3.6
-        - ENABLE_CONTRIB=0
-
-    # Contrib builds for MacOS
-    - os: osx
-      osx_image: xcode7.3
-      env:
-        - MB_PYTHON_VERSION=2.7
-        - ENABLE_CONTRIB=1
-    - os: osx
-      osx_image: xcode7.3
-      env:
-        - MB_PYTHON_VERSION=3.4
-        - ENABLE_CONTRIB=1
-    - os: osx
-      osx_image: xcode7.3
-      env:
-        - MB_PYTHON_VERSION=3.5
-        - ENABLE_CONTRIB=1
-    - os: osx
-      osx_image: xcode7.3
-      env:
-        - MB_PYTHON_VERSION=3.6
-        - ENABLE_CONTRIB=1
-
-    # default builds for Linux
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=2.7
-        - ENABLE_CONTRIB=0
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=2.7
-        - UNICODE_WIDTH=16
-        - ENABLE_CONTRIB=0
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=2.7
-        - PLAT=i686
-        - ENABLE_CONTRIB=0
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=2.7
-        - PLAT=i686
-        - UNICODE_WIDTH=16
-        - ENABLE_CONTRIB=0
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.4
-        - ENABLE_CONTRIB=0
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.4
-        - PLAT=i686
-        - ENABLE_CONTRIB=0
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.5
-        - ENABLE_CONTRIB=0
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.5
-        - PLAT=i686
-        - ENABLE_CONTRIB=0
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.6
-        - ENABLE_CONTRIB=0
-
-        - TEST_DEPENDS=numpy==1.11.3
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.6
-        - PLAT=i686
-        - ENABLE_CONTRIB=0
-
-        - TEST_DEPENDS=numpy==1.11.3
-
-    # contrib builds for Linux
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=2.7
-
-        - ENABLE_CONTRIB=1
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=2.7
-
-        - UNICODE_WIDTH=16
-        - ENABLE_CONTRIB=1
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=2.7
-
-        - PLAT=i686
-        - ENABLE_CONTRIB=1
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=2.7
-
-        - PLAT=i686
-        - UNICODE_WIDTH=16
-        - ENABLE_CONTRIB=1
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.4
-
-        - ENABLE_CONTRIB=1
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.4
-
-        - PLAT=i686
-        - ENABLE_CONTRIB=1
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.5
-
-        - ENABLE_CONTRIB=1
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.5
-
-        - PLAT=i686
-        - ENABLE_CONTRIB=1
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.6
-
-
-        - TEST_DEPENDS=numpy==1.11.3
-        - ENABLE_CONTRIB=1
-
-    - os: linux
-      env:
-        - MB_PYTHON_VERSION=3.6
-
-        - PLAT=i686
-
-        - TEST_DEPENDS=numpy==1.11.3
-        - ENABLE_CONTRIB=1
-
-# The first line is printed in the folding header in Travis output
-before_install: |
-    # Check out and prepare the source
-    set -e
-    #Multibuild doesn't have releases, so --depth would break eventually (see
-    #https://superuser.com/questions/1240216/server-does-not-allow-request-for-unadvertised)
-    git submodule update --init multibuild
-    source multibuild/common_utils.sh
-    # https://github.com/matthew-brett/multibuild/issues/116
-    if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then export ARCH_FLAGS=" "; fi
-    source multibuild/travis_steps.sh
-    # This sets -x
-    source multibuild_customize.sh
-    echo $ENABLE_CONTRIB > contrib.enabled
-    before_install
-    # Not interested in travis internal scripts' output
-    set +x
-
-install: |
-    # Build and package
-    set -x
-    build_wheel $REPO_DIR $PLAT
-    set +x
-
-script: |
-    # Install and run tests
-    set -x
-    install_run $PLAT
-    set +x
-
-after_success: |
-    # Upload wheels to pypi if requested
-    if [ -n "$TRAVIS_TAG" ]; then
-        set -x
-        pip install twine
-
-        if [[ $ENABLE_CONTRIB == 0 ]]; then
-            echo "This is default build. Deployment will be done to to PyPI entry opencv-python."
-        else
-            echo "This is contrib build. Deployment will be done to to PyPI entry opencv-contrib-python."
-        fi
-
-        twine upload -u ${USER} -p ${PASS} --skip-existing ${TRAVIS_BUILD_DIR}/wheelhouse/opencv*
-        set +x
-    else
-        echo "Tag not set, deployment skipped."
-    fi
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6a843f0e..07ac1259 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -6,9 +6,12 @@ Thank you for considering contributing to opencv-python.
 
 If you've noticed a bug or have a question that doesn't belong on
 [Stack Overflow](http://stackoverflow.com/questions/tagged/opencv-python),
-[search the issue tracker](https://github.com/skvark/opencv-python/issues?q=something)
+[search the project issue tracker](https://github.com/opencv/opencv-python/issues?q=something) or
+[search OpenCV issue tracker](https://github.com/opencv/opencv/issues?q=is%3Aissue+is%3Aopen+label%3A%22category%3A+python+bindings%22)
 to see if someone else in the community has already created a ticket.
-If not, go ahead and [make one](https://github.com/skvark/opencv-python/issues/new)!
+If not, go ahead and:
+- [make new one for opencv-python](https://github.com/opencv/opencv-python/issues/new) if you cannot load package or some functionality is not available!
+- [make new one for OpenCV](https://github.com/opencv/opencv-python/issues/new) if something went wrong with some function, class  or method in code!
 
 ### 2. Fork & create a branch
 
diff --git a/LICENSE-3RD-PARTY.txt b/LICENSE-3RD-PARTY.txt
index 8cbc4f5c..caeffe51 100644
--- a/LICENSE-3RD-PARTY.txt
+++ b/LICENSE-3RD-PARTY.txt
@@ -1,52 +1,251 @@
 OpenCV library is redistributed within opencv-python package.
 This license applies to OpenCV binary in the directory cv2/.
 
-By downloading, copying, installing or using the software you agree to this license.
-If you do not agree to this license, do not download, install,
-copy or use the software.
 
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
 
-                          License Agreement
-               For Open Source Computer Vision Library
-                       (3-clause BSD License)
-
-Copyright (C) 2000-2016, Intel Corporation, all rights reserved.
-Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
-Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved.
-Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved.
-Copyright (C) 2015-2016, OpenCV Foundation, all rights reserved.
-Copyright (C) 2015-2016, Itseez Inc., all rights reserved.
-Third party copyrights are property of their respective owners.
-
-Redistribution and use in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
-
-  * Redistributions of source code must retain the above copyright notice,
-    this list of conditions and the following disclaimer.
-
-  * Redistributions in binary form must reproduce the above copyright notice,
-    this list of conditions and the following disclaimer in the documentation
-    and/or other materials provided with the distribution.
+------------------------------------------------------------------------------
+libvpx is redistributed within all opencv-python Linux packages.
+This license applies to libvpx binary in the directory cv2/.
+
+Copyright (c) 2010, The WebM Project authors. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+  * Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+
+  * Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+
+  * Neither the name of Google, nor the WebM Project, nor the names
+    of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written
+    permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-  * Neither the names of the copyright holders nor the names of the contributors
-    may be used to endorse or promote products derived from this software
-    without specific prior written permission.
+------------------------------------------------------------------------------
+FFmpeg is redistributed within all opencv-python packages.
 
-This software is provided by the copyright holders and contributors "as is" and
-any express or implied warranties, including, but not limited to, the implied
-warranties of merchantability and fitness for a particular purpose are disclaimed.
-In no event shall copyright holders or contributors be liable for any direct,
-indirect, incidental, special, exemplary, or consequential damages
-(including, but not limited to, procurement of substitute goods or services;
-loss of use, data, or profits; or business interruption) however caused
-and on any theory of liability, whether in contract, strict liability,
-or tort (including negligence or otherwise) arising in any way out of
-the use of this software, even if advised of the possibility of such damage.
+Libbluray, libgnutls, libnettle, libhogweed, libintl, libmp3lame, libp11,
+librtmp, libsoxr and libtasn1 are redistributed within all opencv-python macOS packages.
 
-------------------------------------------------------------------------------
-FFmpeg is redistributed within opencv-python Windows packages.
-Qt 4.8.7 is redistributed within opencv-python Linux and macOS packages
-This license applies to FFmpeg and Qt binaries in the directory cv2/.
+This license applies to the above library binaries in the directory cv2/.
 
                   GNU LESSER GENERAL PUBLIC LICENSE
                        Version 2.1, February 1999
@@ -506,47 +705,1734 @@ SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
 DAMAGES.
 
                      END OF TERMS AND CONDITIONS
-
-           How to Apply These Terms to Your New Libraries
 
-  If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change.  You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
+------------------------------------------------------------------------------
+Qt 5 is redistributed within non-headless opencv-python Linux and macOS packages.
+libgmp is redistributed within opencv-python macOS packages.
+libidn2 is redistributed within opencv-python macOS packages.
+libunistring is redistributed within opencv-python macOS packages.
+This license applies to the above binaries in the directory cv2/.
+
+                   GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
+
+------------------------------------------------------------------------------
+bzip2 is redistributed within all opencv-python Linux packages.
+This license applies to libbz2 binary in the directory cv2/.
+
+This program, "bzip2", the associated library "libbzip2", and all
+documentation, are copyright (C) 1996-2010 Julian R Seward.  All
+rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+2. The origin of this software must not be misrepresented; you must 
+   not claim that you wrote the original software.  If you use this 
+   software in a product, an acknowledgment in the product 
+   documentation would be appreciated but is not required.
+
+3. Altered source versions must be plainly marked as such, and must
+   not be misrepresented as being the original software.
+
+4. The name of the author may not be used to endorse or promote 
+   products derived from this software without specific prior written 
+   permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Julian Seward, jseward@bzip.org
+bzip2/libbzip2 version 1.0.6 of 6 September 2010
+
+------------------------------------------------------------------------------
+libcrypto and libssl are redistributed within all opencv-python Linux and macOS packages.
+libopencore-amrnb and libopencore-amrwb are redistributed within all opencv-python Linux and macOS packages.
+This license applies to above binaries in the directory cv2/.
+
+  LICENSE ISSUES
+  ==============
+
+  The OpenSSL toolkit stays under a double license, i.e. both the conditions of
+  the OpenSSL License and the original SSLeay license apply to the toolkit.
+  See below for the actual license texts.
+
+  OpenSSL License
+  ---------------
+
+/* ====================================================================
+ * Copyright (c) 1998-2019 The OpenSSL Project.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ *    software must display the following acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ *    endorse or promote products derived from this software without
+ *    prior written permission. For written permission, please contact
+ *    openssl-core@openssl.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ *    nor may "OpenSSL" appear in their names without prior written
+ *    permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ *    acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com).  This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
+
+ Original SSLeay License
+ -----------------------
+
+/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
+ * All rights reserved.
+ *
+ * This package is an SSL implementation written
+ * by Eric Young (eay@cryptsoft.com).
+ * The implementation was written so as to conform with Netscapes SSL.
+ *
+ * This library is free for commercial and non-commercial use as long as
+ * the following conditions are adhered to.  The following conditions
+ * apply to all code found in this distribution, be it the RC4, RSA,
+ * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
+ * included with this distribution is covered by the same copyright terms
+ * except that the holder is Tim Hudson (tjh@cryptsoft.com).
+ *
+ * Copyright remains Eric Young's, and as such any Copyright notices in
+ * the code are not to be removed.
+ * If this package is used in a product, Eric Young should be given attribution
+ * as the author of the parts of the library used.
+ * This can be in the form of a textual message at program startup or
+ * in documentation (online or textual) provided with the package.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *    "This product includes cryptographic software written by
+ *     Eric Young (eay@cryptsoft.com)"
+ *    The word 'cryptographic' can be left out if the routines from the library
+ *    being used are not cryptographic related :-).
+ * 4. If you include any Windows specific code (or a derivative thereof) from
+ *    the apps directory (application code) you must include an acknowledgement:
+ *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * The licence and distribution terms for any publicly available version or
+ * derivative of this code cannot be changed.  i.e. this code cannot simply be
+ * copied and put under another distribution licence
+ * [including the GNU Public Licence.]
+ */
+
+------------------------------------------------------------------------------
+libfontconfig is redistributed within all opencv-python macOS packages.
+This license applies to libfontconfig binary in the directory cv2/.
+
+Copyright © 2000,2001,2002,2003,2004,2006,2007 Keith Packard
+Copyright © 2005 Patrick Lam
+Copyright © 2009 Roozbeh Pournader
+Copyright © 2008,2009 Red Hat, Inc.
+Copyright © 2008 Danilo Šegan
+Copyright © 2012 Google, Inc.
+
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation, and that the name of the author(s) not be used in
+advertising or publicity pertaining to distribution of the software without
+specific, written prior permission.  The authors make no
+representations about the suitability of this software for any purpose.  It
+is provided "as is" without express or implied warranty.
+
+THE AUTHOR(S) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+
+------------------------------------------------------------------------------
+libfreetype is redistributed within opencv-python Linux and macOS packages.
+This license applies to libfreetype binary in the directory cv2/.
+
+                    The FreeType Project LICENSE
+                    ----------------------------
+
+                            2006-Jan-27
+
+                    Copyright 1996-2002, 2006 by
+          David Turner, Robert Wilhelm, and Werner Lemberg
+
 
-  To apply these terms, attach the following notices to the library.  It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
 
-    <one line to give the library's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
+Introduction
+============
 
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
+  The FreeType  Project is distributed in  several archive packages;
+  some of them may contain, in addition to the FreeType font engine,
+  various tools and  contributions which rely on, or  relate to, the
+  FreeType Project.
 
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
+  This  license applies  to all  files found  in such  packages, and
+  which do not  fall under their own explicit  license.  The license
+  affects  thus  the  FreeType   font  engine,  the  test  programs,
+  documentation and makefiles, at the very least.
 
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+  This  license   was  inspired  by  the  BSD,   Artistic,  and  IJG
+  (Independent JPEG  Group) licenses, which  all encourage inclusion
+  and  use of  free  software in  commercial  and freeware  products
+  alike.  As a consequence, its main points are that:
 
-Also add information on how to contact you by electronic and paper mail.
+    o We don't promise that this software works. However, we will be
+      interested in any kind of bug reports. (`as is' distribution)
 
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary.  Here is a sample; alter the names:
+    o You can  use this software for whatever you  want, in parts or
+      full form, without having to pay us. (`royalty-free' usage)
 
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the
-  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+    o You may not pretend that  you wrote this software.  If you use
+      it, or  only parts of it,  in a program,  you must acknowledge
+      somewhere  in  your  documentation  that  you  have  used  the
+      FreeType code. (`credits')
 
-  <signature of Ty Coon>, 1 April 1990
-  Ty Coon, President of Vice
+  We  specifically  permit  and  encourage  the  inclusion  of  this
+  software, with  or without modifications,  in commercial products.
+  We  disclaim  all warranties  covering  The  FreeType Project  and
+  assume no liability related to The FreeType Project.
+
+
+  Finally,  many  people  asked  us  for  a  preferred  form  for  a
+  credit/disclaimer to use in compliance with this license.  We thus
+  encourage you to use the following text:
+
+   """
+    Portions of this software are copyright © <year> The FreeType
+    Project (www.freetype.org).  All rights reserved.
+   """
+
+  Please replace <year> with the value from the FreeType version you
+  actually use.
+
+
+Legal Terms
+===========
+
+0. Definitions
+--------------
+
+  Throughout this license,  the terms `package', `FreeType Project',
+  and  `FreeType  archive' refer  to  the  set  of files  originally
+  distributed  by the  authors  (David Turner,  Robert Wilhelm,  and
+  Werner Lemberg) as the `FreeType Project', be they named as alpha,
+  beta or final release.
+
+  `You' refers to  the licensee, or person using  the project, where
+  `using' is a generic term including compiling the project's source
+  code as  well as linking it  to form a  `program' or `executable'.
+  This  program is  referred to  as  `a program  using the  FreeType
+  engine'.
+
+  This  license applies  to all  files distributed  in  the original
+  FreeType  Project,   including  all  source   code,  binaries  and
+  documentation,  unless  otherwise  stated   in  the  file  in  its
+  original, unmodified form as  distributed in the original archive.
+  If you are  unsure whether or not a particular  file is covered by
+  this license, you must contact us to verify this.
+
+  The FreeType  Project is copyright (C) 1996-2000  by David Turner,
+  Robert Wilhelm, and Werner Lemberg.  All rights reserved except as
+  specified below.
+
+1. No Warranty
+--------------
+
+  THE FREETYPE PROJECT  IS PROVIDED `AS IS' WITHOUT  WARRANTY OF ANY
+  KIND, EITHER  EXPRESS OR IMPLIED,  INCLUDING, BUT NOT  LIMITED TO,
+  WARRANTIES  OF  MERCHANTABILITY   AND  FITNESS  FOR  A  PARTICULAR
+  PURPOSE.  IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS
+  BE LIABLE  FOR ANY DAMAGES CAUSED  BY THE USE OR  THE INABILITY TO
+  USE, OF THE FREETYPE PROJECT.
+
+2. Redistribution
+-----------------
+
+  This  license  grants  a  worldwide, royalty-free,  perpetual  and
+  irrevocable right  and license to use,  execute, perform, compile,
+  display,  copy,   create  derivative  works   of,  distribute  and
+  sublicense the  FreeType Project (in  both source and  object code
+  forms)  and  derivative works  thereof  for  any  purpose; and  to
+  authorize others  to exercise  some or all  of the  rights granted
+  herein, subject to the following conditions:
+
+    o Redistribution of  source code  must retain this  license file
+      (`FTL.TXT') unaltered; any  additions, deletions or changes to
+      the original  files must be clearly  indicated in accompanying
+      documentation.   The  copyright   notices  of  the  unaltered,
+      original  files must  be  preserved in  all  copies of  source
+      files.
+
+    o Redistribution in binary form must provide a  disclaimer  that
+      states  that  the software is based in part of the work of the
+      FreeType Team,  in  the  distribution  documentation.  We also
+      encourage you to put an URL to the FreeType web page  in  your
+      documentation, though this isn't mandatory.
+
+  These conditions  apply to any  software derived from or  based on
+  the FreeType Project,  not just the unmodified files.   If you use
+  our work, you  must acknowledge us.  However, no  fee need be paid
+  to us.
+
+3. Advertising
+--------------
+
+  Neither the  FreeType authors and  contributors nor you  shall use
+  the name of the  other for commercial, advertising, or promotional
+  purposes without specific prior written permission.
+
+  We suggest,  but do not require, that  you use one or  more of the
+  following phrases to refer  to this software in your documentation
+  or advertising  materials: `FreeType Project',  `FreeType Engine',
+  `FreeType library', or `FreeType Distribution'.
+
+  As  you have  not signed  this license,  you are  not  required to
+  accept  it.   However,  as  the FreeType  Project  is  copyrighted
+  material, only  this license, or  another one contracted  with the
+  authors, grants you  the right to use, distribute,  and modify it.
+  Therefore,  by  using,  distributing,  or modifying  the  FreeType
+  Project, you indicate that you understand and accept all the terms
+  of this license.
+
+4. Contacts
+-----------
+
+  There are two mailing lists related to FreeType:
+
+    o freetype@nongnu.org
+
+      Discusses general use and applications of FreeType, as well as
+      future and  wanted additions to the  library and distribution.
+      If  you are looking  for support,  start in  this list  if you
+      haven't found anything to help you in the documentation.
+
+    o freetype-devel@nongnu.org
+
+      Discusses bugs,  as well  as engine internals,  design issues,
+      specific licenses, porting, etc.
+
+  Our home page can be found at
+
+    https://www.freetype.org
+
+------------------------------------------------------------------------------
+libpng is redistributed within all opencv-python Linux and macOS packages.
+This license applies to libpng binary in the directory cv2/.
+
+PNG Reference Library License version 2
+---------------------------------------
+
+ * Copyright (c) 1995-2019 The PNG Reference Library Authors.
+ * Copyright (c) 2018-2019 Cosmin Truta.
+ * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson.
+ * Copyright (c) 1996-1997 Andreas Dilger.
+ * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
+
+The software is supplied "as is", without warranty of any kind,
+express or implied, including, without limitation, the warranties
+of merchantability, fitness for a particular purpose, title, and
+non-infringement.  In no event shall the Copyright owners, or
+anyone distributing the software, be liable for any damages or
+other liability, whether in contract, tort or otherwise, arising
+from, out of, or in connection with the software, or the use or
+other dealings in the software, even if advised of the possibility
+of such damage.
+
+Permission is hereby granted to use, copy, modify, and distribute
+this software, or portions hereof, for any purpose, without fee,
+subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you
+    must not claim that you wrote the original software.  If you
+    use this software in a product, an acknowledgment in the product
+    documentation would be appreciated, but is not required.
+
+ 2. Altered source versions must be plainly marked as such, and must
+    not be misrepresented as being the original software.
+
+ 3. This Copyright notice may not be removed or altered from any
+    source or altered source distribution.
+
+
+PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35)
+-----------------------------------------------------------------------
+
+libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are
+Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are
+derived from libpng-1.0.6, and are distributed according to the same
+disclaimer and license as libpng-1.0.6 with the following individuals
+added to the list of Contributing Authors:
+
+    Simon-Pierre Cadieux
+    Eric S. Raymond
+    Mans Rullgard
+    Cosmin Truta
+    Gilles Vollant
+    James Yu
+    Mandar Sahastrabuddhe
+    Google Inc.
+    Vadim Barkov
+
+and with the following additions to the disclaimer:
+
+    There is no warranty against interference with your enjoyment of
+    the library or against infringement.  There is no warranty that our
+    efforts or the library will fulfill any of your particular purposes
+    or needs.  This library is provided with all faults, and the entire
+    risk of satisfactory quality, performance, accuracy, and effort is
+    with the user.
+
+Some files in the "contrib" directory and some configure-generated
+files that are distributed with libpng have other copyright owners, and
+are released under other open source licenses.
+
+libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
+Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
+libpng-0.96, and are distributed according to the same disclaimer and
+license as libpng-0.96, with the following individuals added to the
+list of Contributing Authors:
+
+    Tom Lane
+    Glenn Randers-Pehrson
+    Willem van Schaik
+
+libpng versions 0.89, June 1996, through 0.96, May 1997, are
+Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
+and are distributed according to the same disclaimer and license as
+libpng-0.88, with the following individuals added to the list of
+Contributing Authors:
+
+    John Bowler
+    Kevin Bracey
+    Sam Bushell
+    Magnus Holmgren
+    Greg Roelofs
+    Tom Tanner
+
+Some files in the "scripts" directory have other copyright owners,
+but are released under this license.
+
+libpng versions 0.5, May 1995, through 0.88, January 1996, are
+Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
+
+For the purposes of this copyright and license, "Contributing Authors"
+is defined as the following set of individuals:
+
+    Andreas Dilger
+    Dave Martindale
+    Guy Eric Schalnat
+    Paul Schmidt
+    Tim Wegner
+
+The PNG Reference Library is supplied "AS IS".  The Contributing
+Authors and Group 42, Inc. disclaim all warranties, expressed or
+implied, including, without limitation, the warranties of
+merchantability and of fitness for any purpose.  The Contributing
+Authors and Group 42, Inc. assume no liability for direct, indirect,
+incidental, special, exemplary, or consequential damages, which may
+result from the use of the PNG Reference Library, even if advised of
+the possibility of such damage.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+source code, or portions hereof, for any purpose, without fee, subject
+to the following restrictions:
+
+ 1. The origin of this source code must not be misrepresented.
+
+ 2. Altered versions must be plainly marked as such and must not
+    be misrepresented as being the original source.
+
+ 3. This Copyright notice may not be removed or altered from any
+    source or altered source distribution.
+
+The Contributing Authors and Group 42, Inc. specifically permit,
+without fee, and encourage the use of this source code as a component
+to supporting the PNG file format in commercial products.  If you use
+this source code in a product, acknowledgment is not required but would
+be appreciated.
+
+------------------------------------------------------------------------------
+libz is redistributed within all opencv-python Linux packages.
+This license applies to libz binary in the directory cv2/.
+
+  Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+------------------------------------------------------------------------------
+libdav1d is redistributed within opencv-python macOS packages.
+This license applies to libdav1d binary in the directory cv2/.
 
-That's all there is to it!
+Copyright © 2018-2019, VideoLAN and dav1d authors
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+   list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+libffi is redistributed within opencv-python macOS packages.
+This license applies to libffi binary in the directory cv2/.
+
+libffi - Copyright (c) 1996-2020  Anthony Green, Red Hat, Inc and others.
+See source files for details.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+------------------------------------------------------------------------------
+libogg is redistributed within opencv-python macOS packages.
+This license applies to libogg binary in the directory cv2/.
+
+Copyright (c) 2002, Xiph.org Foundation
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+- Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+
+- Neither the name of the Xiph.org Foundation nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+libopenjp2 is redistributed within opencv-python macOS packages.
+This license applies to libopenjp2 binary in the directory cv2/.
+
+The copyright in this software is being made available under the 2-clauses 
+BSD License, included below. This software may be subject to other third 
+party and contributor rights, including patent rights, and no such rights
+are granted under this license.
+
+Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
+Copyright (c) 2002-2014, Professor Benoit Macq
+Copyright (c) 2003-2014, Antonin Descampe
+Copyright (c) 2003-2009, Francois-Olivier Devaux
+Copyright (c) 2005, Herve Drolon, FreeImage Team
+Copyright (c) 2002-2003, Yannick Verschueren
+Copyright (c) 2001-2003, David Janssens
+Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France 
+Copyright (c) 2012, CS Systemes d'Information, France
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+libopus is redistributed within opencv-python macOS packages.
+This license applies to libopus binary in the directory cv2/.
+
+Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic,
+                    Jean-Marc Valin, Timothy B. Terriberry,
+                    CSIRO, Gregory Maxwell, Mark Borgerding,
+                    Erik de Castro Lopo
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+- Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+
+- Neither the name of Internet Society, IETF or IETF Trust, nor the
+names of specific contributors, may be used to endorse or promote
+products derived from this software without specific prior written
+permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Opus is subject to the royalty-free patent licenses which are
+specified at:
+
+Xiph.Org Foundation:
+https://datatracker.ietf.org/ipr/1524/
+
+Microsoft Corporation:
+https://datatracker.ietf.org/ipr/1914/
+
+Broadcom Corporation:
+https://datatracker.ietf.org/ipr/1526/
+
+------------------------------------------------------------------------------
+librav1e is redistributed within opencv-python macOS packages.
+This license applies to librav1e binary in the directory cv2/.
+
+BSD 2-Clause License
+
+Copyright (c) 2017-2020, the rav1e contributors
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+libsnappy is redistributed within opencv-python macOS packages.
+This license applies to libsnappy binary in the directory cv2/.
+
+Copyright 2011, Google Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+    * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+    * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+libspeex is redistributed within opencv-python macOS packages.
+This license applies to libspeex binary in the directory cv2/.
+
+Copyright 2002-2008   Xiph.org Foundation
+Copyright 2002-2008   Jean-Marc Valin
+Copyright 2005-2007 Analog Devices Inc.
+Copyright 2005-2008 Commonwealth Scientific and Industrial Research 
+                        Organisation (CSIRO)
+Copyright 1993, 2002, 2006 David Rowe
+Copyright 2003    EpicGames
+Copyright 1992-1994 Jutta Degener, Carsten Bormann
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+- Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+
+- Neither the name of the Xiph.org Foundation nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+libsrt is redistributed within opencv-python macOS packages.
+This license applies to libsrt binary in the directory cv2/.
+
+/*
+ *  
+ * Copyright (c) 2001-2017 Cisco Systems, Inc.
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 
+ *   Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * 
+ *   Redistributions in binary form must reproduce the above
+ *   copyright notice, this list of conditions and the following
+ *   disclaimer in the documentation and/or other materials provided
+ *   with the distribution.
+ * 
+ *   Neither the name of the Cisco Systems, Inc. nor the names of its
+ *   contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+ Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+    means each individual or legal entity that creates, contributes to
+    the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+    means the combination of the Contributions of others (if any) used
+    by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+    means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+    means Source Code Form to which the initial Contributor has attached
+    the notice in Exhibit A, the Executable Form of such Source Code
+    Form, and Modifications of such Source Code Form, in each case
+    including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+    means
+
+    (a) that the initial Contributor has attached the notice described
+        in Exhibit B to the Covered Software; or
+
+    (b) that the Covered Software was made available under the terms of
+        version 1.1 or earlier of the License, but not also under the
+        terms of a Secondary License.
+
+1.6. "Executable Form"
+    means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+    means a work that combines Covered Software with other material, in 
+    a separate file or files, that is not Covered Software.
+
+1.8. "License"
+    means this document.
+
+1.9. "Licensable"
+    means having the right to grant, to the maximum extent possible,
+    whether at the time of the initial grant or subsequently, any and
+    all of the rights conveyed by this License.
+
+1.10. "Modifications"
+    means any of the following:
+
+    (a) any file in Source Code Form that results from an addition to,
+        deletion from, or modification of the contents of Covered
+        Software; or
+
+    (b) any new file in Source Code Form that contains any Covered
+        Software.
+
+1.11. "Patent Claims" of a Contributor
+    means any patent claim(s), including without limitation, method,
+    process, and apparatus claims, in any patent Licensable by such
+    Contributor that would be infringed, but for the grant of the
+    License, by the making, using, selling, offering for sale, having
+    made, import, or transfer of either its Contributions or its
+    Contributor Version.
+
+1.12. "Secondary License"
+    means either the GNU General Public License, Version 2.0, the GNU
+    Lesser General Public License, Version 2.1, the GNU Affero General
+    Public License, Version 3.0, or any later versions of those
+    licenses.
+
+1.13. "Source Code Form"
+    means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+    means an individual or a legal entity exercising rights under this
+    License. For legal entities, "You" includes any entity that
+    controls, is controlled by, or is under common control with You. For
+    purposes of this definition, "control" means (a) the power, direct
+    or indirect, to cause the direction or management of such entity,
+    whether by contract or otherwise, or (b) ownership of more than
+    fifty percent (50%) of the outstanding shares or beneficial
+    ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+    Licensable by such Contributor to use, reproduce, make available,
+    modify, display, perform, distribute, and otherwise exploit its
+    Contributions, either on an unmodified basis, with Modifications, or
+    as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+    for sale, have made, import, and otherwise transfer either its
+    Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+    or
+
+(b) for infringements caused by: (i) Your and any other third party's
+    modifications of Covered Software, or (ii) the combination of its
+    Contributions with other software (except as part of its Contributor
+    Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+    its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+    Form, as described in Section 3.1, and You must inform recipients of
+    the Executable Form how they can obtain a copy of such Source Code
+    Form by reasonable means in a timely manner, at a charge no more
+    than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+    License, or sublicense it under different terms, provided that the
+    license for the Executable Form does not attempt to limit or alter
+    the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+*                                                                      *
+*  6. Disclaimer of Warranty                                           *
+*  -------------------------                                           *
+*                                                                      *
+*  Covered Software is provided under this License on an "as is"       *
+*  basis, without warranty of any kind, either expressed, implied, or  *
+*  statutory, including, without limitation, warranties that the       *
+*  Covered Software is free of defects, merchantable, fit for a        *
+*  particular purpose or non-infringing. The entire risk as to the     *
+*  quality and performance of the Covered Software is with You.        *
+*  Should any Covered Software prove defective in any respect, You     *
+*  (not any Contributor) assume the cost of any necessary servicing,   *
+*  repair, or correction. This disclaimer of warranty constitutes an   *
+*  essential part of this License. No use of any Covered Software is   *
+*  authorized under this License except under this disclaimer.         *
+*                                                                      *
+************************************************************************
+
+************************************************************************
+*                                                                      *
+*  7. Limitation of Liability                                          *
+*  --------------------------                                          *
+*                                                                      *
+*  Under no circumstances and under no legal theory, whether tort      *
+*  (including negligence), contract, or otherwise, shall any           *
+*  Contributor, or anyone who distributes Covered Software as          *
+*  permitted above, be liable to You for any direct, indirect,         *
+*  special, incidental, or consequential damages of any character      *
+*  including, without limitation, damages for lost profits, loss of    *
+*  goodwill, work stoppage, computer failure or malfunction, or any    *
+*  and all other commercial damages or losses, even if such party      *
+*  shall have been informed of the possibility of such damages. This   *
+*  limitation of liability shall not apply to liability for death or   *
+*  personal injury resulting from such party's negligence to the       *
+*  extent applicable law prohibits such limitation. Some               *
+*  jurisdictions do not allow the exclusion or limitation of           *
+*  incidental or consequential damages, so this exclusion and          *
+*  limitation may not apply to You.                                    *
+*                                                                      *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+  This Source Code Form is subject to the terms of the Mozilla Public
+  License, v. 2.0. If a copy of the MPL was not distributed with this
+  file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+  This Source Code Form is "Incompatible With Secondary Licenses", as
+  defined by the Mozilla Public License, v. 2.0.
+
+------------------------------------------------------------------------------
+libtheoradec and libtheoraenc are redistributed within opencv-python macOS packages.
+This license applies to libtheoradec and libtheoraenc binaries in the directory cv2/.
+
+  Copyright (C) 2002-2009 Xiph.org Foundation
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+- Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+
+- Neither the name of the Xiph.org Foundation nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+libwebp and libwebpmux are redistributed within opencv-python macOS packages.
+This license applies to libwebp  and libwebpmux binaries in the directory cv2/.
+
+Copyright (c) 2010, Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+  * Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+
+  * Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+
+  * Neither the name of Google nor the names of its contributors may
+    be used to endorse or promote products derived from this software
+    without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+libvorbis and libvorbisenc are redistributed within opencv-python macOS packages.
+This license applies to libvorbis and libvorbisenc binaries in the directory cv2/.
+
+Copyright (c) 2002-2020 Xiph.org Foundation
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+- Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+
+- Neither the name of the Xiph.org Foundation nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+Libxcb utility libraries are redistributed within opencv-python non-headless Linux packages.
+This license applies to libxcb related binaries in the directory cv2/.
+
+Copyright (C) 2001-2006 Bart Massey, Jamey Sharp, and Josh Triplett.
+All Rights Reserved.
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall
+be included in all copies or substantial portions of the
+Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the names of the authors
+or their institutions shall not be used in advertising or
+otherwise to promote the sale, use or other dealings in this
+Software without prior written authorization from the
+authors.
+
+------------------------------------------------------------------------------
+Libxcb-image is redistributed within opencv-python non-headless Linux packages.
+This license applies to libxcb-image binary in the directory cv2/.
+
+Copyright © 2007-2008 Bart Massey <bart@cs.pdx.edu>
+Copyright © 2008 Julien Danjou <julien@danjou.info>
+Copyright © 2008 Keith Packard <keithp@keithp.com>
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use, copy,
+modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the names of the authors or
+their institutions shall not be used in advertising or otherwise to
+promote the sale, use or other dealings in this Software without
+prior written authorization from the authors.
+
+------------------------------------------------------------------------------
+Libxcb-util is redistributed within opencv-python non-headless Linux packages.
+This license applies to libxcb-util binary in the directory cv2/.
+
+Copyright © 2008 Bart Massey <bart@cs.pdx.edu>
+Copyright © 2008 Ian Osgood <iano@quirkster.com>
+Copyright © 2008 Jamey Sharp <jamey@minilop.net>
+Copyright © 2008 Josh Triplett <josh@freedesktop.org>
+Copyright © 2008-2009 Julien Danjou <julien@danjou.info>
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use, copy,
+modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the names of the authors or
+their institutions shall not be used in advertising or otherwise to
+promote the sale, use or other dealings in this Software without
+prior written authorization from the authors.
+
+------------------------------------------------------------------------------
+Libxcb-render-util is redistributed within opencv-python non-headless Linux packages.
+This license applies to libxcb-render-util binary in the directory cv2/.
+
+Copyright © 2000 Keith Packard
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation, and that the name of Keith Packard not be used in
+advertising or publicity pertaining to distribution of the software without
+specific, written prior permission.  Keith Packard makes no
+representations about the suitability of this software for any purpose.  It
+is provided "as is" without express or implied warranty.
+
+KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+
+Copyright © 2006 Jamey Sharp.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the names of the authors or their
+institutions shall not be used in advertising or otherwise to promote the
+sale, use or other dealings in this Software without prior written
+authorization from the authors.
+
+Copyright © 2006 Ian Osgood
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the names of the authors or their
+institutions shall not be used in advertising or otherwise to promote the
+sale, use or other dealings in this Software without prior written
+authorization from the authors.
+
+------------------------------------------------------------------------------
+Libxcb-icccm is redistributed within opencv-python non-headless Linux packages.
+This license applies to Libxcb-icccm binary in the directory cv2/.
+
+Copyright © 2008-2011 Arnaud Fontaine <arnau@debian.org>
+Copyright © 2007-2008 Vincent Torri <vtorri@univ-evry.fr>
+
+Permission  is  hereby  granted,  free  of charge,  to  any  person
+obtaining  a copy  of  this software  and associated  documentation
+files   (the  "Software"),   to  deal   in  the   Software  without
+restriction, including without limitation  the rights to use, copy,
+modify, merge, publish,  distribute, sublicense, and/or sell copies
+of  the Software, and  to permit  persons to  whom the  Software is
+furnished to do so, subject to the following conditions:
+
+The  above copyright  notice and  this permission  notice  shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE  IS PROVIDED  "AS IS", WITHOUT  WARRANTY OF  ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT  NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY,   FITNESS    FOR   A   PARTICULAR    PURPOSE   AND
+NONINFRINGEMENT. IN  NO EVENT SHALL  THE AUTHORS BE LIABLE  FOR ANY
+CLAIM,  DAMAGES  OR  OTHER  LIABILITY,  WHETHER  IN  AN  ACTION  OF
+CONTRACT, TORT OR OTHERWISE, ARISING  FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as  contained in  this notice, the  names of the  authors or
+their institutions shall not be used in advertising or otherwise to
+promote the  sale, use or  other dealings in this  Software without
+prior written authorization from the authors.
+
+------------------------------------------------------------------------------
+libXau is redistributed within opencv-python non-headless Linux packages.
+This license applies to libXau binary in the directory cv2/.
+
+Copyright 1988, 1993, 1994, 1998  The Open Group
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall not be
+used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization from The Open Group.
\ No newline at end of file
diff --git a/LICENSE.txt b/LICENSE.txt
index af1ba757..328bf506 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -1,6 +1,6 @@
 MIT License
 
-Copyright (c) 2016-2017 Olli-Pekka Heinisuo and contributors
+Copyright (c) Olli-Pekka Heinisuo
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 00000000..b429eae0
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,12 @@
+include LICENSE-3RD-PARTY.txt
+include LICENSE.txt
+include README.md
+include find_version.py
+include setup.py
+include pyproject.toml
+recursive-include cv2 *
+recursive-include docker *
+recursive-include opencv *
+recursive-include opencv_contrib *
+recursive-include patches *
+recursive-include scripts *.py
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..d60fcdf2
--- /dev/null
+++ b/README.md
@@ -0,0 +1,230 @@
+[![Downloads](http://pepy.tech/badge/opencv-python)](http://pepy.tech/project/opencv-python)
+
+## OpenCV on Wheels
+
+Pre-built CPU-only OpenCV packages for Python.
+
+Check the manual build section if you wish to compile the bindings from source to enable additional modules such as CUDA.
+
+### Installation and Usage
+
+1. If you have previous/other manually installed (= not installed via ``pip``) version of OpenCV installed (e.g. cv2 module in the root of Python's site-packages), remove it before installation to avoid conflicts.
+2. Make sure that your `pip` version is up-to-date (19.3 is the minimum supported version): `pip install --upgrade pip`. Check version with `pip -V`. For example Linux distributions ship usually with very old `pip` versions which cause a lot of unexpected problems especially with the `manylinux` format.
+3. Select the correct package for your environment:
+
+    There are four different packages (see options 1, 2, 3 and 4 below) and you should **SELECT ONLY ONE OF THEM**. Do not install multiple different packages in the same environment. There is no plugin architecture: all the packages use the same namespace (`cv2`). If you installed multiple different packages in the same environment, uninstall them all with ``pip uninstall`` and reinstall only one package.
+
+    **a.** Packages for standard desktop environments (Windows, macOS, almost any GNU/Linux distribution)
+
+    - Option 1 - Main modules package: ``pip install opencv-python``
+    - Option 2 - Full package (contains both main modules and contrib/extra modules): ``pip install opencv-contrib-python`` (check contrib/extra modules listing from [OpenCV documentation](https://docs.opencv.org/master/))
+
+    **b.** Packages for server (headless) environments (such as Docker, cloud environments etc.), no GUI library dependencies
+
+    These packages are smaller than the two other packages above because they do not contain any GUI functionality (not compiled with Qt / other GUI components). This means that the packages avoid a heavy dependency chain to X11 libraries and you will have for example smaller Docker images as a result. You should always use these packages if you do not use `cv2.imshow` et al. or you are using some other package (such as PyQt) than OpenCV to create your GUI.
+
+    - Option 3 - Headless main modules package: ``pip install opencv-python-headless``
+    - Option 4 - Headless full package (contains both main modules and contrib/extra modules): ``pip install opencv-contrib-python-headless`` (check contrib/extra modules listing from [OpenCV documentation](https://docs.opencv.org/master/))
+
+4. Import the package:
+
+    ``import cv2``
+
+    All packages contain Haar cascade files. ``cv2.data.haarcascades`` can be used as a shortcut to the data folder. For example:
+
+    ``cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")``
+
+5. Read [OpenCV documentation](https://docs.opencv.org/master/)
+
+6. Before opening a new issue, read the FAQ below and have a look at the other issues which are already open.
+
+Frequently Asked Questions
+--------------------------
+
+**Q: Do I need to install also OpenCV separately?**
+
+A: No, the packages are special wheel binary packages and they already contain statically built OpenCV binaries.
+
+**Q: Pip install fails with ``ModuleNotFoundError: No module named 'skbuild'``?**
+
+Since ``opencv-python`` version 4.3.0.\*, ``manylinux1`` wheels were replaced by ``manylinux2014`` wheels. If your pip is too old, it will try to use the new source distribution introduced in 4.3.0.38 to manually build OpenCV because it does not know how to install ``manylinux2014`` wheels. However, source build will also fail because of too old ``pip`` because it does not understand build dependencies in ``pyproject.toml``. To use the new ``manylinux2014`` pre-built wheels (or to build from source), your ``pip`` version must be >= 19.3. Please upgrade ``pip`` with ``pip install --upgrade pip``.
+
+**Q: Import fails on Windows: ``ImportError: DLL load failed: The specified module could not be found.``?**
+
+A: If the import fails on Windows, make sure you have [Visual C++ redistributable 2015](https://www.microsoft.com/en-us/download/details.aspx?id=48145) installed. If you are using older Windows version than Windows 10 and latest system updates are not installed, [Universal C Runtime](https://support.microsoft.com/en-us/help/2999226/update-for-universal-c-runtime-in-windows) might be also required.
+
+Windows N and KN editions do not include Media Feature Pack which is required by OpenCV. If you are using Windows N or KN edition, please install also [Windows Media Feature Pack](https://support.microsoft.com/en-us/help/3145500/media-feature-pack-list-for-windows-n-editions).
+
+If you have Windows Server 2012+, media DLLs are probably missing too; please install the Feature called "Media Foundation" in the Server Manager. Beware, some posts advise to install "Windows Server Essentials Media Pack", but this one requires the "Windows Server Essentials Experience" role, and this role will deeply affect your Windows Server configuration (by enforcing active directory integration etc.); so just installing the "Media Foundation" should be a safer choice.
+
+If the above does not help, check if you are using Anaconda. Old Anaconda versions have a bug which causes the error, see [this issue](https://github.com/opencv/opencv-python/issues/36) for a manual fix.
+
+If you still encounter the error after you have checked all the previous solutions, download [Dependencies](https://github.com/lucasg/Dependencies) and open the ``cv2.pyd`` (located usually at ``C:\Users\username\AppData\Local\Programs\Python\PythonXX\Lib\site-packages\cv2``) file with it to debug missing DLL issues.
+
+**Q: I have some other import errors?**
+
+A: Make sure you have removed old manual installations of OpenCV Python bindings (cv2.so or cv2.pyd in site-packages).
+
+**Q: Function foo() or method bar() returns wrong result, throws exception or crashes interpreter. What should I do?**
+
+A: The repository contains only OpenCV-Python package build scripts, but not OpenCV itself. Python bindings for OpenCV are developed in official OpenCV repository and it's the best place to report issues. Also please check {OpenCV wiki](https://github.com/opencv/opencv/wiki) and [the official OpenCV forum](https://forum.opencv.org/) before file new bugs.
+
+**Q: Why the packages do not include non-free algorithms?**
+
+A: Non-free algorithms such as SURF are not included in these packages because they are patented / non-free and therefore cannot be distributed as built binaries. Note that SIFT is included in the builds due to patent expiration since OpenCV versions 4.3.0 and 3.4.10. See this issue for more info: https://github.com/skvark/opencv-python/issues/126
+
+**Q: Why the package and import are different (opencv-python vs. cv2)?**
+
+A: It's easier for users to understand ``opencv-python`` than ``cv2`` and it makes it easier to find the package with search engines. `cv2` (old interface in old OpenCV versions was named as `cv`) is the name that OpenCV developers chose when they created the binding generators. This is kept as the import name to be consistent with different kind of tutorials around the internet. Changing the import name or behaviour would be also confusing to experienced users who are accustomed to the ``import cv2``.
+
+## Documentation for opencv-python
+
+[![Windows Build Status](https://github.com/opencv/opencv-python/actions/workflows/build_wheels_windows.yml/badge.svg)](https://github.com/opencv/opencv-python/actions/workflows/build_wheels_windows.yml)
+[![(Linux Build status)](https://github.com/opencv/opencv-python/actions/workflows/build_wheels_linux.yml/badge.svg)](https://github.com/opencv/opencv-python/actions/workflows/build_wheels_linux.yml)
+[![(Mac OS Build status)](https://github.com/opencv/opencv-python/actions/workflows/build_wheels_macos.yml/badge.svg)](https://github.com/opencv/opencv-python/actions/workflows/build_wheels_macos.yml)
+
+The aim of this repository is to provide means to package each new [OpenCV release](https://github.com/opencv/opencv/releases) for the most used Python versions and platforms.
+
+### CI build process
+
+The project is structured like a normal Python package with a standard ``setup.py`` file.
+The build process for a single entry in the build matrices is as follows (see for example `.github/workflows/build_wheels_linux.yml` file):
+
+0. In Linux and MacOS build: get OpenCV's optional C dependencies that we compile against
+
+1. Checkout repository and submodules
+
+   -  OpenCV is included as submodule and the version is updated
+      manually by maintainers when a new OpenCV release has been made
+   -  Contrib modules are also included as a submodule
+
+2. Find OpenCV version from the sources
+
+3. Build OpenCV
+
+   -  tests are disabled, otherwise build time increases too much
+   -  there are 4 build matrix entries for each build combination: with and without contrib modules, with and without GUI (headless)
+   -  Linux builds run in manylinux Docker containers (CentOS 5)
+   -  source distributions are separate entries in the build matrix
+
+4. Rearrange OpenCV's build result, add our custom files and generate wheel
+
+5. Linux and macOS wheels are transformed with auditwheel and delocate, correspondingly
+
+6. Install the generated wheel
+7. Test that Python can import the library and run some sanity checks
+8. Use twine to upload the generated wheel to PyPI (only in release builds)
+
+Steps 1--4 are handled by ``pip wheel``.
+
+The build can be customized with environment variables. In addition to any variables that OpenCV's build accepts, we recognize:
+
+- ``CI_BUILD``. Set to ``1`` to emulate the CI environment build behaviour. Used only in CI builds to force certain build flags on in ``setup.py``. Do not use this unless you know what you are doing.
+- ``ENABLE_CONTRIB`` and ``ENABLE_HEADLESS``. Set to ``1`` to build the contrib and/or headless version
+- ``ENABLE_JAVA``, Set to ``1`` to enable the Java client build.  This is disabled by default.
+- ``CMAKE_ARGS``. Additional arguments for OpenCV's CMake invocation. You can use this to make a custom build.
+
+See the next section for more info about manual builds outside the CI environment.
+
+### Manual builds
+
+If some dependency is not enabled in the pre-built wheels, you can also run the build locally to create a custom wheel.
+
+1. Clone this repository: `git clone --recursive https://github.com/opencv/opencv-python.git`
+2. ``cd opencv-python``
+    - you can use `git` to checkout some other version of OpenCV in the `opencv` and `opencv_contrib` submodules if needed
+3. Add custom Cmake flags if needed, for example: `export CMAKE_ARGS="-DSOME_FLAG=ON -DSOME_OTHER_FLAG=OFF"` (in Windows you need to set environment variables differently depending on Command Line or PowerShell)
+4. Select the package flavor which you wish to build with `ENABLE_CONTRIB` and `ENABLE_HEADLESS`: i.e. `export ENABLE_CONTRIB=1` if you wish to build `opencv-contrib-python`
+5. Run ``pip wheel . --verbose``. NOTE: make sure you have the latest ``pip`` version, the ``pip wheel`` command replaces the old ``python setup.py bdist_wheel`` command which does not support ``pyproject.toml``.
+    - this might take anything from 5 minutes to over 2 hours depending on your hardware
+6. You'll have the wheel file in the `dist` folder and you can do with that whatever you wish
+    - Optional: on Linux use some of the `manylinux` images as a build hosts if maximum portability is needed and run `auditwheel` for the wheel after build
+    - Optional: on macOS use ``delocate`` (same as ``auditwheel`` but for macOS) for better portability
+
+#### Manual debug builds
+
+In order to build `opencv-python` in an unoptimized debug build, you need to side-step the normal process a bit.
+
+1. Install the packages `scikit-build` and `numpy` via pip.
+2. Run the command `python setup.py bdist_wheel --build-type=Debug`.
+3. Install the generated wheel file in the `dist/` folder with `pip install dist/wheelname.whl`.
+
+If you would like the build produce all compiler commands, then the following combination of flags and environment variables has been tested to work on Linux:
+```
+export CMAKE_ARGS='-DCMAKE_VERBOSE_MAKEFILE=ON'
+export VERBOSE=1
+
+python3 setup.py bdist_wheel --build-type=Debug
+```
+
+See this issue for more discussion: https://github.com/opencv/opencv-python/issues/424
+
+#### Source distributions
+
+Since OpenCV version 4.3.0, also source distributions are provided in PyPI. This means that if your system is not compatible with any of the wheels in PyPI, ``pip`` will attempt to build OpenCV from sources. If you need a OpenCV version which is not available in PyPI as a source distribution, please follow the manual build guidance above instead of this one.
+
+You can also force ``pip`` to build the wheels from the source distribution. Some examples:
+
+- ``pip install --no-binary opencv-python opencv-python``
+- ``pip install --no-binary :all: opencv-python``
+
+If you need contrib modules or headless version, just change the package name (step 4 in the previous section is not needed). However, any additional CMake flags can be provided via environment variables as described in step 3 of the manual build section. If none are provided, OpenCV's CMake scripts will attempt to find and enable any suitable dependencies. Headless distributions have hard coded CMake flags which disable all possible GUI dependencies.
+
+On slow systems such as Raspberry Pi the full build may take several hours. On a 8-core Ryzen 7 3700X the build takes about 6 minutes.
+
+### Licensing
+
+Opencv-python package (scripts in this repository) is available under MIT license.
+
+OpenCV itself is available under [Apache 2](https://github.com/opencv/opencv/blob/master/LICENSE) license.
+
+Third party package licenses are at [LICENSE-3RD-PARTY.txt](https://github.com/opencv/opencv-python/blob/master/LICENSE-3RD-PARTY.txt).
+
+All wheels ship with [FFmpeg](http://ffmpeg.org) licensed under the [LGPLv2.1](http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html).
+
+Non-headless Linux wheels ship with [Qt 5](http://doc.qt.io/qt-5/lgpl.html) licensed under the [LGPLv3](http://www.gnu.org/licenses/lgpl-3.0.html).
+
+The packages include also other binaries. Full list of licenses can be found from [LICENSE-3RD-PARTY.txt](https://github.com/opencv/opencv-python/blob/master/LICENSE-3RD-PARTY.txt).
+
+### Versioning
+
+``find_version.py`` script searches for the version information from OpenCV sources and appends also a revision number specific to this repository to the version string. It saves the version information to ``version.py`` file under ``cv2`` in addition to some other flags.
+
+### Releases
+
+A release is made and uploaded to PyPI when a new tag is pushed to master branch. These tags differentiate packages (this repo might have modifications but OpenCV version stays same) and should be incremented sequentially. In practice, release version numbers look like this:
+
+``cv_major.cv_minor.cv_revision.package_revision`` e.g. ``3.1.0.0``
+
+The master branch follows OpenCV master branch releases. 3.4 branch follows OpenCV 3.4 bugfix releases.
+
+### Development builds
+
+Every commit to the master branch of this repo will be built. Possible build artifacts use local version identifiers:
+
+``cv_major.cv_minor.cv_revision+git_hash_of_this_repo`` e.g. ``3.1.0+14a8d39``
+
+These artifacts can't be and will not be uploaded to PyPI.
+
+### Manylinux wheels
+
+Linux wheels are built using [manylinux2014](https://github.com/pypa/manylinux). These wheels should work out of the box for most of the distros (which use GNU C standard library) out there since they are built against an old version of glibc.
+
+The default ``manylinux2014`` images have been extended with some OpenCV dependencies. See [Docker folder](https://github.com/skvark/opencv-python/tree/master/docker) for more info.
+
+### Supported Python versions
+
+Python 3.x compatible pre-built wheels are provided for the officially supported Python versions (not in EOL):
+
+- 3.6
+- 3.7
+- 3.8
+- 3.9
+- 3.10
+
+### Backward compatibility
+
+Starting from 4.2.0 and 3.4.9 builds the macOS Travis build environment was updated to XCode 9.4. The change effectively dropped support for older than 10.13 macOS versions.
+
+Starting from 4.3.0 and 3.4.10 builds the Linux build environment was updated from `manylinux1` to `manylinux2014`. This dropped support for old Linux distributions.
+
diff --git a/README.rst b/README.rst
deleted file mode 100644
index 795a359b..00000000
--- a/README.rst
+++ /dev/null
@@ -1,190 +0,0 @@
-OpenCV on Wheels
-================
-
-**Unofficial** OpenCV packages for Python.
-
-This package contains only the OpenCV core modules without the optional contrib modules.
-If you are looking for a version which includes OpenCV contrib modules, please install `opencv-contrib-python <https://pypi.python.org/pypi/opencv-contrib-python>`__ instead.
-
-The packages contain pre-compiled OpenCV binary with Python bindings.
-This enables super fast (usually < 10 seconds) OpenCV installation for Python.
-
-If you need only OpenCV Python bindings, no separate OpenCV installation is required.
-
-Installation and Usage
-----------------------
-
-1. If you have previous/other version of OpenCV installed (e.g. cv2 module in the root of Python's site-packages), remove it before installation to avoid conflicts.
-
- - To further avoid conflicts and to make development easier, Python's `virtual environments <https://docs.python.org/3/library/venv.html>`__ are highly recommended for development purposes.
-
-2. If you have an existing ``opencv-contrib-python`` installation, run ``pip uninstall opencv-contrib-python``
-
-3. Install this package:
-
-``pip install opencv-python``
-
-4. Import the package:
-
-``import cv2``
-
-The package contains haarcascade files. ``cv2.data.haarcascades`` can be used as a shortcut to the data folder. For example:
-
-``cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")``
-
-5. Read `OpenCV documentation <http://docs.opencv.org/>`__
-
-6. Before opening a new issue, read the FAQ below and have a look at the other issues which are already open.
-
-Frequently Asked Questions
---------------------------
-
-**Q: Do I need to install also OpenCV separately?**
-
-A: No, the packages are special wheel binary packages and they already contain statically built OpenCV binaries.
-
-**Q: Pip does not find package ``opencv-python``?**
-
-A: The wheel package format and manylinux builds are pretty new things. Most likely the issue is related to too old pip and can be fixed by running ``pip install --upgrade pip`` and ``pip install wheel``.
-
-**Q: I need contrib modules?**
-
-A: Please install `opencv-contrib-python <https://pypi.python.org/pypi/opencv-contrib-python>`__ instead. However, note that commercial usage might be restricted in some countries since the contrib modules might contain some non-free/patented algorithms.
-
-**Q: Import fails on Windows to some DLL load error?**
-
-A: If the import fails on Windows, make sure you have `Visual C++ redistributable 2015 <https://www.microsoft.com/en-us/download/details.aspx?id=48145>`__ installed. If you are using older Windows version than Windows 10 and latest system updates are not installed, `Universal C Runtime <https://support.microsoft.com/en-us/help/2999226/update-for-universal-c-runtime-in-windows>`__ might be also required.
-
-See also `this issue <https://github.com/skvark/opencv-python/issues/36>`__ if you are using Anaconda.
-
-**Q: I have some other import errors?**
-
-A: Make sure you have removed old manual installations of OpenCV Python bindings (cv2.so or cv2.pyd in site-packages).
-
-Documentation for opencv-python
--------------------------------
-
-.. image:: https://img.shields.io/appveyor/ci/skvark/opencv-python.svg?maxAge=3600&label=Windows
-   :target: https://ci.appveyor.com/project/skvark/opencv-python
-   :alt: AppVeyor CI test status (Windows)
-
-.. image:: https://img.shields.io/travis/skvark/opencv-python.svg?maxAge=3600&label="Linux / OS X"
-   :target: https://travis-ci.org/skvark/opencv-python
-   :alt: Travis CI test status (Linux and OS X)
-
-The aim of this repository is to provide means to package each new
-`OpenCV release <https://github.com/opencv/opencv/releases>`__ for the
-most used Python versions and platforms.
-
-At the same time it allows anyone to build a custom version of OpenCV
-for any Python version: just fork this repo and modify the build files
-and scripts to fit your needs.
-
-Build process
--------------
-
-The project is structured like a normal Python package with a standard
-``setup.py`` file. The build process for a single entry in the build matrices is as follows (see for example
-``appveyor.yml`` file):
-
-1. Checkout repository and submodules
-
-   -  OpenCV is included as submodule and the version is updated
-      manually by maintainers when a new OpenCV release has been made
-   -  Contrib modules are also included as a submodule
-
-2. Find OpenCV version from the sources
-3. Install dependencies (numpy)
-4. Build OpenCV
-
-   -  tests are disabled, otherwise build time increases too much
-   -  there are 2 build matrix entries for each build combination: with and without contrib modules
-   -  Linux builds run in manylinux Docker containers (CentOS 5)
-
-5. Copy each ``.pyd/.so`` file to cv2 folder of this project and
-   generate wheel
-
-   - Linux and macOS wheels are checked with auditwheel and delocate
-
-6. Install the generated wheel
-7. Test that Python can import the library and run some sanity checks
-8. Use twine to upload the generated wheel to PyPI (only in release builds)
-
-Currently the ``find_version.py`` file parses OpenCV version information
-from the OpenCV sources. OpenCV depends on numpy, so ``setup.py`` checks
-the minimum required numpy version also with the help of pip.
-
-The ``cv2.pyd/.so`` file is normally copied to site-packages.
-To avoid polluting the root folder this package wraps
-the statically built binary into cv2 package and ``__init__.py``
-file in the package handles the import logic correctly.
-
-Since both ``opencv-python`` and ``opencv-contrib-python`` use the same namespace explained above,
-it is highly recommended to uninstall the other package before switching from example from
-``opencv-python`` to ``opencv-contrib-python`` package.
-
-Licensing
----------
-
-Opencv-python package (scripts in this repository) is available under
-MIT license.
-
-OpenCV itself is available under `3-clause BSD
-License <https://github.com/opencv/opencv/blob/master/LICENSE>`__
-(`LICENSE-3RD-PARTY.txt <https://github.com/skvark/opencv-python/blob/master/LICENSE-3RD-PARTY.txt>`__).
-
-All wheels ship with `FFmpeg <http://ffmpeg.org>`__ licensed under the `LGPLv2.1 <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>`__.
-
-Linux and MacOS wheels ship with `Qt 4.8.7 <http://doc.qt.io/qt-4.8/lgpl.html>`__ licensed under the `LGPLv2.1 <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>`__.
-
-Versioning
-----------
-
-Currently the ``find_version.py`` script searches for the version
-information from OpenCV sources and appends also a revision number
-specific to this repository to the version string.
-
-Releases
-~~~~~~~~
-
-A release is made and uploaded to PyPI when a new tag is pushed to
-master branch. These tags differentiate packages (this repo might have
-modifications but OpenCV version stays same) and should be incremented
-sequentially. In practice, release version numbers look like this:
-
-``cv_major.cv_minor.cv_revision.package_revision`` e.g. ``3.1.0.0``
-
-Development builds
-~~~~~~~~~~~~~~~~~~
-
-Every commit to the master branch of this repo will be built. Possible
-build artifacts use local version identifiers:
-
-``cv_major.cv_minor.cv_revision+git_hash_of_this_repo`` e.g.
-``3.1.0+14a8d39``
-
-These artifacts can't be and will not be uploaded to PyPI.
-
-Manylinux wheels
-----------------
-
-Linux wheels are built using
-`manylinux <https://github.com/pypa/python-manylinux-demo>`__. These
-wheels should work out of the box for most of the distros
-(which use GNU C standard library) out there since they are built
-against an old version of glibc.
-
-Supported Python versions
--------------------------
-
-Python 2.7 is the only supported version in 2.x series.
-Python 3.x releases follow Numpy releases, for example
-Python 3.3 is no longer supported by Numpy so the support
-for it has been dropped in ``opencv-python`` too.
-
-Currently, builds for following Python versions are provided:
-
-- 2.7
-- 3.4
-- 3.5
-- 3.6
diff --git a/README_CONTRIB.rst b/README_CONTRIB.rst
deleted file mode 100644
index 0fe36e50..00000000
--- a/README_CONTRIB.rst
+++ /dev/null
@@ -1,186 +0,0 @@
-OpenCV on Wheels
-================
-
-**Unofficial** OpenCV packages for Python with contrib modules.
-
-**Note: the (commercial) usage of opencv-contrib-python might be restricted in some countries since the contrib package might contain some patented algorithms/non-free modules.**
-
-If you are looking for a version without the contrib modules, please install `opencv-python <https://pypi.python.org/pypi/opencv-python>`__ instead.
-
-The packages contain pre-compiled OpenCV binary with Python bindings.
-This enables super fast (usually < 10 seconds) OpenCV installation for Python.
-
-If you need only OpenCV Python bindings, no separate OpenCV installation is required.
-
-Installation and Usage
-----------------------
-
-1. If you have previous/other version of OpenCV installed (e.g. cv2 module in the root of Python's site-packages), remove it before installation to avoid conflicts.
-
- - To further avoid conflicts and to make development easier, Python's `virtual environments <https://docs.python.org/3/library/venv.html>`__ are highly recommended for development purposes.
-
-2. If you have an existing ``opencv-python`` installation, run ``pip uninstall opencv-python``
-3. Install this package:
-
-``pip install opencv-contrib-python``
-
-4. Import the package:
-
-``import cv2``
-
-The package contains haarcascade files. ``cv2.data.haarcascades`` can be used as a shortcut to the data folder. For example:
-
-``cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")``
-
-5. Read `OpenCV documentation <http://docs.opencv.org/>`__
-
-6. Before opening a new issue, read the FAQ below and have a look at the other issues which are already open.
-
-Frequently Asked Questions
---------------------------
-
-**Q: Do I need to install also OpenCV separately?**
-
-A: No, the packages are special wheel binary packages and they already contain statically built OpenCV binaries.
-
-**Q: Pip does not find package opencv-contrib-python?**
-
-A: The wheel package format and manylinux builds are pretty new things. Most likely the issue is related to too old pip and can be fixed by running ``pip install --upgrade pip`` and ``pip install wheel``.
-
-**Q: Import fails on Windows to some DLL load error?**
-
-A: If the import fails on Windows, make sure you have `Visual C++ redistributable 2015 <https://www.microsoft.com/en-us/download/details.aspx?id=48145>`__ installed. If you are using older Windows version than Windows 10 and latest system updates are not installed, `Universal C Runtime <https://support.microsoft.com/en-us/help/2999226/update-for-universal-c-runtime-in-windows>`__ might be also required.
-
-See also `this issue <https://github.com/skvark/opencv-python/issues/36>`__ if you are using Anaconda.
-
-**Q: I have some other import errors?**
-
-A: Make sure you have removed old manual installations of OpenCV Python bindings (cv2.so or cv2.pyd in site-packages).
-
-Documentation for opencv-python
--------------------------------
-
-.. image:: https://img.shields.io/appveyor/ci/skvark/opencv-python.svg?maxAge=3600&label=Windows
-   :target: https://ci.appveyor.com/project/skvark/opencv-python
-   :alt: AppVeyor CI test status (Windows)
-
-.. image:: https://img.shields.io/travis/skvark/opencv-python.svg?maxAge=3600&label="Linux / OS X"
-   :target: https://travis-ci.org/skvark/opencv-python
-   :alt: Travis CI test status (Linux and OS X)
-
-The aim of this repository is to provide means to package each new
-`OpenCV release <https://github.com/opencv/opencv/releases>`__ for the
-most used Python versions and platforms.
-
-At the same time it allows anyone to build a custom version of OpenCV
-for any Python version: just fork this repo and modify the build files
-and scripts to fit your needs.
-
-Build process
--------------
-
-The project is structured like a normal Python package with a standard
-``setup.py`` file. The build process for a single entry in the build matrices is as follows (see for example
-``appveyor.yml`` file):
-
-1. Checkout repository and submodules
-
-   -  OpenCV is included as submodule and the version is updated
-      manually by maintainers when a new OpenCV release has been made
-   -  Contrib modules are also included as a submodule
-
-2. Find OpenCV version from the sources
-3. Install dependencies (numpy)
-4. Build OpenCV
-
-   -  tests are disabled, otherwise build time increases too much
-   -  there are 2 build matrix entries for each build combination: with and without contrib modules
-   -  Linux builds run in manylinux Docker containers (CentOS 5)
-
-5. Copy each ``.pyd/.so`` file to cv2 folder of this project and
-   generate wheel
-
-   - Linux and macOS wheels are checked with auditwheel and delocate
-
-6. Install the generated wheel
-7. Test that python can import the library and run some sanity checks
-8. Use twine to upload the generated wheel to PyPI (only in release builds)
-
-Currently the ``find_version.py`` file parses OpenCV version information
-from the OpenCV sources. OpenCV depends on numpy, so ``setup.py`` checks
-the minimum required numpy version also with the help of pip.
-
-The ``cv2.pyd/.so`` file is normally copied to site-packages.
-To avoid polluting the root folder this package wraps
-the statically built binary into cv2 package and ``__init__.py``
-file in the package handles the import logic correctly.
-
-Since both ``opencv-python`` and ``opencv-python-contrib`` use the same namespace explained above,
-it is highly recommended to uninstall the other package before switching from example from
-``opencv-python`` to ``opencv-python-contrib`` package.
-
-Licensing
----------
-
-Opencv-python package (scripts in this repository) is available under
-MIT license.
-
-OpenCV itself is available under `3-clause BSD
-License <https://github.com/opencv/opencv/blob/master/LICENSE>`__
-(`LICENSE-3RD-PARTY.txt <https://github.com/skvark/opencv-python/blob/master/LICENSE-3RD-PARTY.txt>`__).
-
-All wheels ship with `FFmpeg <http://ffmpeg.org>`__ licensed under the `LGPLv2.1 <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>`__.
-
-Linux and MacOS wheels ship with `Qt 4.8.7 <http://doc.qt.io/qt-4.8/lgpl.html>`__ licensed under the `LGPLv2.1 <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>`__.
-
-Versioning
-----------
-
-Currently the ``find_version.py`` script searches for the version
-information from OpenCV sources and appends also a revision number
-specific to this repository to the version string.
-
-Releases
-~~~~~~~~
-
-A release is made and uploaded to PyPI when a new tag is pushed to
-master branch. These tags differentiate packages (this repo might have
-modifications but OpenCV version stays same) and should be incremented
-sequentially. In practice, release version numbers look like this:
-
-``cv_major.cv_minor.cv_revision.package_revision`` e.g. ``3.1.0.0``
-
-Development builds
-~~~~~~~~~~~~~~~~~~
-
-Every commit to the master branch of this repo will be built. Possible
-build artifacts use local version identifiers:
-
-``cv_major.cv_minor.cv_revision+git_hash_of_this_repo`` e.g.
-``3.1.0+14a8d39``
-
-These artifacts can't be and will not be uploaded to PyPI.
-
-Manylinux wheels
-----------------
-
-Linux wheels are built using
-`manylinux <https://github.com/pypa/python-manylinux-demo>`__. These
-wheels should work out of the box for most of the distros
-(which use GNU C standard library) out there since they are built
-against an old version of glibc.
-
-Supported Python versions
--------------------------
-
-Python 2.7 is the only supported version in 2.x series.
-Python 3.x releases follow Numpy releases, for example
-Python 3.3 is no longer supported by Numpy so the support
-for it has been dropped in ``opencv-python`` too.
-
-Currently, builds for following Python versions are provided:
-
-- 2.7
-- 3.4
-- 3.5
-- 3.6
diff --git a/appveyor.yml b/appveyor.yml
deleted file mode 100644
index 80bd5e97..00000000
--- a/appveyor.yml
+++ /dev/null
@@ -1,96 +0,0 @@
-environment:
-  USER:
-    secure: fXgF9uyy6sT0JoVOR7BoqA==
-
-  PASS:
-    secure: HHNjmjxQSvgSY9Zde0qh6A==
-
-  matrix:
-    - PYTHON: "C:/Python27"
-      ENABLE_CONTRIB: 0
-
-    - PYTHON: "C:/Python27-x64"
-      ENABLE_CONTRIB: 0
-
-    - PYTHON: "C:/Python34"
-      ENABLE_CONTRIB: 0
-
-    - PYTHON: "C:/Python34-x64"
-      ENABLE_CONTRIB: 0
-
-    - PYTHON: "C:/Python35"
-      ENABLE_CONTRIB: 0
-
-    - PYTHON: "C:/Python35-x64"
-      ENABLE_CONTRIB: 0
-
-    - PYTHON: "C:/Python36"
-      ENABLE_CONTRIB: 0
-
-    - PYTHON: "C:/Python36-x64"
-      ENABLE_CONTRIB: 0
-
-    - PYTHON: "C:/Python27"
-      ENABLE_CONTRIB: 1
-
-    - PYTHON: "C:/Python27-x64"
-      ENABLE_CONTRIB: 1
-
-    - PYTHON: "C:/Python34"
-      ENABLE_CONTRIB: 1
-
-    - PYTHON: "C:/Python34-x64"
-      ENABLE_CONTRIB: 1
-
-    - PYTHON: "C:/Python35"
-      ENABLE_CONTRIB: 1
-
-    - PYTHON: "C:/Python35-x64"
-      ENABLE_CONTRIB: 1
-
-    - PYTHON: "C:/Python36"
-      ENABLE_CONTRIB: 1
-
-    - PYTHON: "C:/Python36-x64"
-      ENABLE_CONTRIB: 1
-
-matrix:
-    fast_finish: true
-
-      
-build_script:
-- cmd: |
-
-    "%PYTHON%/python.exe" setup.py bdist_wheel
-
-before_test:
-- ps: |
-
-    cd ${Env:APPVEYOR_BUILD_FOLDER}\tests
-    &"${Env:PYTHON}/python.exe" -m pip install --user (ls "../dist/opencv_*.whl")
-    if ($LastExitCode -ne 0) {throw $LastExitCode}
-
-test_script:
-- cmd: |
-
-    cd %APPVEYOR_BUILD_FOLDER%\tests
-    "%PYTHON%/python.exe" -m unittest test
-
-artifacts:
-- path: dist\*.whl
-  name: wheels
-
-deploy_script:
-- ps: |
-
-    if (${Env:APPVEYOR_REPO_TAG} -eq "true") {
-        cd ${Env:APPVEYOR_BUILD_FOLDER}
-        if (${Env:ENABLE_CONTRIB} -eq 0) `
-            {echo "This is a default build. Deployment will be done to PyPI entry opencv-python."} `
-        else `
-            {echo "This is a contrib build. Deployment will be done to PyPI entry opencv-contrib-python."}
-
-        &"${Env:PYTHON}/python.exe" -m pip install twine
-        &"${Env:PYTHON}/python.exe" -m twine upload -u ${Env:USER} -p ${Env:PASS} --skip-existing dist/opencv* } `
-    else
-        {echo "Tag not set, deployment skipped."}
diff --git a/config.sh b/config.sh
deleted file mode 100644
index 3eba50b3..00000000
--- a/config.sh
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/bin/bash
-#Customize multibuild logic that is run after entering docker.
-#Sourced by docker_build_wrap.sh and docker_test_wrap.sh .
-#Runs in Docker, so only the vars passed to `docker run' exist.
-#See multibuild/README.rst
-echo "===  Loading config.sh  === "
-
-# To see build progress
-function build_wheel {
-    build_bdist_wheel $@
-}
-
-if [ -n "$IS_OSX" ]; then
-  echo "    > OSX environment "
-else
-  echo "    > Linux environment "
-fi
-
-function pre_build {
-  echo "Starting pre-build"
-  set -e
-
-  if [ -n "$IS_OSX" ]; then
-    echo "Running for OSX"
-
-    # For some reason, gt@4 and ffmpeg can be preinstalled in Travis Mac env
-    echo 'Installing QT4'
-    brew tap | grep -qxF cartr/qt4 || brew tap -v cartr/qt4
-    brew tap --list-pinned | grep -qxF cartr/qt4 || brew tap-pin -v cartr/qt4
-    brew list --versions qt@4 || brew install -v qt@4
-    echo '-----------------'
-    echo 'Installing FFmpeg'
-    # brew install does produce output regularly on a regular MacOS,
-    # but Travis doesn't see it for some reason
-    brew list --versions ffmpeg || \
-    travis_wait brew install -v ffmpeg --without-x264 --without-xvid --without-gpl
-    brew info ffmpeg
-    echo '-----------------'
-  else
-    echo "Running for linux"
-  fi
-  qmake -query  
-}
-
-function run_tests {
-    # Runs tests on installed distribution from an empty directory
-    echo "Run tests..."
-    echo $PWD
-
-    if [ -n "$IS_OSX" ]; then
-      echo "Running for OS X"
-      cd ../tests/
-    else
-      echo "Running for linux"
-      cd /io/tests/
-    fi
-    
-    test_wheels
-}
-
-function test_wheels {
-    PYTHON=python$PYTHON_VERSION
-
-    echo "Starting tests..."
-
-    #Test package
-    $PYTHON -m unittest test
-}
-
-export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
-set -x
\ No newline at end of file
diff --git a/cv2/__init__.py b/cv2/__init__.py
index 3c176752..e69de29b 100644
--- a/cv2/__init__.py
+++ b/cv2/__init__.py
@@ -1,9 +0,0 @@
-import importlib
-
-# make IDE's (PyCharm) autocompletion happy
-from .cv2 import *
-from .data import *
-
-# wildcard import above does not import "private" variables like __version__
-# this makes them available
-globals().update(importlib.import_module('cv2.cv2').__dict__)
diff --git a/cv2/data/__init__.py b/cv2/data/__init__.py
index 12c818d9..1cad2750 100644
--- a/cv2/data/__init__.py
+++ b/cv2/data/__init__.py
@@ -1,3 +1,3 @@
 import os
 
-haarcascades = os.path.join(os.path.dirname(__file__), '')
+haarcascades = os.path.join(os.path.dirname(__file__), "")
diff --git a/docker/README.md b/docker/README.md
new file mode 100644
index 00000000..6e00e8f3
--- /dev/null
+++ b/docker/README.md
@@ -0,0 +1,9 @@
+### Customized manylinux images for opencv-python
+
+The subfolders include Dockerfiles for extending both ``i686`` and ``x86_64`` manylinux1 and manylinux2014 images.
+
+Manylinux2014 is used in wheels with version 3.4.10.* / 4.3.0.* and above. 
+
+The extended images were created to be able to build OpenCV in reasonable time with Travis. The images are hosted at https://quay.io/user/skvark.
+
+See the dockerfiles for more info.
diff --git a/docker/manylinux1/Dockerfile_i686 b/docker/manylinux1/Dockerfile_i686
new file mode 100644
index 00000000..cffc998c
--- /dev/null
+++ b/docker/manylinux1/Dockerfile_i686
@@ -0,0 +1,111 @@
+FROM quay.io/pypa/manylinux1_i686:latest
+
+RUN curl -O -L https://download.qt.io/archive/qt/4.8/4.8.7/qt-everywhere-opensource-src-4.8.7.tar.gz && \
+    tar -xf qt-everywhere-opensource-src-4.8.7.tar.gz && \
+    cd qt-everywhere* && \
+    #configure does a bootstrap make under the hood
+    #manylinux1 is too old to have `nproc`
+    export MAKEFLAGS=-j$(getconf _NPROCESSORS_ONLN) && \
+    #OpenCV only links against QtCore, QtGui, QtTest
+    ./configure -prefix /opt/Qt4.8.7 -release -opensource -confirm-license -make && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf qt-everywhere-opensource-src-4.8.7 && \
+    rm qt-everywhere-opensource-src-4.8.7.tar.gz
+
+ENV QTDIR /opt/Qt4.8.7
+ENV PATH "$QTDIR/bin:$PATH"
+
+RUN curl -O -L https://cmake.org/files/v3.9/cmake-3.9.0.tar.gz && \
+    tar -xf cmake-3.9.0.tar.gz && \
+    cd cmake-3.9.0 && \
+    #manylinux1 provides curl-devel equivalent and libcurl statically linked
+    # against the same newer OpenSSL as other source-built tools
+    # (1.0.2s as of this writing)
+    yum -y install zlib-devel && \
+    #configure does a bootstrap make under the hood
+    export MAKEFLAGS=-j$(getconf _NPROCESSORS_ONLN) && \
+    ./configure --system-curl && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf cmake-3.9.0*
+
+# https://trac.ffmpeg.org/wiki/CompilationGuide/Centos#GettheDependencies
+# manylinux provides the toolchain and git; we provide cmake
+RUN yum install freetype-devel bzip2-devel zlib-devel -y && \
+    mkdir ~/ffmpeg_sources
+
+# Newer openssl configure requires newer perl
+RUN curl -O -L https://www.cpan.org/src/5.0/perl-5.20.1.tar.gz && \
+    tar -xf perl-5.20.1.tar.gz && \
+    cd perl-5.20.1 && \
+    ./Configure -des -Dprefix="$HOME/openssl_build" && \
+    #perl build scripts do much redundant work
+    # if running "make install" separately
+    make install -j$(getconf _NPROCESSORS_ONLN) && \
+    cd .. && \
+    rm -rf perl-5.20.1*
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L https://github.com/openssl/openssl/archive/OpenSSL_1_1_1c.tar.gz && \
+    tar -xf OpenSSL_1_1_1c.tar.gz && \
+    cd openssl-OpenSSL_1_1_1c && \
+    #in i686, ./config detects x64 in i686 container without linux32
+    # when run from "docker build"
+    PERL="$HOME/openssl_build/bin/perl" linux32 ./config --prefix="$HOME/ffmpeg_build" --openssldir="$HOME/ffmpeg_build" shared zlib && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    #skip installing documentation
+    make install_sw && \
+    rm -rf ~/openssl_build
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L http://www.nasm.us/pub/nasm/releasebuilds/2.14.01/nasm-2.14.01.tar.bz2 && \
+    tar -xf nasm-2.14.01.tar.bz2 && cd nasm-2.14.01 && ./autogen.sh && \
+    ./configure --prefix="$HOME/ffmpeg_build" --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L http://www.tortall.net/projects/yasm/releases/yasm-1.3.0.tar.gz && \
+    tar -xf yasm-1.3.0.tar.gz && \
+    cd yasm-1.3.0 && \
+    ./configure --prefix="$HOME/ffmpeg_build" --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN cd ~/ffmpeg_sources && \
+    git clone --depth 1 https://chromium.googlesource.com/webm/libvpx.git && \
+    cd libvpx && \
+    ./configure --prefix="$HOME/ffmpeg_build" --disable-examples --disable-unit-tests --enable-vp9-highbitdepth --as=yasm --enable-pic --enable-shared && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L https://ffmpeg.org/releases/ffmpeg-snapshot.tar.bz2 && \
+    tar -xf ffmpeg-snapshot.tar.bz2 && \
+    cd ffmpeg && \
+    PATH=~/bin:$PATH && \
+    PKG_CONFIG_PATH="$HOME/ffmpeg_build/lib/pkgconfig" ./configure --prefix="$HOME/ffmpeg_build" --extra-cflags="-I$HOME/ffmpeg_build/include" --extra-ldflags="-L$HOME/ffmpeg_build/lib" --enable-openssl --enable-libvpx --enable-shared --enable-pic --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    echo "/root/ffmpeg_build/lib/" >> /etc/ld.so.conf && \
+    ldconfig && \
+    rm -rf ~/ffmpeg_sources
+
+ENV PKG_CONFIG_PATH /usr/local/lib/pkgconfig:/root/ffmpeg_build/lib/pkgconfig
+ENV LDFLAGS -L/root/ffmpeg_build/lib
+
+RUN curl -O https://raw.githubusercontent.com/torvalds/linux/v4.14/include/uapi/linux/videodev2.h && \
+    curl -O https://raw.githubusercontent.com/torvalds/linux/v4.14/include/uapi/linux/v4l2-common.h && \
+    curl -O https://raw.githubusercontent.com/torvalds/linux/v4.14/include/uapi/linux/v4l2-controls.h && \
+    curl -O https://raw.githubusercontent.com/torvalds/linux/v4.14/include/linux/compiler.h && \
+    mv videodev2.h v4l2-common.h v4l2-controls.h compiler.h /usr/include/linux
+
+#in i686, yum metadata ends up with slightly wrong timestamps
+#which inhibits its update
+#https://github.com/skvark/opencv-python/issues/148
+RUN yum clean all
+
+ENV PATH "$HOME/bin:$PATH"
diff --git a/docker/manylinux1/Dockerfile_x86_64 b/docker/manylinux1/Dockerfile_x86_64
new file mode 100644
index 00000000..c4d47bc7
--- /dev/null
+++ b/docker/manylinux1/Dockerfile_x86_64
@@ -0,0 +1,106 @@
+FROM quay.io/pypa/manylinux1_x86_64:latest
+
+RUN curl -O -L https://download.qt.io/archive/qt/4.8/4.8.7/qt-everywhere-opensource-src-4.8.7.tar.gz && \
+    tar -xf qt-everywhere-opensource-src-4.8.7.tar.gz && \
+    cd qt-everywhere* && \
+    #configure does a bootstrap make under the hood
+    #manylinux1 is too old to have `nproc`
+    export MAKEFLAGS=-j$(getconf _NPROCESSORS_ONLN) && \
+    #OpenCV only links against QtCore, QtGui, QtTest
+    ./configure -prefix /opt/Qt4.8.7 -release -opensource -confirm-license \
+    -no-sql-sqlite -no-qt3support -no-xmlpatterns -no-multimedia \
+    -no-webkit -no-script -no-declarative -no-dbus -make libs && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf qt-everywhere-opensource-src-4.8.7 && \
+    rm qt-everywhere-opensource-src-4.8.7.tar.gz
+
+ENV QTDIR /opt/Qt4.8.7
+ENV PATH "$QTDIR/bin:$PATH"
+
+RUN curl -O -L https://cmake.org/files/v3.9/cmake-3.9.0.tar.gz && \
+    tar -xf cmake-3.9.0.tar.gz && \
+    cd cmake-3.9.0 && \
+    #manylinux1 provides curl-devel equivalent and libcurl statically linked
+    # against the same newer OpenSSL as other source-built tools
+    # (1.0.2s as of this writing)
+    yum -y install zlib-devel && \
+    #configure does a bootstrap make under the hood
+    export MAKEFLAGS=-j$(getconf _NPROCESSORS_ONLN) && \
+    ./configure --system-curl && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf cmake-3.9.0*
+
+# https://trac.ffmpeg.org/wiki/CompilationGuide/Centos#GettheDependencies
+# manylinux provides the toolchain and git; we provide cmake
+RUN yum install freetype-devel bzip2-devel zlib-devel -y && \
+    mkdir ~/ffmpeg_sources
+
+# Newer openssl configure requires newer perl
+RUN curl -O -L https://www.cpan.org/src/5.0/perl-5.20.1.tar.gz && \
+    tar -xf perl-5.20.1.tar.gz && \
+    cd perl-5.20.1 && \
+    ./Configure -des -Dprefix="$HOME/openssl_build" && \
+    #perl build scripts do much redundant work
+    # if running "make install" separately
+    make install -j$(getconf _NPROCESSORS_ONLN) && \
+    cd .. && \
+    rm -rf perl-5.20.1*
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L https://github.com/openssl/openssl/archive/OpenSSL_1_1_1c.tar.gz && \
+    tar -xf OpenSSL_1_1_1c.tar.gz && \
+    cd openssl-OpenSSL_1_1_1c && \
+    PERL="$HOME/openssl_build/bin/perl" ./config --prefix="$HOME/ffmpeg_build" --openssldir="$HOME/ffmpeg_build" shared zlib && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    #skip installing documentation
+    make install_sw && \
+    rm -rf ~/openssl_build
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L http://www.nasm.us/pub/nasm/releasebuilds/2.14.01/nasm-2.14.01.tar.bz2 && \
+    tar -xf nasm-2.14.01.tar.bz2 && cd nasm-2.14.01 && ./autogen.sh && \
+    ./configure --prefix="$HOME/ffmpeg_build" --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L http://www.tortall.net/projects/yasm/releases/yasm-1.3.0.tar.gz && \
+    tar -xf yasm-1.3.0.tar.gz && \
+    cd yasm-1.3.0 && \
+    ./configure --prefix="$HOME/ffmpeg_build" --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN cd ~/ffmpeg_sources && \
+    git clone --depth 1 https://chromium.googlesource.com/webm/libvpx.git && \
+    cd libvpx && \
+    ./configure --prefix="$HOME/ffmpeg_build" --disable-examples --disable-unit-tests --enable-vp9-highbitdepth --as=yasm --enable-pic --enable-shared && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L https://ffmpeg.org/releases/ffmpeg-snapshot.tar.bz2 && \
+    tar -xf ffmpeg-snapshot.tar.bz2 && \
+    cd ffmpeg && \
+    PATH=~/bin:$PATH && \
+    PKG_CONFIG_PATH="$HOME/ffmpeg_build/lib/pkgconfig" ./configure --prefix="$HOME/ffmpeg_build" --extra-cflags="-I$HOME/ffmpeg_build/include" --extra-ldflags="-L$HOME/ffmpeg_build/lib" --enable-openssl --enable-libvpx --enable-shared --enable-pic --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    echo "/root/ffmpeg_build/lib/" >> /etc/ld.so.conf && \
+    ldconfig && \
+    rm -rf ~/ffmpeg_sources
+
+ENV PKG_CONFIG_PATH /usr/local/lib/pkgconfig:/root/ffmpeg_build/lib/pkgconfig
+ENV LDFLAGS -L/root/ffmpeg_build/lib
+
+RUN curl -O https://raw.githubusercontent.com/torvalds/linux/v4.14/include/uapi/linux/videodev2.h && \
+    curl -O https://raw.githubusercontent.com/torvalds/linux/v4.14/include/uapi/linux/v4l2-common.h && \
+    curl -O https://raw.githubusercontent.com/torvalds/linux/v4.14/include/uapi/linux/v4l2-controls.h && \
+    curl -O https://raw.githubusercontent.com/torvalds/linux/v4.14/include/linux/compiler.h && \
+    mv videodev2.h v4l2-common.h v4l2-controls.h compiler.h /usr/include/linux
+
+ENV PATH "$HOME/bin:$PATH"
diff --git a/docker/manylinux2014/Dockerfile_aarch64 b/docker/manylinux2014/Dockerfile_aarch64
new file mode 100644
index 00000000..2679cbbf
--- /dev/null
+++ b/docker/manylinux2014/Dockerfile_aarch64
@@ -0,0 +1,142 @@
+# Version: 20220628
+# Image name: quay.io/opencv-ci/opencv-python-manylinux2014-aarch64
+
+FROM quay.io/pypa/manylinux2014_aarch64:latest
+
+ARG CCACHE_VERSION=3.7.9
+ARG FFMPEG_VERSION=4.4.1
+ARG FREETYPE_VERSION=2.12.1
+ARG LIBPNG_VERSION=1.6.37
+ARG NASM_VERSION=2.15.04
+ARG OPENSSL_VERSION=1_1_1o
+ARG QT_VERSION=5.15.0
+ARG YASM_VERSION=1.3.0
+
+ENV LD_LIBRARY_PATH /usr/local/lib:$LD_LIBRARY_PATH
+
+# epel-release need for aarch64 to get openblas packages
+RUN yum install bzip2-devel curl-devel zlib-devel xcb-util-renderutil-devel xcb-util-devel xcb-util-image-devel xcb-util-keysyms-devel xcb-util-wm-devel mesa-libGL-devel libxkbcommon-devel libxkbcommon-x11-devel libXi-devel lapack-devel epel-release -y && \
+    yum install openblas-devel -y && \
+    cp /usr/include/lapacke/lapacke*.h /usr/include/ && \
+    curl https://raw.githubusercontent.com/xianyi/OpenBLAS/v0.3.3/cblas.h -o /usr/include/cblas.h && \
+    # libpng will be built from source
+    yum remove libpng -y
+
+RUN mkdir ~/libpng_sources && \
+    cd ~/libpng_sources && \
+    curl -O -L https://download.sourceforge.net/libpng/libpng-${LIBPNG_VERSION}.tar.gz && \
+    tar -xf libpng-${LIBPNG_VERSION}.tar.gz && \
+    cd libpng-${LIBPNG_VERSION} && \
+    ./configure --prefix=/usr/local && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf ~/libpng_sources
+
+RUN mkdir ~/freetype_sources && \
+    cd ~/freetype_sources && \
+    curl -O -L https://download.savannah.gnu.org/releases/freetype/freetype-${FREETYPE_VERSION}.tar.gz && \
+    tar -xf freetype-${FREETYPE_VERSION}.tar.gz && \
+    cd freetype-${FREETYPE_VERSION} && \
+    ./configure --prefix="/ffmpeg_build" --enable-freetype-config && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf ~/freetype_sources
+
+RUN curl -O -L https://download.qt.io/official_releases/qt/5.15/${QT_VERSION}/single/qt-everywhere-src-${QT_VERSION}.tar.xz && \
+    tar -xf qt-everywhere-src-${QT_VERSION}.tar.xz && \
+    cd qt-everywhere-src-${QT_VERSION} && \
+    export MAKEFLAGS=-j$(nproc) && \
+    ./configure -prefix /opt/Qt${QT_VERSION} -release -opensource -confirm-license -qtnamespace QtOpenCVPython -xcb -xcb-xlib -bundled-xcb-xinput -no-openssl -no-dbus -skip qt3d -skip qtactiveqt -skip qtcanvas3d -skip qtconnectivity -skip qtdatavis3d -skip qtdoc -skip qtgamepad -skip qtgraphicaleffects -skip qtimageformats -skip qtlocation -skip qtmultimedia -skip qtpurchasing -skip qtqa -skip qtremoteobjects -skip qtrepotools -skip qtscript -skip qtscxml -skip qtsensors -skip qtserialbus -skip qtserialport -skip qtspeech -skip qttranslations -skip qtwayland -skip qtwebchannel -skip qtwebengine -skip qtwebsockets -skip qtwebview -skip xmlpatterns -skip declarative -make libs && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf qt-everywhere*
+
+ENV QTDIR /opt/Qt${QT_VERSION}
+ENV PATH "$QTDIR/bin:$PATH"
+
+RUN mkdir ~/openssl_sources && \
+    cd ~/openssl_sources && \
+    curl -O -L https://github.com/openssl/openssl/archive/OpenSSL_${OPENSSL_VERSION}.tar.gz && \
+    tar -xf OpenSSL_${OPENSSL_VERSION}.tar.gz && \
+    cd openssl-OpenSSL_${OPENSSL_VERSION} && \
+    ./config --prefix="/ffmpeg_build" --openssldir="/ffmpeg_build" no-pinshared shared zlib && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    # skip installing documentation
+    make install_sw && \
+    cd .. && \
+    rm -rf ~/openssl_build ~/openssl_sources
+
+RUN mkdir ~/nasm_sources && \
+    cd ~/nasm_sources && \
+    curl -O -L http://www.nasm.us/pub/nasm/releasebuilds/${NASM_VERSION}/nasm-${NASM_VERSION}.tar.bz2 && \
+    tar -xf nasm-${NASM_VERSION}.tar.bz2 && cd nasm-${NASM_VERSION} && ./autogen.sh && \
+    ./configure --prefix="/ffmpeg_build" --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    cd .. && \
+    rm -rf ~/nasm_sources
+
+RUN mkdir ~/yasm_sources && \
+    cd ~/yasm_sources && \
+    curl -O -L http://www.tortall.net/projects/yasm/releases/yasm-${YASM_VERSION}.tar.gz && \
+    tar -xf yasm-${YASM_VERSION}.tar.gz && \
+    cd yasm-${YASM_VERSION} && \
+    ./configure --prefix="/ffmpeg_build" --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    cd .. && \
+    rm -rf ~/yasm_sources
+
+RUN mkdir ~/libvpx_sources && \
+    cd ~/libvpx_sources && \
+    git clone --depth 1 https://github.com/webmproject/libvpx.git && \
+    cd libvpx && \
+    ./configure --prefix="/ffmpeg_build" --disable-examples --disable-unit-tests --enable-vp9-highbitdepth --as=yasm --enable-pic --enable-shared && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    cd .. && \
+    rm -rf ~/libvpx_sources
+
+RUN mkdir ~/ffmpeg_sources && \
+    cd ~/ffmpeg_sources && \
+    curl -O -L https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.bz2 && \
+    tar -xf ffmpeg-${FFMPEG_VERSION}.tar.bz2 && \
+    cd ffmpeg-${FFMPEG_VERSION} && \
+    PATH=~/bin:$PATH && \
+    PKG_CONFIG_PATH="/ffmpeg_build/lib/pkgconfig" ./configure --prefix="/ffmpeg_build" --extra-cflags="-I/ffmpeg_build/include" --extra-ldflags="-L/ffmpeg_build/lib" --enable-openssl --enable-libvpx --enable-shared --enable-pic --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    echo "/ffmpeg_build/lib/" >> /etc/ld.so.conf && \
+    ldconfig && \
+    rm -rf ~/ffmpeg_sources && \
+    yum remove bzip2-devel -y
+
+RUN curl -O -L https://github.com/ccache/ccache/releases/download/v${CCACHE_VERSION}/ccache-${CCACHE_VERSION}.tar.gz && \
+    tar -xf ccache-${CCACHE_VERSION}.tar.gz && \
+    cd ccache-${CCACHE_VERSION} && \
+    linux32 ./configure && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    cd .. && \
+    rm -rf ccache-${CCACHE_VERSION}.tar.gz
+
+# Self-hosted runner UID is 1004
+RUN useradd ci -m -s /bin/bash -G users --uid=1004 && \
+    mkdir /io && \
+    chown -R ci:ci /io && \
+    # This needs to find ffmpeg packages from ci user
+    chown -R ci:ci /ffmpeg_build && \
+    # This calls in mutlibuild scripts and cannot be run without permissions
+    chown -R ci:ci /opt/_internal/pipx/venvs/auditwheel
+
+USER ci
+
+# Git security vulnerability: https://github.blog/2022-04-12-git-security-vulnerability-announced
+RUN git config --global --add safe.directory /io
+
+ENV PKG_CONFIG_PATH /usr/local/lib/pkgconfig:/ffmpeg_build/lib/pkgconfig
+ENV LDFLAGS -L/ffmpeg_build/lib
+ENV PATH "$HOME/bin:$PATH"
diff --git a/docker/manylinux2014/Dockerfile_i686 b/docker/manylinux2014/Dockerfile_i686
new file mode 100644
index 00000000..3b866874
--- /dev/null
+++ b/docker/manylinux2014/Dockerfile_i686
@@ -0,0 +1,99 @@
+FROM quay.io/pypa/manylinux2014_i686:latest
+
+ARG CCACHE_VERSION=3.7.9
+ARG CMAKE_VERSION=3.17.0
+ARG FFMPEG_VERSION=4.4.1
+ARG NASM_VERSION=2.15.04
+ARG OPENSSL_VERSION=1_1_1m
+ARG QT_VERSION=5.15.0
+ARG YASM_VERSION=1.3.0
+
+RUN yum install bzip2-devel curl-devel zlib-devel xcb-util-renderutil-devel xcb-util-devel xcb-util-image-devel xcb-util-keysyms-devel xcb-util-wm-devel mesa-libGL-devel libxkbcommon-devel libxkbcommon-x11-devel libXi-devel freetype-devel -y
+
+RUN curl -O -L https://download.qt.io/official_releases/qt/5.15/${QT_VERSION}/single/qt-everywhere-src-${QT_VERSION}.tar.xz && \
+    tar -xf qt-everywhere-src-${QT_VERSION}.tar.xz && \
+    cd qt-everywhere* && \
+    export MAKEFLAGS=-j$(nproc) && \
+    ./configure -prefix /opt/Qt${QT_VERSION} -release -opensource -confirm-license -qtnamespace QtOpenCVPython -xcb -xcb-xlib -bundled-xcb-xinput -no-openssl -no-dbus -skip qt3d -skip qtactiveqt -skip qtcanvas3d -skip qtconnectivity -skip qtdatavis3d -skip qtdoc -skip qtgamepad -skip qtgraphicaleffects -skip qtimageformats -skip qtlocation -skip qtmultimedia -skip qtpurchasing -skip qtqa -skip qtremoteobjects -skip qtrepotools -skip qtscript -skip qtscxml -skip qtsensors -skip qtserialbus -skip qtserialport -skip qtspeech -skip qttranslations -skip qtwayland -skip qtwebchannel -skip qtwebengine -skip qtwebsockets -skip qtwebview -skip xmlpatterns -skip declarative -make libs && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf qt-everywhere-src-${QT_VERSION} && \
+    rm qt-everywhere-src-${QT_VERSION}.tar.xz
+
+ENV QTDIR /opt/Qt${QT_VERSION}
+ENV PATH "$QTDIR/bin:$PATH"
+
+RUN mkdir ~/ffmpeg_sources && \
+    cd ~/ffmpeg_sources && \
+    curl -O -L https://github.com/openssl/openssl/archive/OpenSSL_${OPENSSL_VERSION}.tar.gz && \
+    tar -xf OpenSSL_${OPENSSL_VERSION}.tar.gz && \
+    cd openssl-OpenSSL_${OPENSSL_VERSION} && \
+    # in i686, ./config detects x64 in i686 container without linux32
+    # when run from "docker build"
+    linux32 ./config --prefix="$HOME/ffmpeg_build" no-pinshared shared zlib && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    #skip installing documentation
+    make install_sw && \
+    rm -rf ~/openssl_build
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L http://www.nasm.us/pub/nasm/releasebuilds/${NASM_VERSION}/nasm-${NASM_VERSION}.tar.bz2 && \
+    tar -xf nasm-${NASM_VERSION}.tar.bz2 && cd nasm-${NASM_VERSION} && ./autogen.sh && \
+    linux32 ./configure && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L http://www.tortall.net/projects/yasm/releases/yasm-${YASM_VERSION}.tar.gz && \
+    tar -xf yasm-${YASM_VERSION}.tar.gz && \
+    cd yasm-${YASM_VERSION} && \
+    linux32 ./configure && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN cd ~/ffmpeg_sources && \
+    git clone --depth 1 https://chromium.googlesource.com/webm/libvpx.git && \
+    cd libvpx && \
+    linux32 ./configure --prefix="$HOME/ffmpeg_build" --disable-examples --disable-unit-tests --enable-vp9-highbitdepth --as=yasm --enable-pic --enable-shared && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN cd ~/ffmpeg_sources && \
+    curl -O -L https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.bz2 && \
+    tar -xf ffmpeg-${FFMPEG_VERSION}.tar.bz2 && \
+    cd ffmpeg-${FFMPEG_VERSION} && \
+    PATH=~/bin:$PATH && \
+    PKG_CONFIG_PATH="$HOME/ffmpeg_build/lib/pkgconfig" linux32 ./configure --prefix="$HOME/ffmpeg_build" --extra-cflags="-I$HOME/ffmpeg_build/include" --extra-ldflags="-L$HOME/ffmpeg_build/lib" --enable-openssl --enable-libvpx --enable-shared --enable-pic --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    echo "/root/ffmpeg_build/lib/" >> /etc/ld.so.conf && \
+    ldconfig && \
+    rm -rf ~/ffmpeg_sources
+
+RUN curl -O -L https://github.com/ccache/ccache/releases/download/v${CCACHE_VERSION}/ccache-${CCACHE_VERSION}.tar.gz && \
+    tar -xf ccache-${CCACHE_VERSION}.tar.gz && \
+    cd ccache-${CCACHE_VERSION} && \
+    linux32 ./configure && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install
+
+RUN curl -O -L https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}.tar.gz && \
+    tar -xf cmake-${CMAKE_VERSION}.tar.gz && \
+    cd cmake-${CMAKE_VERSION} && \
+    export MAKEFLAGS=-j$(getconf _NPROCESSORS_ONLN) && \
+    ./configure --system-curl && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf cmake-${CMAKE_VERSION}*
+
+ENV PKG_CONFIG_PATH /usr/local/lib/pkgconfig:/root/ffmpeg_build/lib/pkgconfig
+ENV LDFLAGS -L/root/ffmpeg_build/lib
+
+# in i686, yum metadata ends up with slightly wrong timestamps
+# which inhibits its update
+# https://github.com/skvark/opencv-python/issues/148
+RUN yum clean all
+
+ENV PATH "$HOME/bin:$PATH"
diff --git a/docker/manylinux2014/Dockerfile_x86_64 b/docker/manylinux2014/Dockerfile_x86_64
new file mode 100644
index 00000000..8bb77341
--- /dev/null
+++ b/docker/manylinux2014/Dockerfile_x86_64
@@ -0,0 +1,142 @@
+# Version: 20220628
+# Image name: quay.io/opencv-ci/opencv-python-manylinux2014-x86-64
+
+FROM quay.io/pypa/manylinux2014_x86_64:latest
+
+ARG CCACHE_VERSION=3.7.9
+ARG FFMPEG_VERSION=4.4.1
+ARG FREETYPE_VERSION=2.12.1
+ARG LIBPNG_VERSION=1.6.37
+ARG NASM_VERSION=2.15.04
+ARG OPENSSL_VERSION=1_1_1o
+ARG QT_VERSION=5.15.0
+ARG YASM_VERSION=1.3.0
+
+ENV LD_LIBRARY_PATH /usr/local/lib:$LD_LIBRARY_PATH
+
+# epel-release need for aarch64 to get openblas packages
+RUN yum install bzip2-devel curl-devel zlib-devel xcb-util-renderutil-devel xcb-util-devel xcb-util-image-devel xcb-util-keysyms-devel xcb-util-wm-devel mesa-libGL-devel libxkbcommon-devel libxkbcommon-x11-devel libXi-devel lapack-devel epel-release -y && \
+    yum install openblas-devel -y && \
+    cp /usr/include/lapacke/lapacke*.h /usr/include/ && \
+    curl https://raw.githubusercontent.com/xianyi/OpenBLAS/v0.3.3/cblas.h -o /usr/include/cblas.h && \
+    # libpng will be built from source
+    yum remove libpng -y
+
+RUN mkdir ~/libpng_sources && \
+    cd ~/libpng_sources && \
+    curl -O -L https://download.sourceforge.net/libpng/libpng-${LIBPNG_VERSION}.tar.gz && \
+    tar -xf libpng-${LIBPNG_VERSION}.tar.gz && \
+    cd libpng-${LIBPNG_VERSION} && \
+    ./configure --prefix=/usr/local && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf ~/libpng_sources
+
+RUN mkdir ~/freetype_sources && \
+    cd ~/freetype_sources && \
+    curl -O -L https://download.savannah.gnu.org/releases/freetype/freetype-${FREETYPE_VERSION}.tar.gz && \
+    tar -xf freetype-${FREETYPE_VERSION}.tar.gz && \
+    cd freetype-${FREETYPE_VERSION} && \
+    ./configure --prefix="/ffmpeg_build" --enable-freetype-config && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf ~/freetype_sources
+
+RUN curl -O -L https://download.qt.io/official_releases/qt/5.15/${QT_VERSION}/single/qt-everywhere-src-${QT_VERSION}.tar.xz && \
+    tar -xf qt-everywhere-src-${QT_VERSION}.tar.xz && \
+    cd qt-everywhere-src-${QT_VERSION} && \
+    export MAKEFLAGS=-j$(nproc) && \
+    ./configure -prefix /opt/Qt${QT_VERSION} -release -opensource -confirm-license -qtnamespace QtOpenCVPython -xcb -xcb-xlib -bundled-xcb-xinput -no-openssl -no-dbus -skip qt3d -skip qtactiveqt -skip qtcanvas3d -skip qtconnectivity -skip qtdatavis3d -skip qtdoc -skip qtgamepad -skip qtgraphicaleffects -skip qtimageformats -skip qtlocation -skip qtmultimedia -skip qtpurchasing -skip qtqa -skip qtremoteobjects -skip qtrepotools -skip qtscript -skip qtscxml -skip qtsensors -skip qtserialbus -skip qtserialport -skip qtspeech -skip qttranslations -skip qtwayland -skip qtwebchannel -skip qtwebengine -skip qtwebsockets -skip qtwebview -skip xmlpatterns -skip declarative -make libs && \
+    make && \
+    make install && \
+    cd .. && \
+    rm -rf qt-everywhere*
+
+ENV QTDIR /opt/Qt${QT_VERSION}
+ENV PATH "$QTDIR/bin:$PATH"
+
+RUN mkdir ~/openssl_sources && \
+    cd ~/openssl_sources && \
+    curl -O -L https://github.com/openssl/openssl/archive/OpenSSL_${OPENSSL_VERSION}.tar.gz && \
+    tar -xf OpenSSL_${OPENSSL_VERSION}.tar.gz && \
+    cd openssl-OpenSSL_${OPENSSL_VERSION} && \
+    ./config --prefix="/ffmpeg_build" --openssldir="/ffmpeg_build" no-pinshared shared zlib && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    # skip installing documentation
+    make install_sw && \
+    cd .. && \
+    rm -rf ~/openssl_build ~/openssl_sources
+
+RUN mkdir ~/nasm_sources && \
+    cd ~/nasm_sources && \
+    curl -O -L http://www.nasm.us/pub/nasm/releasebuilds/${NASM_VERSION}/nasm-${NASM_VERSION}.tar.bz2 && \
+    tar -xf nasm-${NASM_VERSION}.tar.bz2 && cd nasm-${NASM_VERSION} && ./autogen.sh && \
+    ./configure --prefix="/ffmpeg_build" --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    cd .. && \
+    rm -rf ~/nasm_sources
+
+RUN mkdir ~/yasm_sources && \
+    cd ~/yasm_sources && \
+    curl -O -L http://www.tortall.net/projects/yasm/releases/yasm-${YASM_VERSION}.tar.gz && \
+    tar -xf yasm-${YASM_VERSION}.tar.gz && \
+    cd yasm-${YASM_VERSION} && \
+    ./configure --prefix="/ffmpeg_build" --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    cd .. && \
+    rm -rf ~/yasm_sources
+
+RUN mkdir ~/libvpx_sources && \
+    cd ~/libvpx_sources && \
+    git clone --depth 1 https://chromium.googlesource.com/webm/libvpx.git && \
+    cd libvpx && \
+    ./configure --prefix="/ffmpeg_build" --disable-examples --disable-unit-tests --enable-vp9-highbitdepth --as=yasm --enable-pic --enable-shared && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    cd .. && \
+    rm -rf ~/libvpx_sources
+
+RUN mkdir ~/ffmpeg_sources && \
+    cd ~/ffmpeg_sources && \
+    curl -O -L https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.bz2 && \
+    tar -xf ffmpeg-${FFMPEG_VERSION}.tar.bz2 && \
+    cd ffmpeg-${FFMPEG_VERSION} && \
+    PATH=~/bin:$PATH && \
+    PKG_CONFIG_PATH="/ffmpeg_build/lib/pkgconfig" ./configure --prefix="/ffmpeg_build" --extra-cflags="-I/ffmpeg_build/include" --extra-ldflags="-L/ffmpeg_build/lib" --enable-openssl --enable-libvpx --enable-shared --enable-pic --bindir="$HOME/bin" && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    echo "/ffmpeg_build/lib/" >> /etc/ld.so.conf && \
+    ldconfig && \
+    rm -rf ~/ffmpeg_sources && \
+    yum remove bzip2-devel -y
+
+RUN curl -O -L https://github.com/ccache/ccache/releases/download/v${CCACHE_VERSION}/ccache-${CCACHE_VERSION}.tar.gz && \
+    tar -xf ccache-${CCACHE_VERSION}.tar.gz && \
+    cd ccache-${CCACHE_VERSION} && \
+    ./configure && \
+    make -j$(getconf _NPROCESSORS_ONLN) && \
+    make install && \
+    cd .. && \
+    rm -rf ccache-${CCACHE_VERSION}.tar.gz
+
+# GitHub Actions user`s UID is 1001
+RUN useradd ci -m -s /bin/bash -G users --uid=1001 && \
+    mkdir /io && \
+    chown -R ci:ci /io && \
+    # This needs to find ffmpeg packages from ci user
+    chown -R ci:ci /ffmpeg_build && \
+    # This calls in mutlibuild scripts and cannot be run without permissions
+    chown -R ci:ci /opt/_internal/pipx/venvs/auditwheel
+
+USER ci
+
+# Git security vulnerability: https://github.blog/2022-04-12-git-security-vulnerability-announced
+RUN git config --global --add safe.directory /io
+
+ENV PKG_CONFIG_PATH /usr/local/lib/pkgconfig:/ffmpeg_build/lib/pkgconfig
+ENV LDFLAGS -L/ffmpeg_build/lib
+ENV PATH "$HOME/bin:$PATH"
diff --git a/find_version.py b/find_version.py
index 0d3faa92..6c676b23 100644
--- a/find_version.py
+++ b/find_version.py
@@ -1,43 +1,68 @@
-import sys
-import os
-import subprocess
-
-opencv_version = ""
-# dig out the version from OpenCV sources
-version_file_path = "opencv/modules/core/include/opencv2/core/version.hpp"
-
-with open(version_file_path, 'r') as f:
-    for line in f:
-        words = line.split()
-
-        if "CV_VERSION_MAJOR" in words:
-            opencv_version += words[2]
-            opencv_version += "."
-
-        if "CV_VERSION_MINOR" in words:
-            opencv_version += words[2]
-            opencv_version += "."
-
-        if "CV_VERSION_REVISION" in words:
-            opencv_version += words[2]
-            break
-
-# used in local dev releases
-git_hash = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).splitlines()[0].decode()
-
-if os.name == 'posix':
-    version = os.getenv('TRAVIS_TAG', git_hash)
-else:
-    version = os.getenv('APPVEYOR_REPO_TAG_NAME', git_hash)
-
-if version != git_hash:
-    # tag identifies the build and should be a sequential revision number
-    opencv_version += ".{}".format(version)
-else:
-    # local version identifier, not to be published on PyPI
-    opencv_version += "+{}".format(version)
-
-print("Version: ", opencv_version)
-
-with open('cv_version.py', 'w') as f:
-    f.write('opencv_version = "{}"'.format(opencv_version))
+import sys
+import os
+import subprocess
+
+if __name__ == "__main__":
+    contrib = sys.argv[1]
+    headless = sys.argv[2]
+    ci_build = sys.argv[3]
+
+    opencv_version = ""
+    # dig out the version from OpenCV sources
+    version_file_path = "opencv/modules/core/include/opencv2/core/version.hpp"
+
+    with open(version_file_path, "r") as f:
+        for line in f:
+            words = line.split()
+
+            if "CV_VERSION_MAJOR" in words:
+                opencv_version += words[2]
+                opencv_version += "."
+
+            if "CV_VERSION_MINOR" in words:
+                opencv_version += words[2]
+                opencv_version += "."
+
+            if "CV_VERSION_REVISION" in words:
+                opencv_version += words[2]
+                break
+
+    # used in local dev releases
+    git_hash = (
+        subprocess.check_output(["git", "rev-parse", "--short", "HEAD"])
+        .splitlines()[0]
+        .decode()
+    )
+    # this outputs the annotated tag if we are exactly on a tag, otherwise <tag>-<n>-g<shortened sha-1>
+    try:
+        tag = (
+            subprocess.check_output(
+                ["git", "describe", "--tags"], stderr=subprocess.STDOUT
+            )
+            .splitlines()[0]
+            .decode()
+            .split("-")
+        )
+    except subprocess.CalledProcessError as e:
+        # no tags reachable (e.g. on a topic branch in a fork), see
+        # https://stackoverflow.com/questions/4916492/git-describe-fails-with-fatal-no-names-found-cannot-describe-anything
+        if e.output.rstrip() == b"fatal: No names found, cannot describe anything.":
+            tag = []
+        else:
+            print(e.output)
+            raise
+
+    if len(tag) == 1:
+        # tag identifies the build and should be a sequential revision number
+        version = tag[0]
+        opencv_version += ".{}".format(version)
+    else:
+        # local version identifier, not to be published on PyPI
+        version = git_hash
+        opencv_version += "+{}".format(version)
+
+    with open("cv2/version.py", "w") as f:
+        f.write('opencv_version = "{}"\n'.format(opencv_version))
+        f.write("contrib = {}\n".format(contrib))
+        f.write("headless = {}\n".format(headless))
+        f.write("ci_build = {}".format(ci_build))
diff --git a/multibuild b/multibuild
index 9330c3dc..bce1637e 160000
--- a/multibuild
+++ b/multibuild
@@ -1 +1 @@
-Subproject commit 9330c3dcc318b7b2b734ab00485d2ab253761811
+Subproject commit bce1637e202cb52b0e7ea42baa1cccc894b82806
diff --git a/opencv b/opencv
index 6d4f6647..b0dc4741 160000
--- a/opencv
+++ b/opencv
@@ -1 +1 @@
-Subproject commit 6d4f66472e14b29b8e1623859cfebfdc67f677c3
+Subproject commit b0dc474160e389b9c9045da5db49d03ae17c6a6b
diff --git a/opencv_contrib b/opencv_contrib
index 81ca8dab..db16caf6 160000
--- a/opencv_contrib
+++ b/opencv_contrib
@@ -1 +1 @@
-Subproject commit 81ca8dab8697ae6acc5d8bc45f03b6b10f4d7d24
+Subproject commit db16caf6ceee76b43b94c846be276e92a43e9700
diff --git a/opencv_extra b/opencv_extra
new file mode 160000
index 00000000..936854e2
--- /dev/null
+++ b/opencv_extra
@@ -0,0 +1 @@
+Subproject commit 936854e2b666853d6d0732a8eabc2d699f4fa3d8
diff --git a/patch_auditwheel_whitelist.py b/patch_auditwheel_whitelist.py
new file mode 100644
index 00000000..b32da17a
--- /dev/null
+++ b/patch_auditwheel_whitelist.py
@@ -0,0 +1,15 @@
+from os.path import join, dirname, abspath
+import json
+
+from auditwheel import policy
+
+policies = None
+
+with open(join(dirname(abspath(policy.__file__)), "manylinux-policy.json")) as f:
+    policies = json.load(f)
+
+for p in policies:
+    p["lib_whitelist"].append("libxcb.so.1")
+
+with open(join(dirname(abspath(policy.__file__)), "manylinux-policy.json"), "w") as f:
+    f.write(json.dumps(policies))
diff --git a/patches/patchOpenEXR b/patches/patchOpenEXR
new file mode 100644
index 00000000..e2a1ffc7
--- /dev/null
+++ b/patches/patchOpenEXR
@@ -0,0 +1,60 @@
+diff -ruN opencv/3rdparty/openexr/IlmImf/ImfSystemSpecific.cpp opencv_patched/3rdparty/openexr/IlmImf/ImfSystemSpecific.cpp
+--- opencv/3rdparty/openexr/IlmImf/ImfSystemSpecific.cpp	2019-08-25 10:40:57.596395000 -0400
++++ opencv_patched/3rdparty/openexr/IlmImf/ImfSystemSpecific.cpp	2019-08-25 10:53:15.331689900 -0400
+@@ -40,21 +40,19 @@
+ 
+ namespace {
+ #if defined(IMF_HAVE_SSE2) && defined(__GNUC__) && !defined(__ANDROID__)
+-
++#include <cpuid.h>
+     // Helper functions for gcc + SSE enabled
+-    void cpuid(int n, int &eax, int &ebx, int &ecx, int &edx)
++    void cpuid(unsigned int n, unsigned int &eax, unsigned int &ebx,
++					unsigned int &ecx, unsigned int &edx)
+     {
+-        __asm__ __volatile__ (
+-            "cpuid"
+-            : /* Output  */ "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) 
+-            : /* Input   */ "a"(n)
+-            : /* Clobber */);
++        __get_cpuid(n, &eax, &ebx, &ecx, &edx);
+     }
+ 
+ #else // IMF_HAVE_SSE2 && __GNUC__
+ 
+     // Helper functions for generic compiler - all disabled
+-    void cpuid(int n, int &eax, int &ebx, int &ecx, int &edx)
++    void cpuid(unsigned int n, unsigned int &eax, unsigned int &ebx,
++					unsigned int &ecx, unsigned int &edx)
+     {
+         eax = ebx = ecx = edx = 0;
+     }
+@@ -64,7 +62,7 @@
+ 
+ #ifdef OPENEXR_IMF_HAVE_GCC_INLINE_ASM_AVX
+ 
+-    void xgetbv(int n, int &eax, int &edx)
++    void xgetbv(unsigned int n, unsigned int &eax, unsigned int &edx)
+     {
+         __asm__ __volatile__ (
+             "xgetbv"
+@@ -75,7 +73,7 @@
+ 
+ #else //  OPENEXR_IMF_HAVE_GCC_INLINE_ASM_AVX
+ 
+-    void xgetbv(int n, int &eax, int &edx)
++    void xgetbv(unsigned int n, unsigned int &eax, unsigned int &edx)
+     {
+         eax = edx = 0;
+     }
+@@ -94,8 +92,8 @@
+     f16c(false)
+ {
+     bool osxsave = false;
+-    int  max     = 0;
+-    int  eax, ebx, ecx, edx;
++    unsigned int  max     = 0;
++    unsigned int  eax, ebx, ecx, edx;
+ 
+     cpuid(0, max, ebx, ecx, edx);
+     if (max > 0)
diff --git a/patches/patchQtPlugins b/patches/patchQtPlugins
new file mode 100644
index 00000000..a05a5f83
--- /dev/null
+++ b/patches/patchQtPlugins
@@ -0,0 +1,25 @@
+diff --git a/opencv/CMakeLists.txt b/opencv/CMakeLists.txt
+index 4c0b3880fc..dffa0a4caa 100644
+--- a/opencv/CMakeLists.txt
++++ b/opencv/CMakeLists.txt
+@@ -1187,6 +1187,13 @@ if(WITH_QT OR HAVE_QT)
+   if(HAVE_QT)
+     status("    QT:" "YES (ver ${QT_VERSION_MAJOR}.${QT_VERSION_MINOR}.${QT_VERSION_PATCH} ${QT_EDITION})")
++    if(APPLE)
++      install(DIRECTORY ${Qt5_DIR}/../../../plugins DESTINATION lib/qt)
++    endif()
++    if(UNIX AND NOT APPLE)
++      install(DIRECTORY /opt/Qt5.15.0/plugins DESTINATION lib/qt)
++      install(DIRECTORY /usr/share/fonts DESTINATION lib/qt)
++    endif()
+     if(HAVE_QT_OPENGL)
+       if(Qt${QT_VERSION_MAJOR}OpenGL_LIBRARIES)
+         status("      QT OpenGL support:" HAVE_QT_OPENGL THEN "YES (${Qt${QT_VERSION_MAJOR}OpenGL_LIBRARIES} ${Qt${QT_VERSION_MAJOR}OpenGL_VERSION_STRING})" ELSE NO)
+       else()
+         status("      QT OpenGL support:" HAVE_QT_OPENGL THEN "YES (${QT_QTOPENGL_LIBRARY})" ELSE NO)
+       endif()
+     else()
+       status("      QT OpenGL support:" "NO")
+     endif()
+   else()
+     status("    QT:" "NO")
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 00000000..ff535e86
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,12 @@
+[build-system]
+requires = [
+  "setuptools==59.2.0", "wheel==0.37.0", "cmake>=3.1", "pip",
+  "scikit-build>=0.13.2",
+  "numpy==1.13.3; python_version=='3.6' and platform_machine != 'aarch64' and platform_machine != 'arm64'",
+  "numpy==1.14.5; python_version=='3.7' and platform_machine != 'aarch64' and platform_machine != 'arm64'",
+  "numpy==1.17.3; python_version=='3.8' and platform_machine != 'aarch64' and platform_machine != 'arm64'",
+  "numpy==1.19.3; python_version<='3.9' and sys_platform == 'linux' and platform_machine == 'aarch64'",
+  "numpy==1.21.0; python_version<='3.9' and sys_platform == 'darwin' and platform_machine == 'arm64'",
+  "numpy==1.19.3; python_version=='3.9' and platform_machine != 'aarch64' and platform_machine != 'arm64'",
+  "numpy==1.21.2; python_version>='3.10'"
+]
diff --git a/scripts/__init__.py b/scripts/__init__.py
new file mode 100644
index 00000000..587a42bf
--- /dev/null
+++ b/scripts/__init__.py
@@ -0,0 +1,24 @@
+PYTHON_EXTENSIONS_PATHS = [
+    LOADER_DIR
+] + PYTHON_EXTENSIONS_PATHS
+
+ci_and_not_headless = False
+
+try:
+    from .version import ci_build, headless
+
+    ci_and_not_headless = ci_build and not headless
+except:
+    pass
+
+# the Qt plugin is included currently only in the pre-built wheels
+if sys.platform.startswith("linux") and ci_and_not_headless:
+    os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = os.path.join(
+        os.path.dirname(os.path.abspath(__file__)), "qt", "plugins"
+    )
+
+# Qt will throw warning on Linux if fonts are not found
+if sys.platform.startswith("linux") and ci_and_not_headless:
+    os.environ["QT_QPA_FONTDIR"] = os.path.join(
+        os.path.dirname(os.path.abspath(__file__)), "qt", "fonts"
+    )
diff --git a/scripts/build.sh b/scripts/build.sh
new file mode 100755
index 00000000..f48ca066
--- /dev/null
+++ b/scripts/build.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+set -e
+# Check out and prepare the source
+# Multibuild doesn't have releases, so --depth would break eventually (see
+# https://superuser.com/questions/1240216/server-does-not-allow-request-for-unadvertised)
+git submodule update --init multibuild
+source multibuild/common_utils.sh
+# https://github.com/matthew-brett/multibuild/issues/116
+if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then export ARCH_FLAGS=" "; fi
+source multibuild/travis_steps.sh
+# This sets -x
+# source travis_multibuild_customize.sh
+echo $ENABLE_CONTRIB > contrib.enabled
+echo $ENABLE_HEADLESS > headless.enabled
+set -x
+build_wheel $REPO_DIR $PLAT
diff --git a/scripts/install.sh b/scripts/install.sh
new file mode 100755
index 00000000..6e019d1c
--- /dev/null
+++ b/scripts/install.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+
+set -e
+# Check out and prepare the source
+# Multibuild doesn't have releases, so --depth would break eventually (see
+# https://superuser.com/questions/1240216/server-does-not-allow-request-for-unadvertised)
+git submodule update --init --recursive
+source multibuild/common_utils.sh
+# https://github.com/matthew-brett/multibuild/issues/116
+if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then export ARCH_FLAGS=" "; fi
+source multibuild/travis_steps.sh
+# This sets -x
+# source travis_multibuild_customize.sh
+echo $ENABLE_CONTRIB > contrib.enabled
+echo $ENABLE_HEADLESS > headless.enabled
+set -x
+install_run $PLAT
+set +x
diff --git a/setup.py b/setup.py
index 039136d7..11014d6b 100644
--- a/setup.py
+++ b/setup.py
@@ -1,349 +1,494 @@
-# No 3rd-party modules here, see "3rd-party" note below
-import io, os, os.path, sys, runpy, subprocess, re, sysconfig
-
-
-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_contrib()
-
-
-    # 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
-    numpy_version = get_or_install("numpy", "1.11.3" if sys.version_info[:2] >= (3, 6) else "1.11.1")
-    get_or_install("scikit-build")
-    import skbuild
-    
-    if os.path.exists('.git'):
-        import pip.vcs.git
-        g = pip.vcs.git.Git()
-        use_depth = g.get_git_version() >= type(g.get_git_version())("1.8.4")
-        g.run_command(["submodule", "update", "--init", "--recursive"] + \
-            (["--depth=1"] if use_depth else []) + \
-            [cmake_source_dir])
-        if build_contrib:
-            g.run_command(["submodule", "update", "--init", "--recursive"] + \
-            (["--depth=1"] if use_depth else []) + \
-            ["opencv_contrib"])
-        del use_depth, g, pip
-
-
-    # https://stackoverflow.com/questions/1405913/python-32bit-or-64bit-mode
-    x64 = sys.maxsize>2**32
-
-
-    package_name = "opencv-contrib-python" if build_contrib else "opencv-python"
-    long_description = io.open('README_CONTRIB.rst' if build_contrib else 'README.rst', encoding="utf-8").read()
-    package_version = get_opencv_version()
-
-    packages = ['cv2', 'cv2.data']
-    package_data = \
-        {'cv2':
-            ['*%s' % sysconfig.get_config_var('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_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/([^/]+/){1,2}cv2[^/]*%(ext)s' % {
-                'ext':   re.escape(sysconfig.get_config_var('SO'))
-                }
-            ],
-         'cv2.data':
-            [ # OPENCV_OTHER_INSTALL_PATH
-            ('etc' if os.name =='nt' else 'share/OpenCV')
-            + 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%d_EXECUTABLE=%s" % (sys.version_info[0], sys.executable),
-        "-DBUILD_opencv_python%d=ON" % sys.version_info[0],
-        # 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"
-    ] + \
-    ([ "-DOPENCV_EXTRA_MODULES_PATH=" + os.path.abspath("opencv_contrib/modules") ]
-       if build_contrib else [])
-       
-    # OS-specific components
-    if sys.platform == 'darwin' or sys.platform.startswith('linux'):
-        cmake_args.append( "-DWITH_QT=4" )
-    if sys.platform.startswith('linux'):
-        cmake_args.append( "-DWITH_V4L=ON" )
-        if all(v in os.environ for v in ('JPEG_INCLUDE_DIR', 'JPEG_LIBRARY')):
-            cmake_args += [
-            "-DBUILD_JPEG=OFF",
-            "-DJPEG_INCLUDE_DIR=%s" % os.environ['JPEG_INCLUDE_DIR'],
-            "-DJPEG_LIBRARY=%s" % os.environ['JPEG_LIBRARY']
-            ]
-            
-    # Turn off broken components
-    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
-    if sys.platform.startswith('linux'):
-        cmake_args.append( "-DWITH_IPP=OFF" )   # https://github.com/opencv/opencv/issues/10411
-
-
-
-    # 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,
-        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 :: 2',
-          'Programming Language :: Python :: 2.7',
-          'Programming Language :: Python :: 3',
-          'Programming Language :: Python :: 3.4',
-          'Programming Language :: Python :: 3.5',
-          'Programming Language :: Python :: 3.6',
-          '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,
-          )
-
-
-class RearrangeCMakeOutput(object):
-    """Patch SKBuild logic to only take files related to the Python package
-    and construct a file hierarchy that SKBuild expects (see below)"""
-    _setuptools_wrap = None
-
-    # Have to wrap a function reference, or it's converted
-    # into an instance method on attr assignment
-    import argparse
-    wraps = argparse.Namespace(
-        _classify_files=None)
-    del argparse
-
-    package_paths_re = None
-    packages = None
-    files_outside_package = None
-
-    def __init__(self, package_paths_re, files_outside_package, packages):
-        cls = self.__class__
-        assert not cls.wraps._classify_files, "Singleton object"
-        import skbuild.setuptools_wrap
-
-        cls._setuptools_wrap = skbuild.setuptools_wrap
-        cls.wraps._classify_files = cls._setuptools_wrap._classify_files
-        cls._setuptools_wrap._classify_files = self._classify_files_override
-
-        cls.package_paths_re = package_paths_re
-        cls.files_outside_package = files_outside_package
-        cls.packages = packages
-    def __del__(self):
-        cls = self.__class__
-        cls._setuptools_wrap._classify_files = cls.wraps._classify_files
-        cls.wraps._classify_files = None
-        cls._setuptools_wrap = None
-
-    def _classify_files_override(self, install_paths,
-            package_data, package_prefixes,
-            py_modules, new_py_modules,
-            scripts, new_scripts,
-            data_files,
-            cmake_source_dir, cmake_install_reldir):
-        """From all CMake output, we're only interested in a few files
-        and must place them into CMake install dir according
-        to Python conventions for SKBuild to find them:
-            package\
-                file
-                subpackage\
-                    etc.
-        """
-        cls = self.__class__
-        # 'relpath'/'reldir' = relative to CMAKE_INSTALL_DIR/cmake_install_dir
-        # 'path'/'dir' = relative to sourcetree root
-        cmake_install_dir = os.path.join(cls._setuptools_wrap.CMAKE_INSTALL_DIR,
-                                         cmake_install_reldir)
-        install_relpaths = [os.path.relpath(p, cmake_install_dir) for p in install_paths]
-        fslash_install_relpaths = [p.replace(os.path.sep, '/') for p in install_relpaths]
-        relpaths_zip = list(zip(fslash_install_relpaths, install_relpaths))
-        del install_relpaths, fslash_install_relpaths
-
-        final_install_relpaths = []
-
-        print("Copying files from CMake output")
-        for package_name, relpaths_re in cls.package_paths_re.items():
-            package_dest_reldir = package_name.replace('.', os.path.sep)
-            for relpath_re in relpaths_re:
-                found = False
-                r = re.compile(relpath_re+'$')
-                for fslash_relpath, relpath in relpaths_zip:
-                    m = r.match(fslash_relpath)
-                    if not m: continue
-                    found = True
-                    new_install_relpath = os.path.join(
-                        package_dest_reldir,
-                        os.path.basename(relpath))
-                    cls._setuptools_wrap._copy_file(
-                        os.path.join(cmake_install_dir, relpath),
-                        os.path.join(cmake_install_dir, new_install_relpath),
-                        hide_listing=False)
-                    final_install_relpaths.append(new_install_relpath)
-                    del m, fslash_relpath, new_install_relpath
-                else:
-                    if not found: raise Exception("Not found: '%s'" % relpath_re)
-                del r, found
-
-        del relpaths_zip
-
-        print("Copying files from non-default sourcetree locations")
-        for package_name, paths in cls.files_outside_package.items():
-            package_dest_reldir = package_name.replace('.', os.path.sep)
-            for path in paths:
-                new_install_relpath = os.path.join(
-                        package_dest_reldir,
-                        # Don't yet have a need to copy
-                        # to subdirectories of package dir
-                        os.path.basename(path))
-                cls._setuptools_wrap._copy_file(
-                    path, os.path.join(cmake_install_dir, new_install_relpath),
-                    hide_listing = False
-                )
-                final_install_relpaths.append(new_install_relpath)
-
-
-        final_install_paths = [os.path.join(cmake_install_dir, p) for p in final_install_relpaths]
-
-        return (cls.wraps._classify_files)(
-            final_install_paths,
-            package_data, package_prefixes,
-            py_modules, new_py_modules,
-            scripts, new_scripts,
-            data_files,
-            # To get around a demented check
-            # that prepends source dir to paths and breaks package detection code.
-            # Can't imagine what the authors were thinking that should be doing.
-            cmake_source_dir = '',
-            cmake_install_dir = cmake_install_reldir
-            )
-
-
-def install_packages(*requirements):
-    # No more convenient way until PEP 518 is implemented; setuptools only handles eggs
-    subprocess.check_call([sys.executable,
-                           "-m", "pip", "install"]
-                          + list(requirements))
-
-
-def get_opencv_version():
-    # cv_version.py should be generated by running find_version.py
-    runpy.run_path("find_version.py")
-    from cv_version import opencv_version
-    return opencv_version
-
-
-def get_build_contrib():
-    build_contrib = False
-    try:
-        build_contrib = bool(int(os.getenv('ENABLE_CONTRIB', None)))
-    except Exception:
-        pass
-
-    if not build_contrib:
-        try:
-            build_contrib = bool(int(open("contrib.enabled").read(1)))
-        except Exception:
-            pass
-    return build_contrib
-
-
-def get_or_install(name, version = None):
-    """If a package is already installed, build against it. If not, install"""
-    # Do not import 3rd-party modules into the current process
-    import json
-    js_packages = json.loads(
-        subprocess.check_output(
-        [sys.executable, "-m", "pip", "list", "--format=json"])
-        .decode('ascii'))  #valid names & versions are ASCII as per PEP 440
-    try:
-        [package] = (package for package in js_packages
-                     if package['name'] == name)
-    except ValueError:
-        install_packages("%s==%s"%(name, version) if version else name)
-        return version
-    else:
-        return package['version']
-
-
-# This creates a list which is empty but returns a length of 1.
-# Should make the wheel a binary distribution and platlib compliant.
-class EmptyListWithLength(list):
-    def __len__(self):
-        return 1
-
-
-if __name__ == '__main__':
-    main()
+import io
+import os
+import os.path
+import sys
+import runpy
+import subprocess
+import re
+import sysconfig
+import platform
+import skbuild
+from skbuild import cmaker
+
+
+def main():
+    os.chdir(os.path.dirname(os.path.abspath(__file__)))
+
+    CI_BUILD = os.environ.get("CI_BUILD", "False")
+    is_CI_build = True if CI_BUILD == "1" else False
+    cmake_source_dir = "opencv"
+    minimum_supported_numpy = "1.13.3"
+    build_contrib = get_build_env_var_by_name("contrib")
+    build_headless = get_build_env_var_by_name("headless")
+    build_java = "ON" if get_build_env_var_by_name("java") else "OFF"
+
+    install_requires = [
+        'numpy>=1.13.3; python_version<"3.7"',
+        'numpy>=1.14.5; python_version>="3.7"',
+        'numpy>=1.17.3; python_version>="3.8"',
+        'numpy>=1.19.3; python_version>="3.9"',
+        'numpy>=1.21.2; python_version>="3.10"',
+        'numpy>=1.19.3; python_version>="3.6" and platform_system=="Linux" and platform_machine=="aarch64"',
+        'numpy>=1.21.2; python_version>="3.6" and platform_system=="Darwin" and platform_machine=="arm64"',
+    ]
+
+    python_version = cmaker.CMaker.get_python_version()
+    python_lib_path = cmaker.CMaker.get_python_library(python_version).replace(
+        "\\", "/"
+    )
+    python_include_dir = cmaker.CMaker.get_python_include_dir(python_version).replace(
+        "\\", "/"
+    )
+
+    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"]
+            )
+
+    package_version, build_contrib, build_headless = get_and_set_info(
+        build_contrib, build_headless, is_CI_build
+    )
+
+    # https://stackoverflow.com/questions/1405913/python-32bit-or-64bit-mode
+    is64 = 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()
+
+    packages = ["cv2", "cv2.data"]
+
+    package_data = {
+        "cv2": ["*%s" % sysconfig.get_config_vars().get("SO"), "version.py"]
+        + (["*.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 is64 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.
+        [
+            r"python/cv2/python-%s/cv2.*"
+            % (sys.version_info[0])
+        ]
+        +
+        [
+            r"python/cv2/__init__.py"
+        ]
+        +
+        [
+            r"python/cv2/.*config.*.py"
+        ],
+        "cv2.data": [  # OPENCV_OTHER_INSTALL_PATH
+            ("etc" if os.name == "nt" else "share/opencv4") + r"/haarcascades/.*\.xml"
+        ],
+        "cv2.gapi": [
+            "python/cv2" + r"/gapi/.*\.py"
+        ],
+        "cv2.mat_wrapper": [
+            "python/cv2" + r"/mat_wrapper/.*\.py"
+        ],
+        "cv2.misc": [
+            "python/cv2" + r"/misc/.*\.py"
+        ],
+        "cv2.utils": [
+            "python/cv2" + r"/utils/.*\.py"
+        ],
+    }
+
+    # 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"]}
+
+    ci_cmake_generator = (
+        ["-G", "Visual Studio 14" + (" Win64" if is64 else "")]
+        if os.name == "nt"
+        else ["-G", "Unix Makefiles"]
+    )
+
+    cmake_args = (
+        (ci_cmake_generator if is_CI_build else [])
+        + [
+            # skbuild inserts PYTHON_* vars. That doesn't satisfy opencv build scripts in case of Py3
+            "-DPYTHON3_EXECUTABLE=%s" % sys.executable,
+            "-DPYTHON3_INCLUDE_DIR=%s" % python_include_dir,
+            "-DPYTHON3_LIBRARY=%s" % python_lib_path,
+            "-DBUILD_opencv_python3=ON",
+            "-DBUILD_opencv_python2=OFF",
+            # Disable the Java build by default as it is not needed
+            "-DBUILD_opencv_java=%s" % build_java,
+            # 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_opencv_freetype=OFF",
+            "-DBUILD_SHARED_LIBS=OFF",
+            "-DBUILD_TESTS=OFF",
+            "-DBUILD_PERF_TESTS=OFF",
+            "-DBUILD_DOCS=OFF",
+            "-DPYTHON3_LIMITED_API=ON",
+            "-DBUILD_OPENEXR=ON",
+        ]
+        + (
+            # CMake flags for windows/arm64 build
+            ["-DCMAKE_GENERATOR_PLATFORM=ARM64",
+             # Emulated cmake requires following flags to correctly detect
+             # target architecture for windows/arm64 build
+             "-DOPENCV_WORKAROUND_CMAKE_20989=ON",
+             "-DCMAKE_SYSTEM_PROCESSOR=ARM64"]
+            if platform.machine() == "ARM64" and sys.platform == "win32"
+            # If it is not defined 'linker flags: /machine:X86' on Windows x64
+            else ["-DCMAKE_GENERATOR_PLATFORM=x64"] if is64 and sys.platform == "win32"
+            else []
+          )
+        + (
+            ["-DOPENCV_EXTRA_MODULES_PATH=" + os.path.abspath("opencv_contrib/modules")]
+            if build_contrib
+            else []
+        )
+    )
+
+    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")
+        cmake_args.append("-DWITH_GTK=OFF")
+        if is_CI_build:
+            cmake_args.append(
+                "-DWITH_MSMF=OFF"
+            )  # see: https://github.com/skvark/opencv-python/issues/263
+
+    if sys.platform.startswith("linux") and not is64 and "bdist_wheel" in sys.argv:
+        subprocess.check_call("patch -p0 < patches/patchOpenEXR", shell=True)
+
+    # OS-specific components during CI builds
+    if is_CI_build:
+
+        if (
+            not build_headless
+            and "bdist_wheel" in sys.argv
+            and sys.platform.startswith("linux")
+        ):
+            cmake_args.append("-DWITH_QT=5")
+            subprocess.check_call("patch -p1 < patches/patchQtPlugins", shell=True)
+
+            if sys.platform.startswith("linux"):
+                rearrange_cmake_output_data["cv2.qt.plugins.platforms"] = [
+                    (r"lib/qt/plugins/platforms/libqxcb\.so")
+                ]
+
+                # add fonts for Qt5
+                fonts = []
+                for file in os.listdir("/usr/share/fonts/dejavu"):
+                    if file.endswith(".ttf"):
+                        fonts.append(
+                            (r"lib/qt/fonts/dejavu/%s\.ttf" % file.split(".")[0])
+                        )
+
+                rearrange_cmake_output_data["cv2.qt.fonts"] = fonts
+
+            if sys.platform == "darwin":
+                rearrange_cmake_output_data["cv2.qt.plugins.platforms"] = [
+                    (r"lib/qt/plugins/platforms/libqcocoa\.dylib")
+                ]
+
+        if sys.platform.startswith("linux"):
+            cmake_args.append("-DWITH_V4L=ON")
+            cmake_args.append("-DWITH_LAPACK=ON")
+            cmake_args.append("-DENABLE_PRECOMPILED_HEADERS=OFF")
+
+    # https://github.com/scikit-build/scikit-build/issues/479
+    if "CMAKE_ARGS" in os.environ:
+        import shlex
+
+        cmake_args.extend(shlex.split(os.environ["CMAKE_ARGS"]))
+        del shlex
+
+    # 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",
+        ext_modules=EmptyListWithLength(),
+        install_requires=install_requires,
+        python_requires=">=3.6",
+        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 :: Only",
+            "Programming Language :: Python :: 3.6",
+            "Programming Language :: Python :: 3.7",
+            "Programming Language :: Python :: 3.8",
+            "Programming Language :: Python :: 3.9",
+            "Programming Language :: Python :: 3.10",
+            "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,
+    )
+
+
+class RearrangeCMakeOutput(object):
+    """
+        Patch SKBuild logic to only take files related to the Python package
+        and construct a file hierarchy that SKBuild expects (see below)
+    """
+
+    _setuptools_wrap = None
+
+    # Have to wrap a function reference, or it's converted
+    # into an instance method on attr assignment
+    import argparse
+
+    wraps = argparse.Namespace(_classify_installed_files=None)
+    del argparse
+
+    package_paths_re = None
+    packages = None
+    files_outside_package = None
+
+    def __init__(self, package_paths_re, files_outside_package, packages):
+        cls = self.__class__
+        assert not cls.wraps._classify_installed_files, "Singleton object"
+        import skbuild.setuptools_wrap
+
+        cls._setuptools_wrap = skbuild.setuptools_wrap
+        cls.wraps._classify_installed_files = (
+            cls._setuptools_wrap._classify_installed_files
+        )
+        cls._setuptools_wrap._classify_installed_files = (
+            self._classify_installed_files_override
+        )
+
+        cls.package_paths_re = package_paths_re
+        cls.files_outside_package = files_outside_package
+        cls.packages = packages
+
+    def __del__(self):
+        cls = self.__class__
+        cls._setuptools_wrap._classify_installed_files = (
+            cls.wraps._classify_installed_files
+        )
+        cls.wraps._classify_installed_files = None
+        cls._setuptools_wrap = None
+
+    def _classify_installed_files_override(
+        self,
+        install_paths,
+        package_data,
+        package_prefixes,
+        py_modules,
+        new_py_modules,
+        scripts,
+        new_scripts,
+        data_files,
+        cmake_source_dir,
+        cmake_install_reldir,
+    ):
+        """
+            From all CMake output, we're only interested in a few files
+            and must place them into CMake install dir according
+            to Python conventions for SKBuild to find them:
+                package\
+                    file
+                    subpackage\
+                        etc.
+        """
+
+        cls = self.__class__
+
+        # 'relpath'/'reldir' = relative to CMAKE_INSTALL_DIR/cmake_install_dir
+        # 'path'/'dir' = relative to sourcetree root
+        cmake_install_dir = os.path.join(
+            cls._setuptools_wrap.CMAKE_INSTALL_DIR(), cmake_install_reldir
+        )
+        install_relpaths = [
+            os.path.relpath(p, cmake_install_dir) for p in install_paths
+        ]
+        fslash_install_relpaths = [
+            p.replace(os.path.sep, "/") for p in install_relpaths
+        ]
+        relpaths_zip = list(zip(fslash_install_relpaths, install_relpaths))
+        del install_relpaths, fslash_install_relpaths
+
+        final_install_relpaths = []
+
+        print("Copying files from CMake output")
+
+        # add lines from the old __init__.py file to the config file
+        with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'scripts', '__init__.py'), 'r') as custom_init:
+            custom_init_data = custom_init.read()
+        with open('%spython/cv2/config-%s.py'
+        % (cmake_install_dir, sys.version_info[0]), 'w') as opencv_init_config:
+            opencv_init_config.write(custom_init_data)
+
+        for package_name, relpaths_re in cls.package_paths_re.items():
+            package_dest_reldir = package_name.replace(".", os.path.sep)
+            for relpath_re in relpaths_re:
+                found = False
+                r = re.compile(relpath_re + "$")
+                for fslash_relpath, relpath in relpaths_zip:
+                    m = r.match(fslash_relpath)
+                    if not m:
+                        continue
+                    found = True
+                    new_install_relpath = os.path.join(
+                        package_dest_reldir, os.path.basename(relpath)
+                    )
+                    cls._setuptools_wrap._copy_file(
+                        os.path.join(cmake_install_dir, relpath),
+                        os.path.join(cmake_install_dir, new_install_relpath),
+                        hide_listing=False,
+                    )
+                    final_install_relpaths.append(new_install_relpath)
+                    del m, fslash_relpath, new_install_relpath
+                else:
+                    # gapi can be missed if ADE was not downloaded (network issue)
+                    if not found and "gapi" not in relpath_re:
+                        raise Exception("Not found: '%s'" % relpath_re)
+                del r, found
+
+        del relpaths_zip
+
+        print("Copying files from non-default sourcetree locations")
+
+        for package_name, paths in cls.files_outside_package.items():
+            package_dest_reldir = package_name.replace(".", os.path.sep)
+            for path in paths:
+                new_install_relpath = os.path.join(
+                    package_dest_reldir,
+                    # Don't yet have a need to copy
+                    # to subdirectories of package dir
+                    os.path.basename(path),
+                )
+                cls._setuptools_wrap._copy_file(
+                    path,
+                    os.path.join(cmake_install_dir, new_install_relpath),
+                    hide_listing=False,
+                )
+                final_install_relpaths.append(new_install_relpath)
+
+        final_install_paths = [
+            os.path.join(cmake_install_dir, p) for p in final_install_relpaths
+        ]
+
+        return (cls.wraps._classify_installed_files)(
+            final_install_paths,
+            package_data,
+            package_prefixes,
+            py_modules,
+            new_py_modules,
+            scripts,
+            new_scripts,
+            data_files,
+            # To get around a check that prepends source dir to paths and breaks package detection code.
+            cmake_source_dir="",
+            _cmake_install_dir=cmake_install_reldir,
+        )
+
+
+def get_and_set_info(contrib, headless, ci_build):
+    # cv2/version.py should be generated by running find_version.py
+    version = {}
+    here = os.path.abspath(os.path.dirname(__file__))
+    version_file = os.path.join(here, "cv2", "version.py")
+
+    # generate a fresh version.py always when Git repository exists
+    # (in sdists the version.py file already exists)
+    if os.path.exists(".git"):
+        old_args = sys.argv.copy()
+        sys.argv = ["", str(contrib), str(headless), str(ci_build)]
+        runpy.run_path("find_version.py", run_name="__main__")
+        sys.argv = old_args
+
+    with open(version_file) as fp:
+        exec(fp.read(), version)
+
+    return version["opencv_version"], version["contrib"], version["headless"]
+
+
+def get_build_env_var_by_name(flag_name):
+    flag_set = False
+
+    try:
+        flag_set = bool(int(os.getenv("ENABLE_" + flag_name.upper(), None)))
+    except Exception:
+        pass
+
+    if not flag_set:
+        try:
+            flag_set = bool(int(open(flag_name + ".enabled").read(1)))
+        except Exception:
+            pass
+
+    return flag_set
+
+
+# This creates a list which is empty but returns a length of 1.
+# Should make the wheel a binary distribution and platlib compliant.
+class EmptyListWithLength(list):
+    def __len__(self):
+        return 1
+
+
+if __name__ == "__main__":
+    main()
diff --git a/tests/get_build_info.py b/tests/get_build_info.py
new file mode 100644
index 00000000..4714f2f4
--- /dev/null
+++ b/tests/get_build_info.py
@@ -0,0 +1,3 @@
+import cv2 as cv
+
+print(cv.getBuildInformation())
diff --git a/tests/pylintrc b/tests/pylintrc
new file mode 100644
index 00000000..a3892018
--- /dev/null
+++ b/tests/pylintrc
@@ -0,0 +1,12 @@
+# Source: opencv/platforms/scripts/pylintrc
+
+[MESSAGES CONTROL]
+
+# Disable all to choose the Tests one by one
+disable=all
+
+# Tests
+enable=bad-indentation,       # Used when an unexpected number of indentation’s tabulations or spaces has been found.
+       mixed-indentation,     # Used when there are some mixed tabs and spaces in a module.
+       unnecessary-semicolon, # Used when a statement is ended by a semi-colon (”;”), which isn’t necessary.
+       unused-variable        # Used when a variable is defined but not used. (Use _var to ignore var).
diff --git a/tests/test.py b/tests/test.py
index e520814f..6411ff39 100644
--- a/tests/test.py
+++ b/tests/test.py
@@ -1,16 +1,17 @@
-import unittest
-import sys
-
-
-class OpenCVTest(unittest.TestCase):
-    """ Simple functionality tests. """
-
-    def test_import(self):
-        """ Test that the cv2 module can be imported. """
-        import cv2
-
-    def test_video_capture(self):
-
-        import cv2
-        cap = cv2.VideoCapture("SampleVideo_1280x720_1mb.mp4")
-        self.assertTrue(cap.isOpened())
+import unittest
+import sys
+
+
+class OpenCVTest(unittest.TestCase):
+    """ Simple functionality tests. """
+
+    def test_import(self):
+        """ Test that the cv2 module can be imported. """
+        import cv2
+
+    def test_video_capture(self):
+
+        import cv2
+
+        cap = cv2.VideoCapture("SampleVideo_1280x720_1mb.mp4")
+        self.assertTrue(cap.isOpened())
diff --git a/travis_config.sh b/travis_config.sh
new file mode 100644
index 00000000..366d35ad
--- /dev/null
+++ b/travis_config.sh
@@ -0,0 +1,172 @@
+#!/bin/bash
+#Customize multibuild logic that is run after entering docker.
+#Sourced by docker_build_wrap.sh and docker_test_wrap.sh .
+#Runs in Docker, so only the vars passed to `docker run' exist.
+#See multibuild/README.rst
+echo "===  Loading config.sh  === "
+
+# To see build progress
+function build_wheel {
+    build_bdist_wheel $@
+}
+
+function bdist_wheel_cmd {
+    # copied from multibuild's common_utils.sh
+    # add osx deployment target so it doesn't default to 10.6
+    local abs_wheelhouse=$1
+    # install all required packages in pyproject.toml, because bdist_wheel does not do it
+    python${PYTHON_VERSION} -m pip install toml && python${PYTHON_VERSION} -c 'import toml; c = toml.load("pyproject.toml"); print("\n".join(c["build-system"]["requires"]))' | python${PYTHON_VERSION} -m pip install -r /dev/stdin
+    CI_BUILD=1 python${PYTHON_VERSION} setup.py bdist_wheel --py-limited-api=cp36 -v
+    cp dist/*.whl $abs_wheelhouse
+    if [ -z "$IS_OSX" ]; then
+      # this path can be changed in the latest manylinux image
+      TOOLS_PATH=/opt/_internal/pipx/venvs/auditwheel
+      /opt/python/cp39-cp39/bin/python -m venv $TOOLS_PATH
+      source $TOOLS_PATH/bin/activate
+      python patch_auditwheel_whitelist.py
+      deactivate
+    fi
+    if [ -n "$USE_CCACHE" -a -z "$BREW_BOOTSTRAP_MODE" ]; then ccache -s; fi
+}
+
+if [ -n "$IS_OSX" ]; then
+  echo "    > OSX environment "
+  export MAKEFLAGS="-j$(sysctl -n hw.ncpu)"
+else
+  echo "    > Linux environment "
+  export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/Qt5.15.0/lib
+  export MAKEFLAGS="-j$(grep -E '^processor[[:space:]]*:' /proc/cpuinfo | wc -l)"
+fi
+
+if [ -n "$IS_OSX" ]; then
+
+    source travis_osx_brew_cache.sh
+
+    BREW_SLOW_BUILIDING_PACKAGES=$(printf '%s\n' \
+        "cmake 15" \
+        "ffmpeg_opencv 10" \
+    )
+
+    function generate_ffmpeg_formula {
+        local FF="ffmpeg"
+        local LFF="ffmpeg_opencv"
+        local FF_FORMULA; FF_FORMULA=$(brew formula "${FF}${FFMPEG_FORMULA_VERSION}")
+        local LFF_FORMULA; LFF_FORMULA="$(dirname "$FF_FORMULA")/${LFF}.rb"
+
+        local REGENERATE
+        if [ -f "$LFF_FORMULA" ]; then
+            local UPSTREAM_VERSION VERSION
+            _brew_parse_package_info "$FF" " " UPSTREAM_VERSION _ _
+            _brew_parse_package_info "$LFF" " " VERSION _ _   || REGENERATE=1
+            #`rebuild` clause is ignored on `brew bottle` and deleted
+            # from newly-generated formula on `brew bottle --merge` for some reason
+            # so can't compare rebuild numbers
+            if [ "$UPSTREAM_VERSION" != "$VERSION" ]; then
+                REGENERATE=1
+            fi
+        else
+            REGENERATE=1
+        fi
+        if [ -n "$REGENERATE" ]; then
+            echo "Regenerating custom ffmpeg formula"
+            # Bottle block syntax: https://docs.brew.sh/Bottles#bottle-dsl-domain-specific-language
+            # FfmpegAT4 is a class in ffmpeg@4 formula
+            perl -wpe 'BEGIN {our ($found_blank, $bottle_block);}
+                if (/(^class )(FfmpegAT4)(\s.*)/) {$_=$1."FfmpegOpencv".$3."\n"; next;}
+                if (!$found_blank && /^$/) {$_.="conflicts_with \"ffmpeg\"\n\n"; $found_blank=1; next;}
+                if (!$bottle_block && /^\s*bottle do$/) { $bottle_block=1; next; }
+                if ($bottle_block) { if (/^\s*end\s*$/) { $bottle_block=0} elsif (/^\s*sha256\s/) {$_=""} next; }
+if (/^\s*depends_on "(x264|x265|xvid|frei0r|rubberband|libvidstab)"$/) {$_=""; next;}
+                if (/^\s*--enable-(gpl|libx264|libx265|libxvid|frei0r|librubberband|libvidstab)$/) {$_=""; next;}
+                ' <"$FF_FORMULA" >"$LFF_FORMULA"
+            diff -u "$FF_FORMULA" "$LFF_FORMULA" || test $? -le 1
+
+            (   cd "$(dirname "$LFF_FORMULA")"
+                # This is the official way to add a formula
+                # https://docs.brew.sh/Formula-Cookbook#commit
+                git add "$(basename "$LFF_FORMULA")"
+                git commit -m "add/update custom ffmpeg ${VERSION}"
+            )
+        fi
+    }
+
+fi
+
+function pre_build {
+  echo "Starting pre-build"
+  set -e -o pipefail
+
+  if [ -n "$IS_OSX" ]; then
+    brew install lapack
+  fi
+
+  if [ -n "$IS_OSX" ]; then
+    echo "Running for OSX"
+
+    local CACHE_STAGE;# (echo "$TRAVIS_BUILD_STAGE_NAME" | grep -qiF "final") || CACHE_STAGE=1
+    CACHE_STAGE=
+    export HOMEBREW_NO_AUTO_UPDATE=1
+
+    echo 'Installing FFmpeg'
+
+    brew update
+    generate_ffmpeg_formula
+    brew_add_local_bottles
+    brew install --build-bottle ffmpeg_opencv
+    # It needs when we use not the latest ffmpeg formula
+    brew link ffmpeg_opencv
+
+    if [ -n "$CACHE_STAGE" ]; then
+        brew_go_bootstrap_mode 0
+        return 0
+    fi
+
+    # Have to install macpython late to avoid conflict with Homebrew Python update
+    before_install
+
+  else
+    echo "Running for linux"
+  fi
+}
+
+function run_tests {
+    # Runs tests on installed distribution from an empty directory
+    echo "Run tests..."
+    echo $PWD
+
+    PYTHON=python$PYTHON_VERSION
+
+    echo "Running for linux"
+
+    if [ $PYTHON == "python3.6" ]; then
+      $PYTHON -m pip install -U numpy==1.19.4
+    fi
+    cd /io/tests
+    $PYTHON get_build_info.py
+
+    cd /io/opencv
+    export OPENCV_TEST_DATA_PATH=/io/opencv_extra/testdata
+
+    test_wheels
+    pylint_test
+}
+
+function test_wheels {
+
+    echo "Starting OpenCV tests..."
+
+    #Test package
+    $PYTHON modules/python/test/test.py -v --repo .
+}
+
+function pylint_test {
+
+    echo "Starting Pylint tests..."
+
+    $PYTHON -m pip install pylint==2.12.2
+    cd /io/tests
+    $PYTHON -m pylint /io/opencv/samples/python/squares.py
+}
+
+export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
+set -x
diff --git a/multibuild_customize.sh b/travis_multibuild_customize.sh
similarity index 81%
rename from multibuild_customize.sh
rename to travis_multibuild_customize.sh
index 9b798c90..178fd6ec 100644
--- a/multibuild_customize.sh
+++ b/travis_multibuild_customize.sh
@@ -3,4 +3,4 @@
 export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
 set -x
 REPO_DIR=$(dirname "${BASH_SOURCE[0]}")
-DOCKER_IMAGE='quay.io/skvark/manylinux_$plat'
+DOCKER_IMAGE='quay.io/asenyaev/manylinux2014_$plat'
diff --git a/travis_osx_brew_cache.sh b/travis_osx_brew_cache.sh
new file mode 100644
index 00000000..1a2a1c6c
--- /dev/null
+++ b/travis_osx_brew_cache.sh
@@ -0,0 +1,451 @@
+# Library to cache downloaded and locally-built Homebrew bottles in Travis OSX build.
+
+
+#Should be in Travis' cache
+BREW_LOCAL_BOTTLE_METADATA="$HOME/local_bottle_metadata"
+
+#FIXME: temporary fix to enable the build, should be replaced with the proper path to the cache dir
+mkdir -p $BREW_LOCAL_BOTTLE_METADATA
+
+# Starting reference point for elapsed build time; seconds since the epoch.
+#TRAVIS_TIMER_START_TIME is set at the start of a log fold, in nanoseconds since the epoch
+BREW_TIME_START=$(($TRAVIS_TIMER_START_TIME/10**9))
+
+# If after a package is built, elapsed time is more than this many seconds, fail the build but save Travis cache
+# The cutoff moment should leave enough time till Travis' job time limit to process the main project.
+#  Since we have moved deps into a separate stage, we don't need to leave time for the project any more
+BREW_TIME_LIMIT=$((42*60))
+# If a slow-building package is about to be built and the projected build end moment is beyond this many seconds,
+# skip that build, fail the Travis job and save Travis cache.
+# This cutoff should leave enough time for before_cache and cache save.
+BREW_TIME_HARD_LIMIT=$((43*60))
+
+
+# Auto cleanup can delete locally-built bottles
+# when the caching logic isn't prepared for that
+export HOMEBREW_NO_INSTALL_CLEANUP=1
+
+# Don't query analytical info online on `brew info`,
+#  this takes several seconds and we don't need it
+# see https://docs.brew.sh/Manpage , "info formula" section
+export HOMEBREW_NO_GITHUB_API=1
+
+#Packages already installed in the current session to avoid checking them again
+_BREW_ALREADY_INSTALLED='$'     #$ = illegal package name; a blank line would cause macos grep to swallow everything
+
+
+#Public functions
+
+function brew_install_and_cache_within_time_limit {
+    # Install the package and its dependencies one by one;
+    # use bottle if available, build and cache bottle if not.
+    # Terminate and exit with status 1 if this takes too long.
+    # Exit with status 2 on any other error.
+    _brew_install_and_cache_within_time_limit $@ \
+    || if test $? -eq 1; then brew_go_bootstrap_mode; return 1; else return 2; fi
+}
+
+function brew_add_local_bottles {
+    # Should be called after `brew update` at startup.
+    # Adds metadata for cached locally-built bottles to local formulas
+    #  so that `brew` commands can find them.
+    # If the package was updated, removes the corresponding files
+    #  and the bottle's entry in the formula, if any.
+
+    # Bottle entry in formula:
+    #   bottle do
+    #     <...>
+    #     sha256 "<sha256>" => :<os_codename>
+    #     <...>
+    #   end
+
+    echo "Cached bottles:"
+    ls "$(brew --cache)/downloads" || true  #may not exist initially since it's "$(brew --cache)" that is in Travis cache
+    echo "Saved .json's and links:"
+    ls "$BREW_LOCAL_BOTTLE_METADATA"
+
+    for JSON in "$BREW_LOCAL_BOTTLE_METADATA"/*.json; do
+        [ -e "$JSON" ] || break    # OSX 10.11 bash has no nullglob
+        local PACKAGE JSON_VERSION JSON_REBUILD OS_CODENAME BOTTLE_HASH
+
+        _brew_parse_bottle_json "$JSON" PACKAGE JSON_VERSION JSON_REBUILD OS_CODENAME BOTTLE_HASH
+
+        echo "Adding local bottle: $PACKAGE ${JSON_VERSION}_${JSON_REBUILD}"
+
+        local FORMULA_VERSION FORMULA_REBUILD FORMULA_BOTTLE_HASH
+
+        _brew_parse_package_info "$PACKAGE" "$OS_CODENAME" FORMULA_VERSION FORMULA_REBUILD FORMULA_BOTTLE_HASH
+
+        local FORMULA_HAS_BOTTLE; [ -n "$FORMULA_BOTTLE_HASH" ] && FORMULA_HAS_BOTTLE=1 || true
+
+
+        local BOTTLE_LINK BOTTLE=""; BOTTLE_LINK="${JSON}.bottle.lnk";
+        local BOTTLE_EXISTS= BOTTLE_MISMATCH= VERSION_MISMATCH=
+
+
+        # Check that the bottle file exists and is still appropriate for the formula
+        if [[ "$FORMULA_VERSION" != "$JSON_VERSION" || "$JSON_REBUILD" != "$FORMULA_REBUILD" ]]; then
+            VERSION_MISMATCH=1;
+            echo "The cached bottle is obsolete: formula ${FORMULA_VERSION}_${FORMULA_REBUILD}"
+        fi
+        if [ -f "$BOTTLE_LINK" ]; then
+            BOTTLE=$(cat "$BOTTLE_LINK");
+            BOTTLE=$(cd "$(dirname "$BOTTLE")"; pwd)/$(basename "$BOTTLE")
+
+            if [ -e "$BOTTLE" ]; then
+                BOTTLE_EXISTS=1;
+
+                # The hash in `brew --cache $PACKAGE` entry is generated from download URL,
+                #  which itself is generated from base URL and version
+                # (see Homebrew/Library/Homebrew/download_strategy.rb:cached_location).
+                # So if version changes, hashes will always mismatch anyway
+                #  and we don't need a separate message about this.
+                # XXX: OSX doesn't have `realpath` so can't compare the entire paths
+                if [ -n "$FORMULA_HAS_BOTTLE" -a -z "$VERSION_MISMATCH" -a \
+                    "$(basename "$(brew --cache "$PACKAGE")")" != "$(basename "$BOTTLE")" ]; then
+                        BOTTLE_MISMATCH=1;
+                        echo "Cached bottle file doesn't correspond to formula's cache entry!" \
+                             "This can happen if download URL has changed." >&2
+                fi
+            else
+                echo "Cached bottle file is missing!" >&2
+            fi
+        else
+            echo "Link file is missing or of invalid type!" >&2
+        fi
+
+        # Delete cached bottle and all metadata if invalid
+        if [[ -z "$BOTTLE_EXISTS" || -n "$VERSION_MISMATCH" || -n "$BOTTLE_MISMATCH" ]]; then
+            echo "Deleting the cached bottle and all metadata"
+
+            if [ "$FORMULA_BOTTLE_HASH" == "$BOTTLE_HASH" ]; then
+                echo "A bottle block for the cached bottle was merged into the updated formula. Removing..."
+                local FORMULA; FORMULA=$(brew formula "$PACKAGE")
+                perl -wpe 'BEGIN { our $IN_BLOCK=0; }
+                    if ( ($IN_BLOCK==0) && /^\s*bottle\s+do\s*$/ ) { $IN_BLOCK=1; next; }
+                    if ( ($IN_BLOCK==1) && /^\s*end\s*$/ )         { $IN_BLOCK=-1; next; }
+                    if ( ($IN_BLOCK==1) && /^\s*sha256\s+"(\w+)"\s+=>\s+:\w+\s*$/ )
+                                                 { if ( $1 eq "'"$BOTTLE_HASH"'" ) {$_="";}; next; }
+                '  <"$FORMULA" >"${FORMULA}.new"
+                # Depending on diff version, 1 may mean differences found
+                # https://stackoverflow.com/questions/6971284/what-are-the-error-exit-values-for-diff
+                diff -u "$FORMULA" "${FORMULA}.new" || test $? -le 1
+                (   cd $(dirname "$FORMULA")
+                    FORMULA=$(basename "$FORMULA")
+                    mv -v "${FORMULA}.new" "$FORMULA"
+                    git commit -m "Removed obsolete local bottle ${JSON_VERSION}_${JSON_REBUILD} :${OS_CODENAME}" "$FORMULA"
+                )
+            fi
+
+            if [ -n "$BOTTLE" -a -n "$BOTTLE_EXISTS" ]; then rm "$BOTTLE"; fi
+            rm -f "$BOTTLE_LINK"
+            rm "$JSON"
+
+        #(Re)add metadata to the formula otherwise
+        else
+            if [ "$FORMULA_BOTTLE_HASH" == "$BOTTLE_HASH" ]; then
+                echo "The cached bottle is already present in the formula"
+            else
+                brew bottle --merge --write "$JSON"
+            fi
+        fi
+    done
+}
+
+
+function brew_cache_cleanup {
+    #Cleanup caching directories
+    # Is supposed to be called in before_cache
+
+    #Lefovers from some failure probably
+    rm -f "$BREW_LOCAL_BOTTLE_METADATA"/*.tar.gz
+
+    #`brew cleanup` may delete locally-built bottles that weren't needed this time
+    # so we're saving and restoring them
+    local BOTTLE_LINK BOTTLE
+    for BOTTLE_LINK in "$BREW_LOCAL_BOTTLE_METADATA"/*.lnk; do
+        [ -e "$BOTTLE_LINK" ] || break
+        BOTTLE=$(cat "$BOTTLE_LINK")
+        ln "$BOTTLE" "$BREW_LOCAL_BOTTLE_METADATA/"
+    done
+    brew cleanup
+    local BOTTLE_BASENAME
+    for BOTTLE_LINK in "$BREW_LOCAL_BOTTLE_METADATA"/*.lnk; do
+        [ -e "$BOTTLE_LINK" ] || break
+        BOTTLE=$(cat "$BOTTLE_LINK")
+        BOTTLE_BASENAME=$(basename "$BOTTLE")
+        if test ! -e "$BOTTLE"; then
+            echo "Restoring: $BOTTLE_BASENAME"
+            mv "$BREW_LOCAL_BOTTLE_METADATA/$BOTTLE_BASENAME" "$BOTTLE"
+        else
+            rm "$BREW_LOCAL_BOTTLE_METADATA/$BOTTLE_BASENAME"
+        fi
+    done
+}
+
+
+function brew_go_bootstrap_mode {
+# Can be overridden
+# Terminate the build but ensure saving the cache
+    local EXIT_CODE=${1:-1}
+
+    echo "Going into cache bootstrap mode"
+
+    BREW_BOOTSTRAP_MODE=1
+
+    #Can't just `exit` because that would terminate the build without saving the cache
+    #Have to replace further actions with no-ops
+
+    local MESSAGE=""; if [ "$EXIT_CODE" -ne 0 ]; then
+        MESSAGE='Building dependencies took too long. Restart the build in Travis UI to continue from cache.';
+    fi
+
+    eval '
+    function '"$cmd"' { return 0; }
+    function repair_wheelhouse { return 0; }
+    function install_run {'\
+        "$(if [ -n "$MESSAGE" ]; then
+            echo \
+        '        echo -e "\n'"$MESSAGE"'\n"'
+        fi)"\
+    '
+        # Travis runs user scripts via `eval` i.e. in the same shell process.
+        # So have to unset errexit in order to get to cache save stage
+        set +e; return '"$EXIT_CODE"'
+    }'
+}
+
+
+
+#Internal functions
+
+function _brew_install_and_cache_within_time_limit {
+    # This fn is run with || so errexit can't be enabled
+
+    local PACKAGE TIME_LIMIT TIME_HARD_LIMIT TIME_START MARKED_INSTALLED
+    PACKAGE="${1:?}" || return 2
+    TIME_LIMIT=${2:-$BREW_TIME_LIMIT} || return 2
+    TIME_HARD_LIMIT=${3:-$BREW_TIME_HARD_LIMIT} || return 2
+    TIME_START=${4:-$BREW_TIME_START} || return 2
+
+    if grep -qxFf <(cat <<<"$_BREW_ALREADY_INSTALLED") <<<"$PACKAGE"; then
+        MARKED_INSTALLED=1
+    fi
+
+    if [ -n "$MARKED_INSTALLED" ] || (brew list --versions "$PACKAGE" >/dev/null && ! (brew outdated | grep -qxF "$PACKAGE")); then
+        echo "Already installed and the latest version: $PACKAGE"
+        if [ -z "$MARKED_INSTALLED" ]; then _brew_mark_installed "$PACKAGE"; fi
+        return 0
+    fi
+
+    local BUILD_FROM_SOURCE INCLUDE_BUILD KEG_ONLY
+
+    _brew_is_bottle_available "$PACKAGE" KEG_ONLY || BUILD_FROM_SOURCE=1
+    [ -n "$BUILD_FROM_SOURCE" ] && INCLUDE_BUILD="--include-build" || true
+
+    # Whitespace is illegal in package names so converting all whitespace into single spaces due to no quotes is okay.
+    DEPS=`brew deps "$PACKAGE" $INCLUDE_BUILD` || return 2
+    DEPS=`grep -vxF <(cat <<<"$_BREW_ALREADY_INSTALLED") <<<"$DEPS"` || test $? -eq 1 || return 2
+    for dep in $DEPS; do
+        #TIME_LIMIT only has to be met if we'll be actually building the main project this iteration, i.e. after the "root" module installation
+        #While we don't know that yet, we can make better use of Travis-given time with a laxer limit
+        #We still can't overrun TIME_HARD_LIMIT as that wouldn't leave time to save the cache
+        _brew_install_and_cache_within_time_limit "$dep" $(((TIME_LIMIT+TIME_HARD_LIMIT)/2)) "$TIME_HARD_LIMIT" "$TIME_START" || return $?
+    done
+
+    _brew_check_slow_building_ahead "$PACKAGE" "$TIME_START" "$TIME_HARD_LIMIT" || return $?
+    _brew_install_and_cache "$PACKAGE" "$([[ -z "$BUILD_FROM_SOURCE" ]] && echo 1 || echo 0)" "$KEG_ONLY" || return 2
+    _brew_check_elapsed_build_time "$TIME_START" "$TIME_LIMIT" || return $?
+}
+
+
+function _brew_parse_bottle_json {
+    # Parse JSON file resulting from `brew bottle --json`
+    # and save data into specified variables
+
+    local JSON; JSON="${1:?}"; shift
+
+    local JSON_DATA; JSON_DATA=$(python2.7 -c 'if True:
+    import sys,json; j=json.load(open(sys.argv[1],"rb")); [name]=j.keys(); [pdata]=j.values()
+    print name
+    print pdata["formula"]["pkg_version"]
+    print pdata["bottle"]["rebuild"]
+    [(tag_name, tag_dict)]=pdata["bottle"]["tags"].items()
+    print tag_name
+    print tag_dict["sha256"]
+    ' "$JSON")
+
+    unset JSON
+
+    { local i v; for i in {1..5}; do
+        read -r v
+        eval "${1:?}=\"$v\""
+        shift
+    done } <<< "$JSON_DATA"
+}
+
+function _brew_parse_package_info {
+    # Get and parse `brew info --json` about a package
+    # and save data into specified variables
+
+    local PACKAGE OS_CODENAME
+    PACKAGE="${1:?}"; shift
+    OS_CODENAME="${1:?}"; shift
+
+    local JSON_DATA; JSON_DATA=$(python2.7 -c 'if True:
+    import sys, json, subprocess; j=json.loads(subprocess.check_output(("brew","info","--json=v1",sys.argv[1])))
+    data=j[0]
+    revision=data["revision"]
+    # in bottle''s json, revision is included into version; here, they are separate
+    print data["versions"]["stable"]+("_"+str(revision) if revision else "")
+    bottle_data=data["bottle"].get("stable",{"rebuild":"","files":{}})
+    print bottle_data["rebuild"]
+    print bottle_data["files"].get(sys.argv[2],{"sha256":"!?"})["sha256"]     #prevent losing trailing blank line to command substitution
+    ' \
+    "$PACKAGE" "$OS_CODENAME"); JSON_DATA="${JSON_DATA%\!\?}"  #!? can't occur in a hash
+
+    unset PACKAGE OS_CODENAME
+
+    { local i v; for i in {1..3}; do
+        read -r v
+        eval "${1:?}=\"$v\""
+        shift
+    done } <<< "$JSON_DATA"
+}
+
+
+
+function _brew_is_bottle_available {
+
+    local PACKAGE;PACKAGE="${1:?}"
+    local VAR_KEG_ONLY="$2"
+
+    # `brew info` prints "Error: Broken pipe" if piped directly to `head` and the info is long
+    # 141 = 128 + SIGPIPE
+    local INFO;INFO="$((brew info "$PACKAGE" | cat || test $? -eq 141) | head -n 1)"
+    if [ -n "$VAR_KEG_ONLY" ]; then
+        if grep -qwF '[keg-only]' <<<"$INFO"; then
+            eval "${VAR_KEG_ONLY}=1"
+        else
+            eval "${VAR_KEG_ONLY}=0"
+        fi
+    fi
+
+    if grep -qxEe '[[:space:]]*bottle :unneeded' $(brew formula "$PACKAGE"); then
+        echo "Bottle disabled: $PACKAGE"
+        return 0
+    fi
+
+    if grep -qwF '(bottled)' <<<"$INFO"; then
+        echo "Bottle available: $INFO"
+        return 0
+    else
+        echo "Bottle not available: $INFO"
+        return 1
+    fi
+}
+
+function _brew_install_and_cache {
+    # Install bottle or make and cache bottle.
+    # assumes that deps were already installed
+    # and not already the latest version
+
+    local PACKAGE USE_BOTTLE KEG_ONLY
+    PACKAGE="${1:?}"
+    USE_BOTTLE="${2:?}"
+    KEG_ONLY="${3:?}"
+    local VERB
+
+    if brew list --versions "$PACKAGE"; then
+        # Install alongside the old version to avoid to have to update "runtime dependents"
+        # https://discourse.brew.sh/t/can-i-install-a-new-version-without-having-to-upgrade-runtime-dependents/4443
+        VERB="install --force"
+        if [ "$KEG_ONLY" -eq 0 ]; then
+            brew unlink "$PACKAGE"
+        fi
+    else
+        VERB=install
+    fi
+
+    if [[ "$USE_BOTTLE" -gt 0 ]]; then
+        echo "Installing bottle for: $PACKAGE"
+        brew $VERB "$PACKAGE"
+    else
+        echo "Building bottle for: $PACKAGE"
+        brew $VERB --build-bottle "$PACKAGE"
+        exec 3>&1
+        local OUT=$(brew bottle --json "$PACKAGE" | tee /dev/fd/3)
+        exec 3>&-
+
+        ls "$PACKAGE"*
+        # doesn't seem to be a documented way to get file names
+        local BOTTLE; BOTTLE=$(grep -Ee '^./' <<<"$OUT")
+        #proper procedure as per https://discourse.brew.sh/t/how-are-bottle-and-postinstall-related-is-it-safe-to-run-bottle-after-postinstall/3410/4
+        brew uninstall --ignore-dependencies "$PACKAGE"
+        brew $VERB "$BOTTLE"
+
+        local JSON; JSON=$(sed -E 's/bottle(.[[:digit:]]+)?\.tar\.gz$/bottle.json/' <<<"$BOTTLE")
+
+        #`brew bottle --merge` doesn't return nonzero on nonexisting json file
+        test -f "$JSON" -a -f "$BOTTLE"
+
+        brew bottle --merge --write "$JSON"
+        local CACHED_BOTTLE; CACHED_BOTTLE="$(brew --cache "$PACKAGE")"
+        mv "$BOTTLE" "$CACHED_BOTTLE";
+        local CACHED_JSON; CACHED_JSON="${BREW_LOCAL_BOTTLE_METADATA}/$(basename "$JSON")"
+        mv "$JSON" "$CACHED_JSON"
+        #Symlinks aren't cached by Travis. Will just save paths in files then.
+        local BOTTLE_LINK; BOTTLE_LINK="${CACHED_JSON}.bottle.lnk"
+        echo "$CACHED_BOTTLE" >"$BOTTLE_LINK"
+
+    fi
+
+    _brew_mark_installed "$PACKAGE"
+}
+
+function _brew_mark_installed {
+    _BREW_ALREADY_INSTALLED="$_BREW_ALREADY_INSTALLED"$'\n'"${1:?}"
+}
+
+function _brew_check_elapsed_build_time {
+    # If time limit has been reached,
+    # arrange for further build to be skipped and return 1
+
+    local TIME_START TIME_LIMIT ELAPSED_TIME
+    TIME_START="${1:?}"
+    TIME_LIMIT="${2:?}"
+
+    ELAPSED_TIME=$(($(date +%s) - $TIME_START))
+    echo "Elapsed time: "$(($ELAPSED_TIME/60))"m (${ELAPSED_TIME}s)"
+
+    if [[ "$ELAPSED_TIME" -gt $TIME_LIMIT ]]; then
+        brew_go_bootstrap_mode
+        return 1
+    fi
+    return 0
+}
+
+function _brew_check_slow_building_ahead {
+
+    #If the package's projected build completion is higher than hard limit,
+    # skip it and arrange for further build to be skipped and return 1
+
+    local PACKAGE TIME_START TIME_HARD_LIMIT
+    PACKAGE="${1:?}"
+    TIME_START="${2:?}"
+    TIME_HARD_LIMIT="${3:?}"
+
+    local PROJECTED_BUILD_TIME
+    PROJECTED_BUILD_TIME=$(echo "$BREW_SLOW_BUILIDING_PACKAGES" | awk '$1=="'"$PACKAGE"'"{print $2}')
+    [ -z "$PROJECTED_BUILD_TIME" ] && return 0 || true
+
+    local PROJECTED_BUILD_END_ELAPSED_TIME
+    PROJECTED_BUILD_END_ELAPSED_TIME=$(( $(date +%s) - TIME_START + PROJECTED_BUILD_TIME * 60))
+
+    if [[ "$PROJECTED_BUILD_END_ELAPSED_TIME" -ge "$TIME_HARD_LIMIT" ]]; then
+        echo -e "\nProjected build end elapsed time for $PACKAGE: $((PROJECTED_BUILD_END_ELAPSED_TIME/60))m ($PROJECTED_BUILD_END_ELAPSED_TIMEs)"
+        brew_go_bootstrap_mode
+        return 1
+    fi
+    return 0
+}
