如何在Mac M1中安装OpenCV?

ctzwtxfj  于 2022-12-04  发布在  Mac
关注(0)|答案(1)|浏览(416)

我的目标是在Mac M1中安装$ pip install opencv-python。问题是我不知道opencv,所以我想从入门页面学习。然而,opencv的第一个代码给我带来了一个错误。
我所做的:

  1. $ pip install opencv-python-〉相同错误
  2. $ pip uninstall opencv-python-〉$ pip install opencv-contrib-python-〉相同错误。
import cv2 as cv
import sys
img = cv.imread(cv.samples.findFile("starry_night.jpg"))
if img is None:
    sys.exit("Could not read the image.")
cv.imshow("Display window", img)
k = cv.waitKey(0)
if k == ord("s"):
    cv.imwrite("starry_night.png", img)

误差

[ WARN:0@0.011] global /Users/xperience/actions-runner/_work/opencv-python/opencv-python/opencv/modules/core/src/utils/samples.cpp (61) findFile cv::samples::findFile('starry_night.jpg') => ''
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
Cell In [1], line 3
      1 import cv2 as cv
      2 import sys
----> 3 img = cv.imread(cv.samples.findFile("starry_night.jpg"))
      4 if img is None:
      5     sys.exit("Could not read the image.")

error: OpenCV(4.6.0) /Users/xperience/actions-runner/_work/opencv-python/opencv-python/opencv/modules/core/src/utils/samples.cpp:64: error: (-2:Unspecified error) OpenCV samples: Can't find required data file: starry_night.jpg in function 'findFile'
7lrncoxx

7lrncoxx1#

看起来cv.imread()函数无法在当前目录中找到图像文件“starry_night. jpg”。这可能是因为findFile()函数返回了一个空字符串,这表明无法找到该文件。
要解决这个问题,你需要确保“starry_night.jpg”文件存在于你当前的工作目录中。你可以通过在终端中运行ls列出当前目录中的所有文件来验证这一点,或者使用Python中的os.path.exists()函数来检查文件是否存在。
一旦确认文件存在于当前目录中,就可以尝试修改代码以指定图像文件的完整路径,而不是依赖findFile()函数。例如:

import cv2 as cv
import os

# Replace "/path/to/image/file" with the full path to your "starry_night.jpg" file
img_path = "/path/to/image/file/starry_night.jpg"

# Check if the file exists
if not os.path.exists(img_path):
    sys.exit("Error: File not found.")

# Read the image file
img = cv.imread(img_path)

# Check if the image was successfully read
if img is None:
    sys.exit("Error: Could not read the image.")

# Display the image
cv.imshow("Display window", img)

# Wait for a key press and save the image if "s" is pressed
k = cv.waitKey(0)
...

相关问题