这是一个非常好的问题。当你知道矩阵的通道类型和数量时,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) –