读取图像中像素的值并保存在文件中 OpenCv

Read value of pixel in a image and save on file OpenCv

我使用代码读取图像(彩色或灰度),如果它是彩色的,则将其转换为灰度,读取每个像素,然后保存在 txt 文件中但我遇到了问题。 当我 运行 程序时,它 return 我这个错误:

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file C:\builds_4_PackSlave-win32-vc12-shared\opencv\modules\imgproc\src\color.cpp, line 3737

问题出在哪里? 我 post 代码:

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

#include <fstream>
using namespace std;


int main(int argc, char** argv)
{
    Mat colorImage = imread("aust.jpg");

    // First convert the image to grayscale.
    Mat grayImage;
    cvtColor(colorImage, grayImage, CV_RGB2GRAY);

    // Then apply thresholding to make it binary.
    Mat binaryImage(grayImage.size(), grayImage.type());


    // Open the file in write mode.
    ofstream outputFile;
    outputFile.open("Myfiles.txt");

    // Iterate through pixels.
    for (int r = 0; r < grayImage.rows; r++)
    {
        for (int c = 0; c < grayImage.cols; c++)
        {
            int pixel = grayImage.at<uchar>(r, c);

            outputFile << pixel << " ";
        }
        outputFile << "-1 ";
    }

    // Close the file.
    outputFile.close();
    return 0;
}

我尝试阅读这样的图像:

感谢大家的帮助。

直接加载灰度图即可,无需手动转换:

Mat grayImage = imread("aust.jpg", CV_LOAD_IMAGE_GRAYSCALE);

如果您想读取彩色图像然后转换为灰度图像,您应该使用 CV_LOAD_IMAGE_COLOR 标志调用 cv::imread


顺便说一句,评论下面的行

// Then apply thresholding to make it binary.

不应用阈值。我猜你打算使用 cv::threshold.

错误意味着cvtColor的输入图像不是3或4通道图像。请检查频道数:

colorImage.channels();

另请注意,您应该使用 COLOR_BGR2GRAY,而不是 COLOR_RGB2GRAY。 OpenCV 中的默认顺序是 BGR,而不是 RGB。

COLOR_XXX2YYY是新名字,还有IMREAD_XXX以后用的


如前所述,您可以直接将图像加载为灰度图像,其中:

Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);

要以csv格式存储数据,可以使用cv::format函数:

Mat1b gray;
cvtColor(img, gray, COLOR_BGR2GRAY);

ofstream out("Myfiles.txt");
out << cv::format(gray, "csv");

或者您可以使用 FileStorage, or .