Bootstrap

在 Raspberry Pi 上安装 OpenCV 可能会出现各种问题

在 Raspberry Pi 上安装 OpenCV 可能会出现各种问题,特别是在虚拟环境中安装时。根据你遇到的错误信息,问题可能与网络超时或特定版本的依赖有关。以下是一些解决方案,你可以尝试逐一解决问题:

pip install opencv-python
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting opencv-python
  Downloading opencv-python-4.9.0.80.tar.gz (92.9 MB)
     |████████████████████████████████| 92.9 MB 14 kB/s 
  Installing build dependencies ... error
  ERROR: Command errored out with exit status 2:
   command: /home/pi/opencv/bin/python3 /home/pi/opencv/lib/python3.9/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-9wmxma8u/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple --extra-index-url https://www.piwheels.org/simple -- 'cmake>=3.1' 'numpy==1.13.3; python_version=='"'"'3.6'"'"' and platform_machine != '"'"'aarch64'"'"' and platform_machine != '"'"'arm64'"'"'' 'numpy==1.17.0; python_version=='"'"'3.7'"'"' and platform_machine != '"'"'aarch64'"'"' and platform_machine != '"'"'arm64'"'"'' 'numpy==1.17.5; 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'"'"' and platform_system!='"'"'Darwin'"'"'' 'numpy==1.21.4; python_version=='"'"'3.10'"'"' and platform_system=='"'"'Darwin'"'"'' 'numpy==1.22.2; python_version>='"'"'3.11'"'"'' pip 'scikit-build>=0.14.0' setuptools==59.2.0
       cwd: None
  Complete output (96 lines):
  Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple, https://www.piwheels.org/simple
  Ignoring numpy: markers 'python_version == "3.6" and platform_machine != "aarch64" and platform_machine != "arm64"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.7" and platform_machine != "aarch64" and platform_machine != "arm64"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.8" and platform_machine != "aarch64" and platform_machine != "arm64"' don't match your environment
  Ignoring numpy: markers 'python_version <= "3.9" and sys_platform == "linux" and platform_machine == "aarch64"' don't match your environment
  Ignoring numpy: markers 'python_version <= "3.9" and sys_platform == "darwin" and platform_machine == "arm64"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.10" and platform_system != "Darwin"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.10" and platform_system == "Darwin"' don't match your environment
  Ignoring numpy: markers 'python_version >= "3.11"' don't match your environment
  Collecting cmake>=3.1
    Downloading https://www.piwheels.org/simple/cmake/cmake-3.29.3-py3-none-linux_armv7l.whl (19.9 MB)
  ERROR: Exception:
  Traceback (most recent call last):
    File "/usr/share/python-wheels/resolvelib-0.5.4-py2.py3-none-any.whl/resolvelib/resolvers.py", line 171, in _merge_into_criterion
      crit = self.state.criteria[name]
  KeyError: 'cmake'
  
  During handling of the above exception, another exception occurred:
  
  Traceback (most recent call last):
    File "/usr/share/python-wheels/urllib3-1.26.5-py2.py3-none-any.whl/urllib3/response.py", line 438, in _error_catcher
      yield
    File "/usr/share/python-wheels/urllib3-1.26.5-py2.py3-none-any.whl/urllib3/response.py", line 519, in read
      data = self._fp.read(amt) if not fp_closed else b""
    File "/usr/share/python-wheels/CacheControl-0.12.6-py2.py3-none-any.whl/cachecontrol/filewrapper.py", line 62, in read
      data = self.__fp.read(amt)
    File "/usr/lib/python3.9/http/client.py", line 458, in read
      n = self.readinto(b)
    File "/usr/lib/python3.9/http/client.py", line 502, in readinto
      n = self.fp.readinto(b)
    File "/usr/lib/python3.9/socket.py", line 704, in readinto
      return self._sock.recv_into(b)
    File "/usr/lib/python3.9/ssl.py", line 1241, in recv_into
      return self.read(nbytes, buffer)
    File "/usr/lib/python3.9/ssl.py", line 1099, in read
      return self._sslobj.read(len, buffer)
  socket.timeout: The read operation timed out
  
  During handling of the above exception, another exception occurred:
  
  Traceback (most recent call last):
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/cli/base_command.py", line 223, in _main
      status = self.run(options, args)
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/cli/req_command.py", line 180, in wrapper
      return func(self, options, args)
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/commands/install.py", line 346, in run
      requirement_set = resolver.resolve(
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 122, in resolve
      self._result = resolver.resolve(
    File "/usr/share/python-wheels/resolvelib-0.5.4-py2.py3-none-any.whl/resolvelib/resolvers.py", line 453, in resolve
      state = resolution.resolve(requirements, max_rounds=max_rounds)
    File "/usr/share/python-wheels/resolvelib-0.5.4-py2.py3-none-any.whl/resolvelib/resolvers.py", line 318, in resolve
      name, crit = self._merge_into_criterion(r, parent=None)
    File "/usr/share/python-wheels/resolvelib-0.5.4-py2.py3-none-any.whl/resolvelib/resolvers.py", line 173, in _merge_into_criterion
      crit = Criterion.from_requirement(self._p, requirement, parent)
    File "/usr/share/python-wheels/resolvelib-0.5.4-py2.py3-none-any.whl/resolvelib/resolvers.py", line 82, in from_requirement
      if not cands:
    File "/usr/share/python-wheels/resolvelib-0.5.4-py2.py3-none-any.whl/resolvelib/structs.py", line 124, in __bool__
      return bool(self._sequence)
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 99, in __bool__
      return any(self)
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/factory.py", line 239, in iter_index_candidates
      candidate = self._make_candidate_from_link(
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/factory.py", line 167, in _make_candidate_from_link
      self._link_candidate_cache[link] = LinkCandidate(
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 296, in __init__
      super(LinkCandidate, self).__init__(
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 144, in __init__
      self.dist = self._prepare()
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 222, in _prepare
      dist = self._prepare_distribution()
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 307, in _prepare_distribution
      return self._factory.preparer.prepare_linked_requirement(
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/operations/prepare.py", line 480, in prepare_linked_requirement
      return self._prepare_linked_requirement(req, parallel_builds)
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/operations/prepare.py", line 503, in _prepare_linked_requirement
      local_file = unpack_url(
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/operations/prepare.py", line 253, in unpack_url
      file = get_http_url(
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/operations/prepare.py", line 130, in get_http_url
      from_path, content_type = download(link, temp_dir.path)
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/network/download.py", line 163, in __call__
      for chunk in chunks:
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/cli/progress_bars.py", line 168, in iter
      for x in it:
    File "/home/pi/opencv/lib/python3.9/site-packages/pip/_internal/network/utils.py", line 64, in response_chunks
      for chunk in response.raw.stream(
    File "/usr/share/python-wheels/urllib3-1.26.5-py2.py3-none-any.whl/urllib3/response.py", line 576, in stream
      data = self.read(amt=amt, decode_content=decode_content)
    File "/usr/share/python-wheels/urllib3-1.26.5-py2.py3-none-any.whl/urllib3/response.py", line 541, in read
      raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
    File "/usr/lib/python3.9/contextlib.py", line 135, in __exit__
      self.gen.throw(type, value, traceback)
    File "/usr/share/python-wheels/urllib3-1.26.5-py2.py3-none-any.whl/urllib3/response.py", line 443, in _error_catcher
      raise ReadTimeoutError(self._pool, None, "Read timed out.")
  urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='www.piwheels.org', port=443): Read timed out.
  ----------------------------------------

解决方案

  1. 安装基础依赖
    首先确保安装了编译 OpenCV 所需的所有基础依赖:
sudo apt-get update
sudo apt-get install -y build-essential cmake git pkg-config libjpeg-dev libtiff-dev libpng-dev
sudo apt-get install -y libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install -y libxvidcore-dev libx264-dev
sudo apt-get install -y libgtk2.0-dev libgtk-3-dev
sudo apt-get install -y libatlas-base-dev gfortran
sudo apt-get install -y python3-dev python3-pip
  1. 配置和激活虚拟环境
    如果还没有创建虚拟环境,创建一个新的虚拟环境:
python3 -m venv /home/pi/opencv
source /home/pi/opencv/bin/activate
  1. 安装 opencv-python 包
    尝试使用 pip 安装 opencv-python 包:
pip install --upgrade pip
pip install opencv-python-headless
opencv-python-headless 是不包含 GUI 相关功能的版本,通常更容易安装。
  1. 手动安装 OpenCV
    如果上述步骤仍然无法解决问题,可以尝试手动编译和安装 OpenCV。以下是具体步骤:

下载 OpenCV 源码

bash
复制代码
cd ~
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
cd opencv
git checkout 4.x
cd …/opencv_contrib
git checkout 4.x
cd …/opencv
创建构建目录并配置 CMake

mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
      -D CMAKE_INSTALL_PREFIX=/usr/local \
      -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \
      -D ENABLE_NEON=ON \
      -D ENABLE_VFPV3=ON \
      -D BUILD_TESTS=OFF \
      -D OPENCV_ENABLE_NONFREE=ON \
      -D INSTALL_PYTHON_EXAMPLES=OFF \
      -D BUILD_EXAMPLES=OFF ..

编译 OpenCV

根据你的设备性能,调整 -j 后的数字,以充分利用你的 CPU 核心。例如,如果你的 Raspberry Pi 有 4 个核心,可以使用 -j4:

make -j4

安装 OpenCV

sudo make install
sudo ldconfig

验证安装

激活你的虚拟环境,并确保 Python 解释器能够找到 OpenCV:

source /home/pi/opencv/bin/activate
python -c "import cv2; print(cv2.__version__)"
;