Why cannot I open .y files when I can open .jpg file in opencv mat class

Viewed 26

I'm trying to convert jpg file to .y file and show the converted .y file by using Mat class. However, while I can read jpg file I cannot read .y file is there any solution to this?

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

void main()
{
    Mat image = imread("lena.jpg", IMREAD_COLOR);
    unsigned char** Y;
    Y = (unsigned char**)malloc(sizeof(unsigned char*) * image.rows);
    for (int i = 0; i < image.rows; i++)
        Y[i] = (unsigned char *)malloc(sizeof(unsigned char) * image.cols);

    FILE* fp;
    fopen_s(&fp, "lena.y", "wb");

    double sum = 0;
    int j;
    for (int i = 0; i < image.rows; i++)
    {
        for ( j = 0; j < image.cols * 3; j++)
        {
            
                if (j%3 == 0)
                {
                    if (j != 0)
                    {
                        Y[i][(j / 3) - 1] = static_cast<uchar>(sum);
                        sum = 0;
                    }
                    sum += 0.299 * image.at<uchar>(i, j);
                }
                    
                else if (j%3 == 1)
                    sum += 0.587 * image.at<uchar>(i, j);
                else if (j%3== 2)
                    sum += 0.114 * image.at<uchar>(i, j);
        }
        Y[i][(j / 3) - 1] = static_cast<uchar>(sum);
    }
    
    for(int i=0;i<image.rows;i++)
        fwrite(Y[i], 1, image.cols, fp);

    fclose(fp);
    Mat new_image = imread("lena.y", IMREAD_GRAYSCALE);
    if (new_image.empty())
    {
        std::cout << "Failed to open image!\n";
        return;
    }

    imshow("gray", image);
    waitKey(0);
}
Related