news 2026/6/6 0:34:58

基于OpenAI Clip模型的自动图像分类

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
基于OpenAI Clip模型的自动图像分类

基于OpenAI Clip模型的自动图像分类

一 环境安装

pip install git+https://github.com/openai/CLIP.git
pip install torch torchvision pip install git+https://github.com/openai/CLIP.git pip install pillow matplotlib

二 基本使用

import clip import torchfromPIL import Image import numpyasnpclassCLIPImageClassifier:def__init__(self,model_name="ViT-B/32",device=None):""" 初始化CLIP分类器 Args:model_name:CLIP模型名称,可选:"ViT-B/32","ViT-B/16","ViT-L/14"device:运行设备,"cuda""cpu""""ifdeviceisNone:self.device="cuda"iftorch.cuda.is_available()else"cpu"else:self.device=deviceprint(f"使用设备: {self.device}")print(f"加载模型: {model_name}")# 加载CLIP模型和预处理函数self.model,self.preprocess=clip.load(model_name,device=self.device)self.model.eval()defclassify_image(self,image_path,class_names,top_k=5):""" 对单张图像进行分类 Args:image_path:图像路径 class_names:类别名称列表 top_k:返回top-k预测结果 Returns:包含预测结果的字典列表"""# 加载并预处理图像try:image=Image.open(image_path).convert('RGB')except Exceptionase:print(f"无法加载图像: {e}")returnNoneimage_input=self.preprocess(image).unsqueeze(0).to(self.device)# 处理文本类别text_inputs=torch.cat([clip.tokenize(f"a photo of {c}")forcinclass_names]).to(self.device)# 推理withtorch.no_grad():image_features=self.model.encode_image(image_input)text_features=self.model.encode_text(text_inputs)# 计算相似度image_features=image_features/image_features.norm(dim=-1,keepdim=True)text_features=text_features/text_features.norm(dim=-1,keepdim=True)similarity=(100.0*image_features @ text_features.T).softmax(dim=-1)# 获取top-k结果probs=similarity.cpu().numpy()[0]top_indices=np.argsort(probs)[::-1][:top_k]results=[]foridxintop_indices:results.append({'class':class_names[idx],'probability':float(probs[idx])})returnresultsdefclassify_batch(self,image_paths,class_names,top_k=5):""" 批量分类多张图像""" results=[]forimage_pathinimage_paths:result=self.classify_image(image_path,class_names,top_k)ifresult:results.append({'image_path':image_path,'predictions':result})returnresults# 使用示例if__name__=="__main__":# 初始化分类器classifier=CLIPImageClassifier(model_name="ViT-B/32")# 定义类别(可以是任何你想要的类别)class_names=["cat","dog","bird","car","airplane","beach","mountain","forest","city","ocean","apple","banana","orange","person","bicycle"]# 单张图像分类image_path="test_image.jpg"# 替换为你的图像路径results=classifier.classify_image(image_path,class_names,top_k=3)ifresults:print("\n分类结果:")fori,resultinenumerate(results,1):print(f"{i}. {result['class']}: {result['probability']:.2%}")

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/6 0:27:52

如何轻松使用EB Garamond 12:古典字体与现代设计的完美结合指南

如何轻松使用EB Garamond 12:古典字体与现代设计的完美结合指南 【免费下载链接】EBGaramond12 项目地址: https://gitcode.com/gh_mirrors/eb/EBGaramond12 你是否在为文档、设计或学术写作寻找一款既优雅又专业的免费开源字体?EB Garamond 12正…

作者头像 李华
网站建设 2026/6/6 0:24:19

多维聚合不是GROUP BY:数据变形术与OLAP操作心法

1. 这不是简单的“加总求平均”——多维聚合中的数据变形术到底在解决什么问题?如果你正在处理销售报表、用户行为宽表、IoT设备时序快照,或者哪怕只是Excel里一张带地区、月份、产品线、渠道四个维度的汇总表,那你大概率已经踩进过这个坑&am…

作者头像 李华
网站建设 2026/6/6 0:23:40

okbiye 双维优化方案:从重复率与 AI 痕迹两大维度破解论文定稿难题

okbiye-免费查重复率aigc检测/开题报告/毕业论文/智能排版/文献综述/AI PPT降重复率 - Okbiye智能写作https://www.okbiye.com/reduceAIGC 开篇:论文定稿阶段,双重检测已成毕业生普遍难题 临近毕业季与期刊投稿窗口期,大量创作者卡在论文终稿…

作者头像 李华
网站建设 2026/6/6 0:20:08

如何从 Vivo 文件保险箱恢复已删除的照片

Vivo 设备上的文件安全是一项实用功能,可帮助用户高度安全地保护他们的私人照片和文件。当您从文件安全中删除重要照片时,该怎么办?您知道如何从 Vivo 的文件安全中恢复已删除的照片吗?您可能有一些疑问,并希望获得可行…

作者头像 李华