使用Modelsim进行图像处理算法的仿真时,需要使用到图像的像素信息序列,这里提供一个程序可以把图片中的像素信息读取出来,依赖于OpenCV库运行,这里仅仅是灰度图像而已,读者可以根据自己的需求增加其它颜色通道。
1 #include "opencv2/core/core.hpp" 2 #include "opencv2/opencv.hpp" 3 #include4 using namespace std; 5 using namespace cv; 6 int main(int argc, char *argv[]) 7 { 8 // create by using the constructor 9 Mat image = imread(argv[1],CV_LOAD_IMAGE_GRAYSCALE);10 if(!image.data)11 {12 printf("Error loading %s",argv[1]);13 return -1;14 }15 //cvNamedWindow("show",CV_WINDOW_AUTOSIZE);16 //imshow("show",image);17 //waitKey(0);18 FILE *pfile=fopen("imgdata.txt","wb");19 if(pfile==NULL)20 {21 printf("Error opening imgdata.txt");22 return -1;23 }24 uchar *p;25 for (int i = 0; i < image.rows; i++)26 {27 p = image.ptr < uchar > (i);28 for (int j = 0; j < image.cols; j++)29 {30 fprintf(pfile,"@%x\n",i*image.cols+j);31 fprintf(pfile,"%x\n", p[j]);32 }33 }34 fclose(pfile);35 36 return 0;37 }
命令行参数:extract_data_from_picture.exe src.bmp 读取的文件格式如下:@0ff@1ff@2ff@3ff@4ff@5ff。。。 符合Verilog的读取。读取图像并保存图像数据的Verilog程序如下:`timescale 1 ps / 1 psmodule read_picture; reg [7:0] DataSource[0:320*240-1]; integer save_picture; integer i; initialbegin $readmemh("imgdata.txt",DataSource);//读取图像 save_picture=$fopen("savedata.txt"); for(i=0;i<320*240;i=i+1) begin $fdisplay(save_picture,"%h",DataSource[i]);end $fclose(save_picture);end endmodule 用处理后的图像数据保存在savedata.txt文件中,数据格式如下:dae9f2f9fdfefefffef6fba5191b。。。 为了更直观显示算法的处理效果,我们要把这些数据转换成图像。用以下代码实现:
1 #include "opencv2/core/core.hpp" 2 #include "opencv2/opencv.hpp" 3 #include4 using namespace std; 5 using namespace cv; 6 void help() 7 { 8 printf("use:\ntest.exe rows cols datafile output_image\n"); 9 }10 int main(int argc, char *argv[])11 {12 // create by using the constructor13 if (argc != 5)14 {15 help();16 return - 1;17 }18 int rows = atoi(argv[1]);19 int cols = atoi(argv[2]);20 Mat image(rows, cols, CV_8U);21 if (!image.data)22 {23 printf("Error loading");24 return - 1;25 }26 //cvNamedWindow("show",CV_WINDOW_AUTOSIZE);27 //imshow("show",image);28 //waitKey(0);29 FILE *pfile = fopen(argv[3], "rb");30 if (pfile == NULL)31 {32 printf("Error opening %s", argv[3]);33 return - 1;34 }35 uchar *p;36 for (int i = 0; i < image.rows; i++)37 {38 p = image.ptr < uchar > (i);39 for (int j = 0; j < image.cols; j++)40 {41 fscanf(pfile, "%x\n", &p[j]);42 }43 }44 fclose(pfile);45 46 imwrite(argv[4], image);47 //cvNamedWindow("show",CV_WINDOW_AUTOSIZE);48 //imshow("show",image);49 //waitKey(0);50 return 0;51 }
命令行参数:save_picture.exe 400 212 savedata.txt output.bmp
output.bmp就是我们处理过后的图像了