OpenCV Mat图像数据结构

时间:2017-03-04 01:09:09

标签: objective-c xcode opencv image-processing

我有一张已经处理过的图片:

//UIImage to Mat
cv::Mat originalMat = [self cvMatFromUIImage:inputImage];

//Grayscale
cv::Mat grayMat;
cv::cvtColor(originalMat, grayMat, CV_RGB2GRAY);

//Blur
cv::Mat gaussMat;
cv::GaussianBlur( grayMat , gaussMat, cv::Size(9, 9), 2, 2 );

//Threshold
cv::threshold(grayMat,tMat,100,255,cv::THRESH_BINARY);

比想要分析(计算白点和黑点的数量)低于线。例如:我有一个图片100x120px,我想查看x = 5y = from 0 to 119的行;反之亦然x = 0..99; y = 5;

所以我希望Mat包含x - Mat.colsy - Mat.rows,但看起来它会以另一种方式保存数据。例如,我试图将下面的像素颜色更改为线条,但没有得到2行:

for( int x = 0; x < tMat.cols; x++ ){
    tMat.at<cv::Vec4b>(5,x)[0] = 100;
}

for( int y = 0; y < tMat.rows; y++ ){
    tMat.at<cv::Vec4b>(y,5)[0] = 100;
}
return  [self UIImageFromCVMat:tMat];

白色图像的结果:

enter image description here

为什么我做了2行?是否可以直接在Mat中绘制\ check行?如果我要检查通过y = kx + b计算的行?

该怎么办?

2 个答案:

答案 0 :(得分:3)

您正以错误的方式访问像素值。您正在处理只有一个通道的图像,这就是您应该像这样访问像素值的原因:

for (int x = 0; x < tMat.cols; x++){
    tMat.at<unsigned char>(5, x) = 100;
}

for (int y = 0; y < tMat.rows; y++){
    tMat.at<unsigned char>(y, 5) = 100;
}

Mat元素的类型由两个属性定义 - 通道数和基础类型的数据。如果您不知道这些术语的含义,我强烈建议您阅读方法cv::Mat::type()cv::Mat::channels()cv::Mat::depth()的文档。

另外两个例子:

mat.at<float>(x, y) = 1.0f; // if mat type is CV_32FC1
mat.at<cv::Vec3b>(x, y) = Vec3b(1, 2, 3); // if mat type is CV_8UC3

答案 1 :(得分:2)

Mat数据类型可能存在问题。阈值输出是8位或32位(http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#threshold)的单通道图像,因此您可能不应该使用Mat.at<Vec4b>[0]设置值。

这是一个返回矩阵类型的函数。用法在注释掉的部分。复制自How to find out what type of a Mat object is with Mat::type() in OpenCV

std::string type2str(int type){
//string ty =  type2str( comparisonResult.type() );
//printf("Matrix: %s %dx%d \n", ty.c_str(), comparisonResult.cols, comparisonResult.rows );

string r;

uchar depth = type & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (type >> CV_CN_SHIFT);

switch ( depth ) {
case CV_8U:  r = "8U"; break;
case CV_8S:  r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default:     r = "User"; break;
}

r += "C";
r += (chans+'0');

return r;}
相关问题