【代码复现】GroundingDINO 全网最详细的保姆级教程

该文章已生成可运行项目,

文章性质:实操笔记 📖

代码来源:https://github.com/IDEA-Research/GroundingDINO

冷知识+1:小伙伴们不经意的 点赞 👍🏻 与 收藏 ✨ 可以让作者更有创作动力! 

目录

一、AutoDL 租用远程服务器

1、获取 SSH 登录

2、配置 SSH 连接

二、VSCode 配置项目环境(远程)

1、初始化 Conda 环境

2、配置项目的远程环境

① 设置环境变量

② 克隆项目代码

③ 配置项目环境

④ 运行 test.py

🎁 问题彩蛋-1 

🔮 解决方案-1

🎁 问题彩蛋-2

🔮 解决方案-2

三、利用 GroundingDINO 裁剪图像


一、AutoDL 租用远程服务器

1、获取 SSH 登录

在 AutoDL 的算力市场按照自身需求租用合适的服务器:

2、配置 SSH 连接

在前面几次项目中我们使用的是 Tabby 工具,但最近改为使用 VSCode 啦 ( •̀ ω •́ )✧

Step01:单击左下角的按钮 >< ,选择【连接到主机】。 

Step02:选择【添加新的SSH主机】,输入 AutoDL 平台提供的 SSH 登录指令。

Step03:连接远程服务器后,在终端窗口输入 AutoDL 平台提供的 SSH 密码。

Step04:单击展开侧边的资源管理器,打开远程服务器上的文件夹,这里我直接选择以 root 为根目录。

二、VSCode 配置项目环境(远程)

1、初始化 Conda 环境

Step01:进入远程服务器终端命令窗口后,我们需要先更新 bashrc 中的环境变量:

conda init bash && source /root/.bashrc

具体说明:conda init bash 会将 Conda 的初始化配置添加到 .bashrc 文件中,而 source /root/.bashrc 则确保这些配置在当前的终端会话中立即生效,从而可以在 Bash shell 中使用 Conda 命令,例如 conda activate、conda install 等。这通常是第一次安装 Conda 或者在更改了 Conda 配置之后需要执行的步骤。 

2、配置项目的远程环境

① 设置环境变量

作者提到如果有 CUDA 环境,需要确保 CUDA_HOME 已经设置环境变量,如果没有 CUDA,编译将以 CPU-only 模式进行。

需要严格按照安装步骤操作,否则会产生:NameError: name '_C' is not defined

注:如果发生这种情况,请通过重新克隆 g​​it 重新安装 GroundingDINO,然后再次执行所有安装步骤。

Step01:使用 which nvcc 命令查看 CUDA 工具包的安装路径,如果是 /usr/local/cuda/bin/nvcc 则:

export CUDA_HOME=/usr/local/cuda

Step02:然后 source bashrc 文件并检查 CUDA_HOME:

source ~/.bashrc
echo $CUDA_HOME

② 克隆项目代码

根据 GroundingDINO 项目代码的操作文档按步骤进行,首先用 git clone 克隆项目到远程服务器:

cd /root/autodl-tmp
git clone https://github.com/IDEA-Research/GroundingDINO.git

③ 配置项目环境

新建并激活虚拟环境,再按照 requirements.txt 文件配置环境:

conda create -n groundingdino python=3.8
conda activate groundingdino
pip install -r requirements.txt

其实作者提供的命令是在 GroundingDINO 项目目录下 pip install -e .

cd /root/autodl-tmp/GroundingDINO
pip install -e .

④ 运行 test.py

Step01:下载预训练的模型权重:

mkdir weights
cd weights
wget -q https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
cd ..

Step02:运行测试代码:

cd /root/autodl-tmp/GroundingDINO
python test.py

具体代码:test.py

from groundingdino.util.inference import load_model, load_image, predict, annotate
import cv2

model = load_model("groundingdino/config/GroundingDINO_SwinT_OGC.py", "weights/groundingdino_swint_ogc.pth")
IMAGE_PATH = "weights/dog-3.jpeg"
TEXT_PROMPT = "chair . person . dog ."
BOX_TRESHOLD = 0.35
TEXT_TRESHOLD = 0.25

image_source, image = load_image(IMAGE_PATH)

boxes, logits, phrases = predict(
    model=model,
    image=image,
    caption=TEXT_PROMPT,
    box_threshold=BOX_TRESHOLD,
    text_threshold=TEXT_TRESHOLD
)

annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
cv2.imwrite("annotated_image.jpg", annotated_frame)
🎁 问题彩蛋-1 

