快速使用OpenVINO的 Anomalib实现训练和推理

快速使用OpenVINO的 Anomalib实现训练和推理

代码


import os
from pathlib import Path
from anomalib.data import MVTec
from anomalib import TaskType
from anomalib.deploy import ExportType, OpenVINOInferencer
from anomalib.engine import Engine
from anomalib.models import Padim, Patchcore,Stfpm
from matplotlib import pyplot as plt
from anomalib.data.utils import read_image
import time



def  train_and_export_model ( object_type, model, transform= None ): 
    """
    训练并导出MVTec数据集上的模型为OpenVINO格式。
    
    Args:
        object_type (str): MVTec数据集的类别,如'bottle'、'cap'等。
        model (torch.nn.Module): 待训练的深度学习模型。
        transform (Callable, optional): 数据预处理函数,默认为None。
    
    Returns:
        str: 导出模型保存的根目录路径。
    
    """

    
    datamodule = MVTec()
    datamodule.category=object_type
    engine = Engine(task=TASK) 
    engine.fit(model=model, datamodule=datamodule) 

    ## 将模型导出为 OpenVINO 格式以进行快速推理
    engine.export( 
        model=model, 
        export_type=ExportType.OPENVINO, 
    ) 
    print(f"Model save to {engine.trainer.default_root_dir}).") 
    return  engine.trainer.default_root_dir




if __name__ == '__main__':

    # Initialize the datamodule, model and engine
    OBJECT = "transistor"  ## 要训练的对象
    TASK = TaskType.SEGMENTATION ## 模型的任务类型

    # model = Padim()
    # model =Patchcore()
    # model=Stfpm()
    
    # train_and_export_model(OBJECT, model)

    output_path=Path("results/Padim/MVTec/transistor/latest")
    openvino_model_path = output_path / "weights" / "openvino" / "model.bin"
    metadata_path = output_path / "weights" / "openvino" / "metadata.json"
    print(openvino_model_path.exists(), metadata_path.exists())

    inferencer = OpenVINOInferencer(
        path=openvino_model_path,  # Path to the OpenVINO IR model.
        metadata=metadata_path,  # Path to the metadata file.
        device="AUTO",  # We would like to run it on an Intel CPU.
    )

    # 定义文件夹路径
    folder_path = "./datasets/MVTec/transistor/test/bent_lead/"

    # 获取文件夹中所有的.png文件
    png_files = [f for f in os.listdir(folder_path) if f.endswith('.png')]

    for file_name in png_files:
         
        image = read_image(path=folder_path +'/'+ file_name)

        # 记录开始时间
        start_time = time.time()
        predictions = inferencer.predict(image=image)
        # 记录结束时间
        end_time = time.time()

        # 计算耗时
        elapsed_time = end_time - start_time
        print(f"Prediction took {elapsed_time:.4f} seconds.")
        print(predictions.pred_score, predictions.pred_label)
        # 创建一个新的图形窗口
        fig, axs = plt.subplots(1, 3, figsize=(18, 8))  # 创建一个1行3列的子图网格

        # 原始图像
        axs[0].imshow(image)
        axs[0].set_title('Original Image')
        axs[0].axis('off')  # 关闭坐标轴

        # 热图
        axs[1].imshow(predictions.heat_map, cmap='hot', interpolation='nearest')
        axs[1].set_title('Heat Map')
        axs[1].axis('off')  # 关闭坐标轴

        # 预测掩模
        axs[2].imshow(predictions.pred_mask, cmap='gray', interpolation='nearest')
        axs[2].set_title('Predicted Mask')
        axs[2].axis('off')  # 关闭坐标轴


        # 添加文本信息到图形的上方中间位置
        fig_text_x = 0.1  # x坐标在图形宽度的中心位置
        fig_text_y = 0.95  # y坐标稍微靠近图形的顶部,避免与子图重叠
        fig.text(fig_text_x, fig_text_y,
                f'Prediction Time: {elapsed_time:.4f} s\n'
                f'Predicted Class: {predictions.pred_label}\n'
                # f'Score: {predictions.pred_score:.4f}\n'
                f'Threshold: {predictions.pred_score:.4f}' if hasattr(predictions, 'pred_score') else '',
                ha='left', va='center', fontsize=12,
                bbox=dict(boxstyle="round", fc="w", ec="0.5", alpha=0.5))  

        # 显示整个图形
        plt.tight_layout()  # 调整子图间的间距
        plt.show()
    print("Done")

    

运行的结果截图

运行结果

### 使用 Anomalib OpenVINO 在 C++ 中进行异常检测 为了在 C++ 中利用 Anomalib 进行异常检测并借助 OpenVINO 加速推理过程,可以遵循以下流程: #### 准备工作 确保已经成功安装了 Anomalib训练了一个模型。接着导出该模型为 ONNX 格式以便于集成到 C++ 应用程序中。 对于图像数据,在将其传递给 ONNX 模型前需要执行特定的预处理操作[^3]。这通常涉及调整大小、归一化以及转换通道顺序等步骤来匹配训练期间使用的配置。 #### 预处理阶段 ```cpp #include <opencv2/opencv.hpp> cv::Mat preprocessImage(const cv::String& imagePath, int inputWidth, int inputHeight) { // Load image from file path. cv::Mat img = cv::imread(imagePath); // Resize to match model's expected dimensions and normalize pixel values between [0., 1.] range. cv::resize(img, img, cv::Size(inputWidth, inputHeight)); img.convertTo(img, CV_32F, 1 / 255.); // Change channel order from BGR (default in OpenCV) to RGB which is commonly used by models like those trained with PyTorch/TensorFlow etc.. std::vector<cv::Mat> channels; split(img, channels); // Split into separate color planes. cv::merge(std::vector<cv::Mat>{channels[2], channels[1], channels[0]}, img); // Merge them back but swap R & B. return img; } ``` 此函数负责加载图片文件,并对其进行必要的尺寸缩放颜色空间变换以适应目标神经网络的要求。 #### 推理部分 一旦完成了上述准备工作,则可以通过调用 OpenVINO 的 API 来运行推断任务。下面是一个简单的例子展示如何设置 Inference Engine 并获取预测结果: ```cpp // Assume `ie` has been initialized as an instance of ie_core class. auto network = ie.ReadNetwork("path/to/model.onnx"); network.setBatchSize(1); // Create executable network on CPU device. auto execNet = ie.LoadNetwork(network, "CPU"); // Prepare inputs according to the preprocessed data format required by your specific anomaly detection task. InferRequest infer_request = execNet.CreateInferRequest(); Blob::Ptr input_blob = infer_request.GetBlob("input_name"); // Replace 'input_name' accordingly based on actual model definition. memcpy(input_blob->buffer().as<float*>(), processed_image.data, sizeof(float)*image_size); infer_request.Infer(); // Extract outputs after inference completes successfully. std::map<std::string, Blob::CPtr> output_blobs = infer_request.OutputBlobs(); for(auto const& item : output_blobs){ auto blob_data = item.second->buffer().as<const float*>(); // Process each element within this tensor... } ``` 这段代码片段展示了怎样创建一个基于指定设备(这里假设是 CPU)上的可执行版本的神经网络实例;随后准备输入张量并将它赋值给即将启动的任务;最后提取计算所得的结果供进一步分析使用。 #### 后处理与可视化 当获得了来自模型的原始输出之后,还需要做一些额外的工作才能得到直观易懂的形式——比如绘制热力图。这部分逻辑取决于具体的业务需求技术栈的选择,但一般会涉及到对概率分布或其他特征向量做适当映射从而形成视觉上友好的表示形式。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值