为毛我要干这件事,把一张jpg图片转成bgr(注意顺序是bgr)二进制文件?最近在弄华为Hi3519AV100开发板上的一些深度学习的样例程序,没想到它的输入文件不是普通的jpg,而是bgr格式的二进制文件,所以不是我闲得蛋疼。还别说,这样确实是大大节省了空间。我一张3.8M的测试文件(test.jpg),转成二进制后为276K。
源代码:
#include
#include
#include
#include "opencv2/imgcodecs/imgcodecs_c.h"
typedef unsigned char U_CHAR;
int main(int argc, char* argv[]) {
if(argc != 3) {
fprintf(stderr, "Usage:%s [src_file] [out_file]\n", argv[0]);
exit(-1);
}
IplImage *img = 0;
const char *filename = argv[1];
const char *outname = argv[2];
int flag = 1;
img = cvLoadImage(filename, flag);
if (img == 0) {
printf("Load image error\n");
return -1;
}
U_CHAR *data = (U_CHAR*)img->imageData;
int step = img->widthStep;
printf("widthStep: %d, height: %d, width: %d\n",
step, img->height, img->width);
FILE *fp = fopen(outname, "wb");
int h = img->height;
int w = img->width;
int c = img->nChannels;
//注意遍历顺序
for (int k=0; k
编译:
g++ cvt2bgr.c -o cvt2bgr `pkg-config --libs --cflags opencv` -Wall
pkg-config --libs --cflgas opencv是作甚?因为代码里面要用到opencv,所以需要在编译命令中给出库文件和头文件所在路径。为了不过于冗长,直接用一条命令代替了,展开来看就是下面这个样子的:
[zuosi@localhost]$pkg-config --cflags opencv
-I/usr/local/include/opencv -I/usr/local/include
[zuosi@localhost]$pkg-config --libs opencv
-L/usr/local/lib -lopencv_cudabgsegm -lopencv_cudaobjdetect -lopencv_cudastereo -lopencv_dnn -lopencv_ml -lopencv_shape -lopencv_stitching -lopencv_cudafeatures2d -lopencv_superres -lopencv_cudacodec -lopencv_videostab -lopencv_cudaoptflow -lopencv_cudalegacy -lopencv_calib3d -lopencv_features2d -lopencv_highgui -lopencv_videoio -lopencv_photo -lopencv_imgcodecs -lopencv_cudawarping -lopencv_cudaimgproc -lopencv_cudafilters -lopencv_video -lopencv_objdetect -lopencv_imgproc -lopencv_flann -lopencv_cudaarithm -lopencv_core -lopencv_cudev
为了检验一下代码的正确性,我转一个华为给的样例图片,然后对比一下md5。
[zuosi@localhost test]$file double_roipooling_224_224.jpg
double_roipooling_224_224.jpg: JPEG image data,
JFIF standard 1.01, resolution (DPI),
density 72x72, segment length 16, baseline, precision 8,
224x224, frames 3
[zuosi@localhost test]$md5sum double_roipooling_224_224.*
bfadf0b2d90fe3b5ee7caeb581e199c5 double_roipooling_224_224.bgr
ee577e3a1415ea677104987b46b0d2a4 double_roipooling_224_224.jpg
选了上面double_roipooling_224_224.jpg这个文件,他的尺寸是224x224,正好华为给了这个尺寸的bgr,所以可以拿来对比验证。把代码编译好后,执行以下命令:
[zuosi@localhost test]$./cvt2bgr double_roipooling_224_224.jpg my_test.bgr
widthStep: 672, height: 224, width: 224
[zuosi@localhost test]$md5sum my_test.bgr
bfadf0b2d90fe3b5ee7caeb581e199c5 my_test.bgr
这里my_test.bgr是用上面的代码生成的,可见其md5与华为给的md5是一样的,都是bfadf0b2d90fe3b5ee7caeb581e199c5。