【发布时间】:2014-09-22 17:43:41
【问题描述】:
我正在做最近的插值算法来缩放 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;
}
原图
半幅图像
0.8 缩放图像
对这种情况有什么建议或解决方案吗?谢谢。
【问题讨论】:
-
我也没有看到直接的解决方案。你确定你的输入没问题吗?不是在该操作或某事期间更新的实时/易失缓冲区?此外,确保
getIndex(j,i,w)真正尊重给定的 w 并且不会恢复为成员Width或期望交换 j 和 i(我会反过来做)。最后,你最后的复制操作好像没什么用,就delete[] Data;和Data = temp;。 -
@Thomas 您好,感谢您的回复,我尝试调试了一整天,但几乎看不到任何错误的编码。我用不同的输入宽度和高度值做了很多实验。我发现无论高度值是多少,某些宽度值都可以正确生成比例图像,而其他值则不能。但是我仍然不知道是什么原因导致了这种奇怪的问题。
-
@Thomas 我看到了一种模式,当宽度除以 4 时,图像就可以了...
-
@Zengrui,我使用了
int getIndex(int w,int h,int stride){return h*stride+w;},并使用了几乎相同的代码+opencv 来可视化图像。您的代码运行良好。我想问题可能出在其他地方,例如您的可视化代码。最有可能的原因可能与用于表示某处不匹配的像素的整数大小有关。 -
@ZawLin 感谢您的回复。我将尝试弄清楚整数表示发生了什么。
标签: c++ image-processing