C++入门&图像处理——图像的读入与读出

    xiaoxiao2021-03-25  142

    打嘎猴!

    前两天写了一个非常简单的小程序,但是出了一个问题卡了很久不知道怎么解决,是关于图片读入那里的,毕竟新手,现在搞清楚了,来写篇博客记录一下。

    首先贴出有错的程序

    #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <iostream> int main (int argc, char *argv[])//输入四个参数,输出图像名称,图像宽,图像高,图像深度 { FILE *out_YUV=NULL; int width=0; int height=0; int depth=0; int i=0; int j=0; unsigned char *count = NULL; if(argc!=5) { printf("input wrong parameter\n"); return 0; } count = (unsigned char*)malloc(width*height*sizeof(unsigned char)); memset (count,0 ,width*height*sizeof(unsigned char)); width = atoi(argv[2]);//atoi作用是把字符串转换成长整型 height = atoi (argv[3]); depth = atoi (argv[4]); for (j=0;j<=4;j++) { for (i=0;i<=4;i++) { count[i] =0; count[i+j*10+5] =100; count[i+j*10+5*10] =200; count[i+j*10+5*10+5] =255; } } out_YUV=fopen(argv[1],"wb"); fwrite(count,sizeof(int),width*height,out_YUV); return 0; }这是一个将yuv图像分割成四块,每块显示不同灰度的简单小程序。运行后会报错,提示说堆已损坏,我从来没遇到过这个问题,查了很久也想不通,后来咨询了自家大神,大神给出的修改版如下

    #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <iostream> int main (int argc, char *argv[])//输入四个参数,输出图像名称,图像宽,图像高,图像深度 { FILE *out_YUV=NULL; int width=0; int height=0; int depth=0; int i=0; int j=0; unsigned char *count = NULL; if(argc!=5) { printf("input wrong parameter\n"); return 0; } width = atoi(argv[2]);//atoi作用是把字符串转换成长整型 height = atoi (argv[3]); depth = atoi (argv[4]); count = (unsigned char*)malloc(width*height*sizeof(unsigned char)); memset (count,0 ,width*height*sizeof(unsigned char)); for (j=0;j<=4;j++) { for (i=0;i<=4;i++) { count[i] =0; count[i+j*10+5] =100; count[i+j*10+5*10] =200; count[i+j*10+5*10+5] =255; } } out_YUV=fopen(argv[1],"wb"); fwrite(count,sizeof(int),width*height,out_YUV); return 0; }可以看出大神只是调整了两句代码的位置。所以我前一篇代码的问题出在,我在将参数赋值给宽和高之前就开辟了随宽高变化的空间并在空间中赋零值,后面也在这个空间中设置灰度值,这样当然会出错。

    只是一个很小的问题我却耽误了很长时间,写出来希望对其他人有帮助,也提醒自己。

    下期见!

    转载请注明原文地址: https://ju.6miu.com/read-6281.html

    最新回复(0)