1

i using a code to read an image ( colour or grayscale ) ,convert that in grayscale if it is coloured, read every single pixel and after that save on txt file But i have a problem. When i run the program, it return me this error:

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

Where is the problem? i post code:

#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;
}

i try to read an image like this:

enter image description here

Thanks all for help.

user3836982
  • 148
  • 1
  • 13

2 Answers2

2

You can simply load the image directly as grayscale, so you do not need to do the conversion manually:

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

If you want to read as color image and then convert to grayscale, you should call cv::imread with the CV_LOAD_IMAGE_COLOR flag.


btw, the line below the comment

// Then apply thresholding to make it binary.

does not apply thresholding. I guess you intended to use cv::threshold.

Tobias Hermann
  • 9,936
  • 6
  • 61
  • 134
1

The error means that the input image to cvtColor is not a 3 or 4 channel image. Please check the number of channels:

colorImage.channels();

Also note that you should use COLOR_BGR2GRAY, and not COLOR_RGB2GRAY. The default order in OpenCV is BGR, and not RGB.

COLOR_XXX2YYY is the new name, as well as IMREAD_XXX used later.


As already mentioned, you can load the image directly as grayscale, with:

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

To store data in csv format, you can use cv::format function:

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

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

Or you can use FileStorage, or save the binary data.

Community
  • 1
  • 1
Miki
  • 40,887
  • 13
  • 123
  • 202