liyun211 2024-04-26 15:17 采纳率: 33.3%
浏览 5
已结题

transformer 目标检测代码找错

我刚学习 transformers,在Windows 上 安装了pytorch 和transformers的4.26.1 版本,
测试 from transformers import DetrImageProcessor, DetrForObjectDetection 成功!
现在我想运行一个 目标检测示例,代码 是从 https://hf-mirror.com/ 找的,如下:


from transformers import pipeline
from transformers import DetrImageProcessor, DetrForObjectDetection
import torch
from PIL import Image
import requests

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)

processor = DetrImageProcessor.from_pretrained("C:\\Users\\hello\\detr_resnet_50", revision="no_timm")
model = DetrForObjectDetection.from_pretrained("C:\\Users\\hello\\detr_resnet_50", revision="no_timm")

inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)

target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]

for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
    box = [round(i, 2) for i in box.tolist()]
    print(
            f"Detected {model.config.id2label[label.item()]} with confidence "
            f"{round(score.item(), 3)} at location {box}"
    )

由于我预先下载了 facebook/detr-resnet-50 模型到本地的 C:\Users\hello\detr_resnet_50 目录下,所以上述代码中的 from_pretrained("C:\Users\hello\detr_resnet_50", revision="no_timm") 表示我自己的 路径,其它地方都是照抄 https://hf-mirror.com,

在python的pycharm 环境下,http://images.cocodataset.org/val2017/000000039769.jpg 的 图片能读取出来,然后长时间没有反应,也没有报错,就是没任何反应,请大家帮助找找原因。

  • 写回答

5条回答 默认 最新

  • 阿里嘎多学长 2024-04-26 15:17
    关注

    以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:


    【问题概括】:用户在使用transformers库进行目标检测时遇到了问题,代码执行后没有反应,没有报错,但也没有输出结果。

    【问题出现原因】:问题可能的原因包括但不限于:

    1. 代码中可能存在逻辑错误或配置问题。
    2. 模型路径或配置可能不正确。
    3. 代码可能缺少必要的错误处理机制,导致程序在遇到问题时没有给出提示。

    【问题解决方案】:

    1. 首先,检查模型路径是否正确,确保C:\\Users\\hello\\detr_resnet_50目录中包含了正确的模型文件。
    2. 确保模型路径中没有使用相对路径,因为from_pretrained方法可能需要绝对路径。
    3. 检查网络请求是否成功,图片是否正确加载。
    4. 增加错误处理机制,以便在出现问题时能够及时发现并解决。

    【提供代码】: 以下是修改后的代码,增加了错误处理机制,并确保了模型路径的正确性。

    from transformers import pipeline, DetrImageProcessor, DetrForObjectDetection
    from PIL import Image
    import requests
    import torch
    
    # 确保模型路径是正确的绝对路径
    model_path = "C:\\Users\\hello\\detr_resnet_50"
    
    # 尝试从网络加载图片
    try:
        url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 确保请求成功
        image = Image.open(response.raw)
    except requests.exceptions.RequestException as e:
        print(f"Error loading image: {e}")
        exit()
    
    # 尝试加载模型和处理器
    try:
        processor = DetrImageProcessor.from_pretrained(model_path, revision="no_timm")
        model = DetrForObjectDetection.from_pretrained(model_path, revision="no_timm")
    except Exception as e:
        print(f"Error loading model or processor: {e}")
        exit()
    
    # 进行目标检测
    try:
        inputs = processor(images=image, return_tensors="pt")
        outputs = model(**inputs)
        target_sizes = torch.tensor([image.size[::-1]])
        results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
        
        for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
            box = [round(i, 2) for i in box.tolist()]
            print(
                f"Detected {model.config.id2label[label.item()]} with confidence "
                f"{round(score.item(), 3)} at location {box}"
            )
    except Exception as e:
        print(f"Error during object detection: {e}")
    
    

    【代码运行方式】:

    1. 确保你的环境中安装了transformers, torch, PIL, 和requests库。
    2. 将上述代码复制到Python环境中运行。

    【代码预期运行结果】: 如果一切正常,代码将输出检测到的对象的类别、置信度和边界框坐标。

    【推荐相关链接】:

    • transformers库官方文档:https://huggingface.co/transformers/
    • PyTorch官方文档:https://pytorch.org/docs/stable/index.html
    • 如何使用requests库:https://docs.python-requests.org/en/latest/
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 5月6日
  • 已采纳回答 4月28日
  • 创建了问题 4月26日

悬赏问题

  • ¥15 关于SSH项目中JSP表单获取的问题
  • ¥50 关于在matlab上对曲柄摇杆机构上一点的运动学仿真
  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥20 公众号如何实现点击超链接后自动发送文字
  • ¥15 用php隐藏类名和增加类名
  • ¥15 算法设计与分析课程的提问
  • ¥15 用MATLAB汇总拟合图
  • ¥15 智能除草机器人方案设计