這是一個非常好的問題。當你知道矩陣的通道類型和數量時,Wiki可以幫助你。如果你不這樣做,那麼你需要一個switch語句。下面是打印幾乎任何類型的矩陣的值/像素的簡單的代碼示例:
// Main print method which includes the switch for types
void printMat(const Mat& M){
switch ((M.dataend-M.datastart)/(M.cols*M.rows*M.channels())){
case sizeof(char):
printMatTemplate<unsigned char>(M,true);
break;
case sizeof(float):
printMatTemplate<float>(M,false);
break;
case sizeof(double):
printMatTemplate<double>(M,false);
break;
}
}
// Print template using printf("%d") for integers and %g for floats
template <typename T>
void printMatTemplate(const Mat& M, bool isInt = true){
if (M.empty()){
printf("Empty Matrix\n");
return;
}
if ((M.elemSize()/M.channels()) != sizeof(T)){
printf("Wrong matrix type. Cannot print\n");
return;
}
int cols = M.cols;
int rows = M.rows;
int chan = M.channels();
char printf_fmt[20];
if (isInt)
sprintf_s(printf_fmt,"%%d,");
else
sprintf_s(printf_fmt,"%%0.5g,");
if (chan > 1){
// Print multi channel array
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
printf("(");
const T* Pix = &M.at<T>(i,j);
for (int c = 0; c < chan; c++){
printf(printf_fmt,Pix[c]);
}
printf(")");
}
printf("\n");
}
printf("-----------------\n");
}
else {
// Single channel
for (int i = 0; i < rows; i++){
const T* Mi = M.ptr<T>(i);
for (int j = 0; j < cols; j++){
printf(printf_fmt,Mi[j]);
}
printf("\n");
}
printf("\n");
}
}
你的意思是垃圾?你期望它打印什麼?你有沒有嘗試過一個簡單的輸入圖像,比如1x2?如何在valgrind下運行以檢查內存訪問問題? –
確切的重複:http://stackoverflow.com/q/4742251/176769 – karlphillip
你沒有把那裏的權利鑄在image.at <>(可惜的是,OpenCV並沒有爲此抱怨......)。你可以在這裏檢查正確的投影:[(link)](http://stackoverflow.com/questions/13484475/what-are-the-upper-and-lower-limits-of-pixel-values-in-opencv) –