OpenCv查看图像中的每个像素值

OpenCv see each pixel value in an image

本文关键字:像素 图像 OpenCv      更新时间:2023-10-16

我正在OpenCv (c++语言)中进行连接组件标签(CCL)操作。为了查看CCL是否可靠地工作,我必须在调试时检查图像中的每个像素值。我已经尝试将CCL的结果保存为图像,但是我无法达到像素的数字值。在调试过程中有什么方法可以做到这一点吗?

正如@Gombat和这里已经提到的,在Visual Studio中你可以安装Image Watch

如果你想保存Mat的值到一个文本文件,你不需要重新发明任何东西(检查OpenCV Mat:基本的图像容器)。

例如,您可以简单地保存csv文件:

Mat img;
// ... fill matrix somehow
ofstream fs("test.csv");
fs << format(img, "csv");

完整的示例:

#include <opencv2opencv.hpp>
#include <iostream>
#include <fstream>
using namespace std;
using namespace cv;
int main()
{
    // Just a green image
    Mat3b img(10,5,Vec3b(0,255,0));
    ofstream fs("test.csv");
    fs << format(img, "csv");
    return 0;
}

将CCL矩阵转换为[0,255]范围内的值,并保存为图像。例如:

cv::Mat ccl = ...; // ccl operation returning CV_8U
double min, max;
cv::minMaxLoc(ccl, &min, &max);
cv::Mat image = ccl * (255. / max);
cv::imwrite("ccl.png", image);

或者将所有值存储在一个文件中:

std::ofstream f("ccl.txt");
f << "row col value" << std::endl;
for (int r = 0; r < ccl.rows; ++r) {
  unsigned char* row = ccl.ptr<unsigned char>(r);
  for (int c = 0; c < ccl.cols; ++c) {
    f << r << " " << c << " " << static_cast<int>(row[c]) << std::endl;
  }
}

当然有,但这取决于您使用的图像类型。

http://docs.opencv.org/doc/user_guide/ug_mat.html accessing-pixel-intensity-values

您使用哪个IDE进行调试?有一个Visual Studio的opencv插件:

http://opencv.org/image-debugger-plug-in-for-visual-studio.htmlhttps://visualstudiogallery.msdn.microsoft.com/e682d542 - 7 - ef3 - 402 c - b857 bbfba714f78d

要简单地将CV_8UC1类型的cv::Mat打印到文本文件中,使用下面的代码:

// create the image
int rows(4), cols(3);
cv::Mat img(rows, cols, CV_8UC1);
// fill image
for ( int r = 0; r < rows; r++ )
{
  for ( int c = 0; c < cols; c++ )
  {
    img.at<unsigned char>(r, c) = std::min(rows + cols - (r + c), 255);
  }
}
// write image to file
std::ofstream out( "output.txt" );
for ( int r = -1; r < rows; r++ )
{
  if ( r == -1 ){ out << 't'; }
  else if ( r >= 0 ){ out << r << 't'; }
  for ( int c = -1; c < cols; c++ )
  {
    if ( r == -1 && c >= 0 ){ out << c << 't'; }
    else if ( r >= 0 && c >= 0 )
    {
      out << static_cast<int>(img.at<unsigned char>(r, c)) << 't';
    }
  }
  out << std::endl;
}

只需将img, rows, cols替换为vars,并将"fill image"部分放在一边,它应该可以工作。第一行和第一列是该行/列的下标。"output.txt"将留在你的调试工作目录中,你可以在visual studio的项目调试设置中指定。