在运行代码的过程中遇到了 huggingface 的网络连接问题,如图所示:

🔮 解决方案-1

在终端窗口执行命令:source /etc/network_turbo

🎁 问题彩蛋-2

在运行代码的过程中还遇到了 CUDA 版本不匹配的问题,如图所示:

🔮 解决方案-2

首先需要验证所谓的版本不一致问题,然后想办法将版本进行统一。

Step01:查看 nvcc 的版本,确定其对应的 CUDA version 为 11.8。

nvcc --version

Step02:查看 torch 的版本,确定其对应的 CUDA version 为 12.1。

import torch
print(torch.__version__)
print(torch.version.cuda)

Step03:卸载当前的 torch 和 torchvision

pip uninstall torch
pip uninstall torchvision

Step04:根据 pytorch 官网提供的命令重新安装相应版本的 torch 和 torchvision(cu118):

pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

Step05:将二者的 CUDA 版本统一后,我发现可以成功 pip install -e . 啦 (๑•̀ㅂ•́)و✧

pip install -e .

三、利用 GroundingDINO 裁剪图像

我们还可以借助 GroundingDINO 来帮助我们进行图像的裁剪,如图所示:

具体代码:segment.py

import os
import time
from groundingdino.util.inference import load_model, load_image, predict
import cv2
import torch
from torchvision.ops import box_convert

def save_cropped_images(image, boxes, image_name, output_folder):
    os.makedirs(output_folder, exist_ok=True)
    h, w, _ = image.shape
    boxes = boxes * torch.tensor([w, h, w, h])
    xyxy_boxes = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").numpy()

    for i, box in enumerate(xyxy_boxes):
        x_min, y_min, x_max, y_max = map(int, box)
        cropped_image = image[y_min:y_max, x_min:x_max]
        # Ensure the color channels are in BGR order for OpenCV
        cropped_image_bgr = cv2.cvtColor(cropped_image, cv2.COLOR_RGB2BGR)
        cv2.imwrite(f"{output_folder}/{image_name}_cropped_{i}.jpg", cropped_image_bgr)

def process_image(image_path, model, output_folder, box_threshold=0.35, text_threshold=0.25):
    image_source, image = load_image(image_path)
    try:
      boxes, logits, phrases = predict(
          model=model,
          image=image,
          caption=TEXT_PROMPT,
          box_threshold=box_threshold,
          text_threshold=text_threshold
      )
    except RuntimeError as e:
      print(f"RuntimeError: {e}")

    # Get the image name without extension
    image_name = os.path.splitext(os.path.basename(image_path))[0]

    # Save cropped images with image name included
    save_cropped_images(image_source, boxes, image_name, output_folder)

def process_images_in_folder(folder_path, model, box_threshold=0.35, text_threshold=0.25):
    folder_name = os.path.basename(folder_path.rstrip('/'))
    output_folder = os.path.join("./animals_classify/Cropped_Dataset", folder_name)
    print(f"{folder_name}, cropping.")
    # Start timer for processing this folder
    start_time = time.time()
    
    for filename in os.listdir(folder_path):
        if filename.endswith(".jpg") or filename.endswith(".png") or filename.endswith(".jpeg"):
            image_path = os.path.join(folder_path, filename)
            process_image(image_path, model, output_folder, box_threshold, text_threshold)
    
    # End timer for processing this folder
    folder_processing_time = time.time() - start_time
    process_images_in_folder.total_time += folder_processing_time
    
    print(f"{folder_name}, cropped. Time taken: {folder_processing_time:.2f} seconds")
    print(f"Total time taken so far: {process_images_in_folder.total_time:.2f} seconds")

# Initialize the total time taken to 0
process_images_in_folder.total_time = 0.0

# Configuration and model loading
model = load_model("groundingdino/config/GroundingDINO_SwinT_OGC.py", "weights/groundingdino_swint_ogc.pth")
TEXT_PROMPT = "canine"
BOX_THRESHOLD = 0.35
TEXT_THRESHOLD = 0.25

FOLDERS_PATH = "./animals_classify/Raw_Dataset"
for FOLDER_Name in os.listdir(FOLDERS_PATH):
	FOLDER_PATH = os.path.join(FOLDERS_PATH, FOLDER_Name)
	# Process all images in the folder
	process_images_in_folder(FOLDER_PATH, model, BOX_THRESHOLD, TEXT_THRESHOLD)
本文章已经生成可运行项目
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

作者正在煮茶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值