打印Mat对象的值

时间:2015-11-18 05:55:53

标签: c++ opencv matrix

我试图获得N * N矩阵。要做到这一点,我使用下面的代码,但始终打印一个值。任何想要采用正确的矩阵值的想法。

我使用imread函数检查了目标mat,该函数不为null。的对价。但是在printf中出现 \ 377 值,其中int count = 0;

 Size s=destination.size();

    int count=0;
    for(int i=0 ;i<s.height; i++)
    {
        for (int j=0; j<s.width; j++) {
            unsigned char* byte = destination.ptr<unsigned char>(i,j);
            count++;
            printf("valeue %s ",byte);
            printf("\n");

        }
    }

输出

valeue \377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377 .......

2 个答案:

答案 0 :(得分:1)

ptr接受号码作为参数。因此,您可以通过调用每个i(外部内部循环)上的指针来获取指向每行的起始元素的指针。

然后您需要%d中的%u(或printf)(或者您可以使用cout)。检查以下代码:

#include <opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;

int main() 
{
    int N = 10;

    // Init matrix
    Mat destination(N, N, CV_8UC1);
    randu(destination, Scalar(0), Scalar(255));

    Size s = destination.size();
    int count = 0;
    for (int i = 0; i<s.height; i++)
    {
        unsigned char* pByte = destination.ptr<unsigned char>(i);
        for (int j = 0; j<s.width; j++) {
            count++;
            printf("value %d ", pByte[j]);
            printf("\n");

            //cout << "value " << int(pByte[j]) << endl;
        }
    }

    return(0);
}

您可以在my other answer其他方法中查看Mat中特定位置的值。

答案 1 :(得分:0)

要打印Mat值,您只需要迭代Mat。

以下是一段代码:

Mat in = imread("image.bmp",CV_LOAD_IMAGE_GRAYSCALE);
if(in.empty())
{
  puts("Cannot open image!");
  return -1;
}
//Print the values
for(int i=0;i<in.rows;i++)
{
    for(int j=0;j<in.cols;j++)
    {
        cout<<in.at<uchar>(i,j)<<" ";
    }
    cout<<endl;
}

这里基本上我正在加载图像,检查图像是否为空,然后打印值。

由于我的图像是灰度图像,我使用了in.at<uchar>(i,j) uchar表示unsigned char

相关问题