从嵌套项目结构中的自定义 Python 包导入对象时出现 ModuleNotFoundError

问题描述 投票:0回答:1

我一直在编写一个图像处理管道,其中一部分是使用 yolov7 来获取图像中人物周围的边界框。我制作了一个 自定义包装器 (我可以

pip install
)来有一个
Detection()
对象来输入图像,并且它在我的测试中完美运行,但当我将对象导入到另一个文件中时却不起作用。这是我当前的项目结构:

src/
├── urlProcessor/
│   ├── models/
│   │   ├── __init__.py
│   │   ├── YOLOWrapper.py
│   │   └── yolov7.pt
│   ├── __init__.py
│   └── runAnalysis.py
└── other_stuff/

里面

YOLOWrapper.py
我有这个代码

from YOLOv7Detector import Detector as det
from PIL import Image


class YOLOInferenceSingleton:
    def __init__(self, weights_path):
        self.detector = det(weights_path)

    def calculateDetections(self, image, view_img=False):
        return self.detector.calculateDetections(image, view_img=view_img)


def main():
    # Initialize the YOLO inference object
    detector = det('yolov7.pt')

    # Load the image
    image = Image.open('../../../data/test_set/test_101.jpg')

    # Run the YOLO detection
    dets = detector.calculateDetections(image, view_img=True)


if __name__ == '__main__':
    main()

其工作原理与预期完全一致。但是,当我将

YOLOInferenceSingleton
对象导入到
runAnalysis.py
时:

from models.YOLOWrapper import YOLOInferenceSingleton

我得到一个

ModuleNotFoundError

Traceback (most recent call last):
  File "...\src\urlProcessor\runAnalysis.py", line 12, in <module>
    from models.YOLOWrapper import YOLOInferenceSingleton
  File "...\src\urlProcessor\models\YOLOWrapper.py", line 1, in <module>
    from YOLOv7Detector import Detector as det
  File "...\venv\lib\site-packages\YOLOv7Detector\__init__.py", line 1, in <module>
    from YOLOv7Detector.model import Detector
  File "...\venv\lib\site-packages\YOLOv7Detector\model.py", line 16, in <module>
    from YOLOv7Detector.yolov7.models.experimental import attempt_load
  File "...\venv\lib\site-packages\YOLOv7Detector\yolov7\models\experimental.py", line 6, in <module>
    from models.common import Conv, DWConv
ModuleNotFoundError: No module named 'models.common'

Process finished with exit code 1

这会一直回到包装器中的原始

yolov7
实现。

更多可能有用的信息:

我制作的包装器中的文件结构是这样的

YOLOv7Detector
├── /yolov7/ <---- This is the original implementation repo, I'm importing from here
├── __init__.py         
├── image_funcs.py     
└── model.py <---- This is where I am importing to 

当我将函数从

yolov7
目录导入到
model.py
时,我遇到了另一个导入错误,我通过将其添加到
sys.path
来修复该错误。这是我第一次制作包,所以我不知道这是否是正确的方法,所以它可能很愚蠢。

我尝试通过

__init__.py
目录中的
/models/
导入内容,但这没有任何作用。 我还尝试在
/models/
中附加
runAnalysis
路径,但这也没有做任何事情。

如果您已经走到这一步,谢谢,我将不胜感激任何帮助,我现在很困惑。

python python-import python-packaging modulenotfounderror
1个回答
0
投票

如果您尝试使用绝对路径导入,这种方法可能会对您有所帮助

你这个老进口货

from models.YOLOWrapper import YOLOInferenceSingleton

现在试试这个

from urlProcessor.models.YOLOWrapper import YOLOInferenceSingleton
© www.soinside.com 2019 - 2024. All rights reserved.