RemoteCLIP 开源项目教程
RemoteCLIP项目地址:https://gitcode.com/gh_mirrors/re/RemoteCLIP
项目介绍
RemoteCLIP 是一个用于遥感领域的视觉语言基础模型,由 Fan Liu 等人开发。该模型在 IEEE Transactions on Geoscience and Remote Sensing (TGRS) 上发表。RemoteCLIP 通过对比语言图像预训练技术,能够在多个下游任务中表现出色,包括零样本图像分类、线性探测、k-NN 分类、少样本分类、图像文本检索和对象计数。
项目快速启动
环境准备
首先,确保你已经安装了必要的依赖库:
pip install torch torchvision
pip install openclip-torch
下载模型
从 GitHub 仓库下载预训练模型:
git clone https://github.com/ChenDelong1999/RemoteCLIP.git
cd RemoteCLIP
加载模型
使用以下代码加载 RemoteCLIP 模型:
import open_clip
model, _, preprocess = open_clip.create_model_and_transforms('ViT-B-32', pretrained='remoteclip')
示例代码
以下是一个简单的示例,展示如何使用 RemoteCLIP 进行图像文本检索:
from PIL import Image
import requests
# 加载图像
image = preprocess(Image.open(requests.get(url, stream=True).raw)).unsqueeze(0)
# 编码图像
with torch.no_grad(), torch.cuda.amp.autocast():
image_features = model.encode_image(image)
# 编码文本
text = open_clip.tokenize(["a remote sensing image of a forest"])
with torch.no_grad(), torch.cuda.amp.autocast():
text_features = model.encode_text(text)
# 计算相似度
similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
print(similarity)
应用案例和最佳实践
零样本图像分类
RemoteCLIP 可以在没有显式训练的情况下对遥感图像进行分类。例如,你可以使用以下代码对遥感图像进行分类:
# 假设你有一个遥感图像
image_path = 'path_to_your_image.jpg'
image = preprocess(Image.open(image_path)).unsqueeze(0)
# 编码图像
with torch.no_grad(), torch.cuda.amp.autocast():
image_features = model.encode_image(image)
# 定义类别
classes = ["forest", "water", "urban"]
text = open_clip.tokenize(classes)
# 编码文本
with torch.no_grad(), torch.cuda.amp.autocast():
text_features = model.encode_text(text)
# 计算相似度
similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
values, indices = similarity[0].topk(1)
print(f"The image is classified as: {classes[indices[0]]}")
图像文本检索
RemoteCLIP 还可以用于图像文本检索任务。以下是一个示例:
# 假设你有一个遥感图像和一个查询文本
image_path = 'path_to_your_image.jpg'
query_text = "a remote sensing image of a forest"
# 加载图像
image = preprocess(Image.open(image_path)).unsqueeze(0)
# 编码图像
with torch.no_grad(), torch.cuda.amp.autocast():
image_features = model.encode_image(image)
# 编码文本
text = open_clip.tokenize([query_text])
with torch.no_grad(), torch.cuda.amp.autocast():
text_features = model.encode_text(text)
# 计算相似度
similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
print(f"Similarity score: {similarity[0][0]}")
典型生态项目
Autodistill
Autodistill