Vaughan Russell
Vaughan Russell

Reputation: 11

Can't Import SAM2 in Python

This is the official introduction to how to install SAM2 using pip:

https://github.com/facebookresearch/sam2?tab=readme-ov-file#installation

I cloned this repo and created a new environment called venv with virtualEnv. Then I install the package using:

pip install -e .

Clearly, it works well.

The question is when I create a new project in another directory, open it with vs code, choose the environment containing sam2, and try to import sam2 using:

from sam2.build_sam import build_sam2

Pylance says "Import sam2.build_sam could not be resolved", which makes me confused.

I noticed that the repo's name is 'sam2', and it might cause a problem because its package name is also 'sam2'.

When cloning sam2 to the root directory of my project, creating a new environment, and installing it, I can import sam2 correctly by adding another 'sam2' as a prefix, like:

from sam2.sam2.build_sam import build_sam2

But once the environment that contains sam2 and the project exist in different directories, adding a 'sam2' as a prefix helps nothing with the problem.

This is the summary of the problem generated by ChatGPT:

When you create a new project in a different directory and try to import sam2 (using the environment that contains sam2), Pylance in VS Code gives you an "import could not be resolved" error. You observed that the import path works when the project and sam2 are in the same directory by adding a second sam2 prefix (e.g., from sam2.sam2.build_sam import build_sam2), but this approach fails when they are in separate directories.

Many Thanks.

Upvotes: 1

Views: 703

Answers (1)

Shower Hu
Shower Hu

Reputation: 15

I encountered the same question on Windows.

A command!{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam2.git' can be found on Colab

So, python -m pip install git+https://github.com/facebookresearch/sam2.git seems to work fine.

Upvotes: 1

Related Questions