• huggingface 模型推理几个重要到类


    pipeline

    它可以让您方便地使用预训练的模型进行各种任务¹。当您用pipeline函数创建一个图像分割的pipeline时,它会自动加载和初始化一个SegformerForSemanticSegmentation的实例并且封装了一些预处理和后处理的逻辑,例如将图像转换为张量,将输出转换为分割图等²。您可以直接用pipeline函数对图像或图像列表进行分割,而不需要关心模型的细节。

    SegformerForSemanticSegmentation

    SegformerForSemanticSegmentation是一个具体的模型类,它由一个分层的Transformer编码器和一个轻量级的全MLP解码器组成,可以实现高效的图像分割³。当您用SegformerForSemanticSegmentation.from_pretrained方法加载一个预训练的模型时,它会返回一个SegformerForSemanticSegmentation的实例,但是您需要自己处理输入和输出的数据格式,例如使用AutoFeatureExtractor来提取图像特征,使用torch.argmax来获取分割结果等。

    AutoModel  

    AutoModel.from_pretrained是一个通用的方法,它可以根据给定的模型名称或路径,自动识别模型的类型,并返回一个相应的模型类的实例³。例如,如果给定的模型名称是"bert-base-chinese",那么这个方法会返回一个BertModel的实例,它是一个用于文本表示的模型。这个方法可以处理多种不同类型的模型,但是它不能处理特定任务的模型,例如图像分割或序列标注。

    本人实验代码:

    1. import cv2
    2. import PIL.Image as Image
    3. import numpy as np
    4. from transformers import pipeline
    5. model_dir = '/speed/speed/code/DECA/face_parsing_model/face-parsing'
    6. image_path = "/speed/speed/code/DECA/TestSamples/examples/6.png"
    7. pipe = pipeline("image-segmentation", model="jonathandinu/face-parsing")
    8. img = Image.open(image_path)
    9. # 加载图片
    10. # img = cv2.imread(image_path)
    11. # 预处理图片
    12. # img = cv2.resize(img, (256, 256))
    13. # img = img.astype(np.float32) / 255.0
    14. # 使用模型分割图片
    15. result = pipe(img)
    16. # Load model directly
    17. from transformers import AutoFeatureExtractor, SegformerForSemanticSegmentation
    18. from transformers import AutoFeatureExtractor, AutoModel
    19. model_dir = '/speed/speed/code/DECA/face_parsing_model/face-parsing'
    20. image_path = "/speed/speed/code/DECA/TestSamples/examples/6.png"
    21. # extractor = AutoFeatureExtractor.from_pretrained("jonathandinu/face-parsing")
    22. # model = SegformerForSemanticSegmentation.from_pretrained("jonathandinu/face-parsing")
    23. extractor = AutoFeatureExtractor.from_pretrained(model_dir)
    24. model = SegformerForSemanticSegmentation.from_pretrained(model_dir)
    25. img = Image.open(image_path)
    26. # 加载图片
    27. img = cv2.imread(image_path)
    28. img = cv2.resize(img, (1024, 1024))
    29. inputs = extractor(img, return_tensors="pt")
    30. outputs = model(**inputs).logits
    31. print('')

  • 相关阅读:
    汽车OBD2蓝牙诊断仪解决方案程序开发
    JS如何判断对象为空?以及各自的缺点。
    Yum 和 Rpm 安装包管理软件的区别 - 分布式网络包仓库管理 - 手动包管理
    Go垃圾回收
    电动平衡车UL2272测试哪些项目
    佳音通讯400电话申请-0选号费-0月租-0开户费
    element el-input 二次封装
    004 Python UDP网络通信
    迅为恩智浦iTOP-IMX6开发平台
    图库 | 图存储的基础概念
  • 原文地址:https://blog.csdn.net/u010087338/article/details/133965965