2014-09-21 75 views
0

我正在做最接近的插值算法来在C++中缩放一个.rgb格式的图像。图像的原始分辨率是352x288。我对该算法的实现很奇怪。当我将它缩放到其原始尺寸的一半或将其扩大到原始尺寸的2倍时,它工作得很好。但是,当我想要将其缩放到其他一些因素(如0.8或1.2)时,显示屏显示不正常。图像处理 - 最近的插值算法执行奇怪

这里是我的一段代码:

void MyImage::Sampling(int destWidth, int destHeight){ 
//Use nearest sampling 
char* temp = new char[destWidth * destHeight * 3]; 

double scale_w = Width/(double)destWidth; 
double scale_h = Height/(double)destHeight; 

int tSrcH = 0, tSrcW = 0; 
int index_src = 0, index_dest = 0; 

for(int i = 0; i < destHeight; ++i){ 
    //Find the nearest y_pos in the original image 
    tSrcH = (int)(scale_h * i + 0.5); 
    for(int j = 0; j < destWidth; ++j){ 
     //Find the nearest y_pos in the original image 
     tSrcW = (int)(scale_w * j + 0.5); 

     //Get the data in the original image 
     //and assign it to the new image 
     index_src = getIndex(tSrcW, tSrcH, Width); 
     index_dest = getIndex(j, i, destWidth); 

     //B, G, R 
     temp[3 * index_dest]  = Data[3 * index_src]; 
     temp[3 * index_dest + 1] = Data[3 * index_src + 1]; 
     temp[3 * index_dest + 2] = Data[3 * index_src + 2]; 
    } 
} 

Width = destWidth; 
Height = destHeight; 

delete [] Data; 
Data = NULL; 

Data = new char[destWidth * destHeight * 3]; 

for(int i = 0; i < destWidth * destHeight * 3; ++i){ 
    Data[i] = temp[i]; 
} 

delete [] temp; 
} 

的原始图像

enter image description here

半尺寸图像

enter image description here

0.8缩放图像

enter image description here

任何建议或解决这种情况?谢谢。

+0

我也没有看到直接的解决方案。你确定你的输入是可以的吗?而不是在该操作或s.th中更新的实时/易失性缓冲区?另外,确保'getIndex(j,i,w)'真正尊重给定的w,并且不会恢复到成员'Width'或期望交换j和i(我会以相反方式完成)。最后,最后你的复制操作看起来没用,只是'delete [] Data;''和'Data = temp;'。 – Thomas 2014-09-21 22:55:03

+0

@Thomas嗨,感谢您的回复,我试图调试一整天,但几乎看不到任何错误的编码。我做了很多不同的输入宽度和高度值的实验。我发现某些宽度值可以正确生成缩放图像,无论高度值是多少,其他值都不能。但我仍然不知道这种奇怪问题的起因是什么。 – Zengrui 2014-09-22 01:06:52

+0

@Thomas我看到一种模式,当宽度可以除以4,那么图像是好的... – Zengrui 2014-09-22 01:29:40

回答

0

我同意@ZawLin,我发现你张贴的图像的宽度不加起来。

原来是353(不像你说的那样是352),更有趣的是0.8倍缩放是285宽而不是352 * 0.8 = 282。 所以我想你会在渲染第0行的时候从第1行中抽取三个额外的像素(285-282),并将它们添加到第0行的末尾。这对于下一行已经是6,然后是9等等。因此图像看起来倾斜。

因此,我得出结论,您将缩放的282宽图像渲染到285广阔的区域。

+0

谢谢@托马斯,请注意我张贴在这里的图片是一个屏幕截图,而不是原始图片,但您的观点很有帮助,我会继续关注它。 – Zengrui 2014-09-22 18:34:34