读取CSV至数组(C语言)

模型推理部署过程中,预使用C语言读取一张0~255的灰度图(jpg)至数组中,但由于jpg是压缩后的图像,无法使用C直接简单的读取(需要进行解码,如果能使用opencv另当别论),

故而选择在保存图片的过程中将其保存为csv文件,方便读取,但是虽然我已经使用了np.round将img数组转为了整数,print打印也显示整数,但使用如下语句保存

np.savetxt(save_path + '/' + name[0] + '.csv', img , delimiter=",")

结果发现其默认为科学计数法保存,不仅占空间,而且C语言无法正确读取,但一张352*352的灰度图保存为.csv居然有3Mb就离谱

读取CSV至数组(C语言)_第1张图片

 print打印也是ok的读取CSV至数组(C语言)_第2张图片

读取CSV至数组(C语言)_第3张图片

最后观察源码发现,默认的fmt参数是%18e,只需要将其调整为整数%d保存即可

@array_function_dispatch(_savetxt_dispatcher)
def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
            footer='', comments='# ', encoding=None):
    """
    Save an array to a text file.

    Parameters
    ----------
    fname : filename or file handle
        If the filename ends in ``.gz``, the file is automatically saved in
        compressed gzip format.  `loadtxt` understands gzipped files
        transparently.
    X : 1D or 2D array_like
        Data to be saved to a text file.
    fmt : str or sequence of strs, optional
        A single format (%10.5f), a sequence of formats, or a
        multi-format string, e.g. 'Iteration %d -- %10.5f', in which
        case `delimiter` is ignored. For complex `X`, the legal options
        for `fmt` are:

        * a single specifier, `fmt='%.4e'`, resulting in numbers formatted
          like `' (%s+%sj)' % (fmt, fmt)`
        * a full string specifying every real and imaginary part, e.g.
          `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns
        * a list of specifiers, one per column - in this case, the real
          and imaginary part must have separate specifiers,
          e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns

 转为整数保存之后大小为483k,合

读取CSV至数组(C语言)_第4张图片

 

还是要看源码!

还是要看源码!

还是要看源码!

重要的事说三遍!!!

接下来是C语言读取:

有关细节如何读取,原理请参见这篇文章

int main{
	FILE *fp1 = fopen("0001.csv", "r");
	if (fp1 == NULL) {
		fprintf(stderr, "fopen() failed.\n");
		exit(EXIT_FAILURE);
	}
	int img[352*352] = {0};
	char row[35200];
	char *token;
	
	for (int ii = 0; ii < 352; ii++)
	{
		if (fgets(row, 352000, fp1) != NULL) {
			token = strtok(row, ",");
			for(int jj = 0; jj < 352; jj++)
			{
				if (token != NULL) {
					img[ii*352 + jj] = atoi(token);
					token = strtok(NULL, ",");
				}
			}
			
		}	
	}
	
	for(int i=0;i<352;i++)
	{
		for(int j=0;j<352;j++)
		{
			printf("%d ", img[i*352 + j]);	
		}
		printf("\n");
	}
	
	fclose(fp1);
    return 0;
}

读取CSV至数组(C语言)_第5张图片

读取结束 打印对比  完全ok! 

你可能感兴趣的:(c语言,opencv,python)