SAM2跑通(Ubuntu20.04)内含安装多个cuda

参考链接:

github链接
安装cuda,之前借鉴的方法
安装多个cuda

补充cuda安装:

A symlink already exists at /usr/local/cuda. Update to this installation?
选择no,否则会创建一个软连接覆盖之前那个/usr/local/cuda

sudo gedit ~/.bashrc
source ~/.bashrc
如果按第二个链接安装的cuda,手动改一下版本即可

SAM环境安装步骤

除了本地cuda版本要对应pytorch的cuda版本之外,没有什么难点。
但YOLO为啥不需要本地cuda,导致我一直以为不需要装cuda就能跑项目,pytorch自带?

git clone https://github.com/facebookresearch/segment-anything-2.git

cd segment-anything-2

conda create -n SAM python=3.10
conda activate SAM

# setup.py要求了环境,python>=3.10
pip install -e .
问题:RuntimeError:
The detected CUDA version (11.7) mismatches the version that was used to compile
PyTorch (12.1). Please make sure to use the same CUDA versions.
解决办法:先去pytorch官网查看torch>=2.3.1要求的cuda为11.8至少,只能再装个cuda12.1

pip install -e ".[demo]"

#下载权重
cd checkpoints
./download_ckpts.sh

SAM推理步骤

有点晕,感觉是标注软件的感觉,需要提供点或者框,然后进行预测。
这里展示使用点预测分割的效果,只需要修改image和input_point,其它详细信息可以查看github或者其他介绍。

import torch
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

def show_mask(mask, ax, random_color=False, borders = True):
    if random_color:
        color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
    else:
        color = np.array([30/255, 144/255, 255/255, 0.6])
    h, w = mask.shape[-2:]
    mask = mask.astype(np.uint8)
    mask_image =  mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
    if borders:
        import cv2
        contours, _ = cv2.findContours(mask,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
        # Try to smooth contours
        contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours]
        mask_image = cv2.drawContours(mask_image, contours, -1, (1, 1, 1, 0.5), thickness=2) 
    ax.imshow(mask_image)

def show_points(coords, labels, ax, marker_size=375):
    pos_points = coords[labels==1]
    neg_points = coords[labels==0]
    ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
    ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)   

def show_box(box, ax):
    x0, y0 = box[0], box[1]
    w, h = box[2] - box[0], box[3] - box[1]
    ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0, 0, 0, 0), lw=2))    

def show_masks(image, masks, scores, point_coords=None, box_coords=None, input_labels=None, borders=True):
    for i, (mask, score) in enumerate(zip(masks, scores)):
        plt.figure(figsize=(10, 10))
        plt.imshow(image)
        show_mask(mask, plt.gca(), borders=borders)
        if point_coords is not None:
            assert input_labels is not None
            show_points(point_coords, input_labels, plt.gca())
        if box_coords is not None:
            # boxes
            show_box(box_coords, plt.gca())
        if len(scores) > 1:
            plt.title(f"Mask {i+1}, Score: {score:.3f}", fontsize=18)
        plt.axis('off')
        plt.show()

checkpoint = "./checkpoints/sam2_hiera_large.pt"
model_cfg = "sam2_hiera_l.yaml"
predictor = SAM2ImagePredictor(build_sam2(model_cfg, checkpoint))

with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
    # 提供图片
    image = Image.open('images/a8.jpg')
    image = np.array(image.convert("RGB"))
    plt.figure(figsize=(10, 10))
    plt.imshow(image)
    plt.axis('on')
    plt.show()
    predictor.set_image(image=image) # 查看输入图片并送入预测

    # 提供标签(prompt:point)
    input_point = np.array([[2700, 435]])
    input_label = np.array([1])
    plt.figure(figsize=(10, 10))
    plt.imshow(image)
    show_points(input_point, input_label, plt.gca())
    plt.axis('on')
    plt.show()  
    
    # 开始预测
    masks, scores, logits = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    multimask_output=True,
    )  
    sorted_ind = np.argsort(scores)[::-1]
    masks = masks[sorted_ind]
    scores = scores[sorted_ind]
    logits = logits[sorted_ind]

    show_masks(image, masks, scores, point_coords=input_point, input_labels=input_label, borders=True)

### 如何在 Ubuntu 20.04安装指定版本的 CUDA #### 准备工作 为了确保顺利安装特定版本的 CUDA,在开始之前需确认已正确安装 NVIDIA 显卡驱动程序。可以过命令 `nvidia-smi` 来验证当前系统的 GPU 和其对应的驱动版本,进而判断可以安装的最大 CUDA 版本[^3]。 #### 获取所需资源 访问[NVIDIA官方网站](https://developer.nvidia.com/cuda-toolkit-archive),根据需求选择合适的 CUDA Toolkit 版本下载相应的本地 deb (network) 文件。对于网络受限的情况,建议提前准备好离线安装包。 #### 安装过程 1. **更新软件源** 更新现有的软件列表以获取最新的依赖关系信息。 ```bash sudo apt update && sudo apt upgrade -y ``` 2. **卸载旧版CUDA(如果存在)** 清理任何先前存在的 CUDA 安装以防冲突。 ```bash sudo apt-get --purge remove "*cublas*" "cuda*" ``` 3. **安装新版本CUDA** 使用 dpkg 命令来安装刚刚下载好的 .deb 文件。 ```bash sudo dpkg -i cuda-repo-ubuntu2004_*.deb sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/7fa2af80.pub sudo apt-get update sudo apt-get -y install cuda=<version> ``` 4. **配置环境变量** 编辑 ~/.bashrc 或者 /etc/profile 文件加入如下路径设置: ```bash export PATH=/usr/local/cuda-<version>/bin${PATH:+:${PATH}} export LD_LIBRARY_PATH=/usr/local/cuda-<version>/lib64\ ${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}} source ~/.bashrc ``` 5. **创建符号链接简化调用** 对于多个不同版本共存的情况下,可过建立软链的方式方便切换默认使用的 CUDA 版本。 ```bash cd /usr/local/ sudo ln -sf cuda-<specific_version> cuda ``` 完成以上操作后重启计算机使更改生效,并过 nvcc –version 测试是否成功安装目标版本的 CUDA 工具集[^1]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值