【发布时间】:2017-06-11 04:55:05
【问题描述】:
我一直在尝试让我的程序放大图像。我在为我的缩放图像分配新空间时遇到了一些问题,但我认为它是固定的。我遇到的问题是,当我试图从我的临时内存持有者发回我的图像时,程序崩溃了。
加载的图片放在我的structImage。像素被放置在
img->pixels,高度为img->height,宽度为img->width。但是我不知道为什么当我将像素从我的tmp2 struct 转移到我的img struct 时程序会崩溃,而当我做相反的事情时它不会崩溃。代码如下:
void makeBigger(Image *img, int scale) {
Image *tmp2;
tmp2 = (Image*)malloc(sizeof(Image));
tmp2->height = img->height*scale;
tmp2->width = img->width*scale;
tmp2->pixels = (Pixel**)malloc(sizeof(Pixel*)*tmp2->height);
for (unsigned int i = 0; i < img->height; i++)
{
tmp2->pixels[i] = (Pixel*)malloc(sizeof(Pixel)*tmp2->width);
for (unsigned int j = 0; j < img->width; j++)
{
tmp2->pixels[i][j] = img->pixels[i][j];
}
}
free(img->pixels);
//scaling up the struct's height and width
img->height *= scale;
img->width *= scale;
img->pixels = (Pixel**)malloc(sizeof(Pixel*)*img->height);
for (unsigned int i = 0; i < tmp2->height; i++)
{
img->pixels[i] = (Pixel*)malloc(sizeof(Pixel)*img->width);
for (unsigned int j = 0; j < tmp2->width; j++)
{
img->pixels[i][j] = tmp2->pixels[i+i/2][j+j/2];
}
}
}
如果您知道如何使最近邻方法起作用,我会很高兴。
编辑:我正在尝试裁剪内部矩形,以便将其放大(缩放)。
Image *tmp = (Image*)malloc(sizeof(Image));
tmp->height = img->height / 2;
tmp->width = img->width / 2;
tmp->pixels = (Pixel**)malloc(sizeof(Pixel*) * tmp->height);
for (unsigned i = img->height / 4 - 1; i < img->height - img->height / 4; i++) {
tmp->pixels[i] = (Pixel*)malloc(sizeof(Pixel) * tmp->width);
for (unsigned j = img->width / 4; j < img->width - img->width / 4; j++) {
tmp->pixels[i][j] = img->pixels[i][j];
}
}
for (unsigned i = 0; i < img->height; i++) {
free(img->pixels[i]);
}
free(img->pixels);
img->height = tmp->height;
img->width = tmp->width;
img->pixels = tmp->pixels;
free(tmp);
【问题讨论】:
-
“程序崩溃”。调试此类问题的方法是使用调试器。
-
是的,我不确定它是关于什么的。似乎 tmp2->pixels 没有得到任何 RGB 值,这看起来很奇怪。但是,程序运行,我没有任何警告。
-
这就是调试器的用途!它允许您逐行遍历代码并检查变量以查看哪里出错了。
-
这显然会导致数组越界访问:
img->pixels[i][j] = tmp2->pixels[i+i/2][j+j/2];。
标签: c image scaling nearest-neighbor