不同框架下验证精度

0.两个txt对比精度

import numpy as np
name = "fc1x_a"
path_pytorch_txt = "/data_1/everyday/1123/img_acc/libtorch_img.txt"
path_caffe_txt = "/data_1/everyday/1123/img_acc/pytorch_img.txt"

pytorch_tensor = np.loadtxt(path_pytorch_txt)
caffe_tensor = np.loadtxt(path_caffe_txt)

diff = pytorch_tensor - caffe_tensor

max_ = np.max(np.abs(diff))
print("max=", max_)

print("none zero=",np.count_nonzero(diff))

print(np.argmax(np.abs(diff)))

1.c++与python的opencv 图像生成txt验证精度

c++

        cv::Mat img = cv::imread(file);
        int rowNumber = img.rows;  //行数
        int colNumber = img.cols*img.channels();  //列数 x 通道数=每一行元素的个数
        std::ofstream out_file("/data_1/everyday/1123/img_acc/libtorch_img.txt");
        //双重循环,遍历所有的像素值
        for (int i = 0; i < rowNumber; i++)  //行循环
        {
            uchar *data = img.ptr<uchar>(i);  //获取第i行的首地址
            for (int j = 0; j < colNumber; j++)   //列循环
            {
                // ---------【开始处理每个像素】-------------
                int pix = int(data[j]);
                out_file << pix << std::endl;
            }
        }
        out_file.close();

这里有个问题需要注意, uchar *data = img.ptr(i); //获取第i行的首地址

这句话当你图像

m_stand.convertTo(m_stand, CV_32FC3);

转为float的时候需要改类型
Python

        img = cv2.imread(path_img)
        tmp_1 = img.reshape(-1)
        np.savetxt("/data_1/everyday/1123/img_acc/pytorch_img.txt",tmp_1)

2.pytorch tensor与libtorch tensor生成txt验证精度

libtorch

bool save_tensor_txt(torch::Tensor tensor_in_,string path_txt)
{
#include "fstream"
    ofstream outfile(path_txt);
    torch::Tensor tensor_in = tensor_in_.clone();
    tensor_in = tensor_in.view({-1,1});
    tensor_in = tensor_in.to(torch::kCPU);

    auto result_data = tensor_in.accessor<float, 2>();

    for(int i=0;i<result_data.size(0);i++)
    {
        float val = result_data[i][0];
//        std::cout<<"val="<<val<<std::endl;
        outfile<<val<<std::endl;

    }

    return true;
}

pytorch

def save_tensor(tensor_in,path_save):
    tensor_in = tensor_in.contiguous().view(-1,1)
    np_tensor = tensor_in.cpu().numpy()
    # np_tensor = np_tensor.view()
    np.savetxt(path_save,np_tensor,fmt='%.12e')
posted @ 2021-11-23 15:58  无左无右  阅读(52)  评论(0编辑  收藏  举报