2014-09-21 42 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