如何将opencv库的位置链接到python文件中(ModuleNotFoundError:No module named 'cv2')

mwyxok5s  于 7个月前  发布在  Python
关注(0)|答案(1)|浏览(69)

所以我为Python(3.10.4)和OpenCV写了一个小的“Hello World”,它做了以下事情:
1.从名为“images”的文件夹中读取图像
1.显示图像
1.将“Hello World”打印到控制台。
如果我在Anaconda中使用python hello_world.py命令(不激活任何环境),它可以正常工作。但是如果我在普通的Windows终端中执行同样的操作,我会得到错误“ModuleNotFoundError: No module named 'cv2'”-所以我假设Anaconda知道在哪里查找OpenCV,但“普通”终端不知道。我如何将信息直接添加到脚本或函数调用?
我不能使用Anaconda来运行它的原因是,我必须将脚本转移到一个我没有Anaconda或类似软件的Linux板上(事实上,我甚至没有在板上连接互联网)。所以我必须以某种方式将信息添加到函数调用或脚本本身,但我不知道如何做到这一点。
在Windows上,OpenCV可以在这里找到:C:/opencv/build/python/cv2
在Linux板上,库似乎在这里/usr/lib/python3.10
如果你能给予我一个如何链接OpenCV的简单步骤指南,我将非常感激!
下面是完整的hello_world.py脚本

import cv2 #I think I need to be more specific here?
import os
import sys

def main():

    # Check if the script is run from its own directory
    script_directory = os.path.dirname(os.path.abspath(__file__))
    image_subfolder = os.path.join(script_directory, "images")

    if not os.path.exists(image_subfolder):
        print("Error: 'images' subfolder not found.")
        sys.exit(1)

    image_files = [f for f in os.listdir(image_subfolder) if f.endswith(('.jpg', '.png', '.jpeg'))]

    if not image_files:
        print("Error: No image files found in the 'images' subfolder.")
        sys.exit(1)

    image_path = os.path.join(image_subfolder, image_files[0])

    # Read and display the image using OpenCV
    image = cv2.imread(image_path)
    cv2.imshow("Image", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # Print "Hello World" to the console
    print("Hello World")

if __name__ == "__main__":
    main()
dgtucam1

dgtucam11#

听起来你还没有在Windows python环境中安装所有的依赖项。
最简单的方法是打开一个新的终端并运行:

pip install opencv-python

(This已在https://pypi.org/project/opencv-python/#installation-and-usage中描述)
有关长读取依赖项,请参见https://packaging.python.org/en/latest/tutorials/managing-dependencies/

相关问题