-1
我想在圖像上應用一個過濾器,過濾器窗口(3x3)的輸出存儲在一個向量(只有非零值丟棄零值)。我想添加矢量的前四個值並將結果存儲在輸出圖像中。運行該程序會生成錯誤「Vector下標超出範圍」。不知道我在做什麼錯誤。opencv圖像處理,向量下標超出範圍
Mat Diff;//input image
int window[9];
Mat road;//output image
road = Diff.clone();
for (int y = 0; y < Diff.rows; y++)
for (int x = 0; x < Diff.cols; x++)
road.at<uchar>(y, x) = 0;
//Apply road filter
for (int y = 1; y < Diff.rows - 1; y++){
for (int x = 1; x < Diff.cols - 1; x++){
// Pick up window element
window[0] = abs(Diff.at<uchar>(y - 1, x - 1) - Diff.at<uchar>(y, x));
window[1] = abs(Diff.at<uchar>(y, x - 1) - Diff.at<uchar>(y, x));
window[2] = abs(Diff.at<uchar>(y + 1, x - 1) - Diff.at<uchar>(y, x));
window[3] = abs(Diff.at<uchar>(y - 1, x) - Diff.at<uchar>(y, x));
window[4] = abs(Diff.at<uchar>(y, x) - Diff.at<uchar>(y, x));
window[5] = abs(Diff.at<uchar>(y + 1, x) - Diff.at<uchar>(y, x));
window[6] = abs(Diff.at<uchar>(y - 1, x + 1) - Diff.at<uchar>(y, x));
window[7] = abs(Diff.at<uchar>(y, x + 1) - Diff.at<uchar>(y, x));
window[8] = abs(Diff.at<uchar>(y + 1, x + 1) - Diff.at<uchar>(y, x));
int road_detector = 0;
vector<int>nonzero_elements;
for (int n = 0; n < 9;n++){
if (window[n]>0){
nonzero_elements.push_back(window[n]);
// select the first non-zero four values of window and sum them
//road.at<uchar>(y, x) = window[0]+window[1]+window[2]+window[3];
if (nonzero_elements.size() <4){
road_detector += nonzero_elements[n];
}
else{
// sort the window
sort(nonzero_elements.begin(), nonzero_elements.end());
road_detector = nonzero_elements.at(0) + nonzero_elements.at(1) + nonzero_elements.at(2) + nonzero_elements.at(3);
}
}
}road.at<uchar>(y, x) = road_detector;
nonzero_elements.clear();
}
}
你試過調試它嗎?試試吧,尤其是在出現運行時錯誤的循環中,你會很快發現問題出在哪裏。 – Gonmator
*不知道我在做什麼錯誤* - 由於您使用的是Visual Studio,因此應該清楚錯誤發生的位置。因爲調試器會彈出一個對話框並要求您「斷開」,這需要你到錯誤發生的地方。 – PaulMcKenzie
修復一些間距和格式。 – rlandster