#include "opencv2/opencv.hpp"

int main() {
    cv::Mat testImg = cv::imread("../img1.png", cv::IMREAD_COLOR); // BGR
    cv::cvtColor(testImg, testImg, cv::COLOR_BGR2RGBA);
    std::cout << "The number of channels: " << testImg.channels() << std::endl;
    if (testImg.type() == CV_8UC1){
        std::cout << "The image type is: CV_8UC1" << std::endl;
    }
//    cv::Rect ROI(0, 0, 50, 50);
//    testImg = testImg(ROI);
    cv::imshow("test", testImg);
    cv::waitKey(0);

//    auto copyData = testImg.clone().data;
//    cv::Mat imgCopy(testImg.rows, testImg.cols, CV_8UC1, copyData);
//    cv::imshow("image copy", imgCopy);
//    cv::waitKey(0);


    std::cout << "The first 9 elements of the Mat array: " << std::endl;
    std::cout << "The matrix obtained values: " << std::endl;
    for (int i = 0; i < 3; i++){
        std::cout << testImg.at<cv::Vec4b>(i, i) << " ";
    }

    std::cout << std::endl << "The array obtained value: " << std::endl;
    for (int i = 0; i < 16; i++){
         std::cout << (int)testImg.data[i] << " ";
    }
    std::cout << std::endl;

//    for (int i = 0; i < 50; i++){
//        for (int j = 0; j < 50; j++){
//            std::cout << testImg.data[j*i + j] << " ";
//        }
//        std::cout << std::endl;
//    }

    auto* p_data = (uint8_t*)malloc(testImg.cols*testImg.rows * testImg.channels() * sizeof(uint8_t));
    auto xres = testImg.cols;
    auto yres = testImg.rows;
    uint8_t color = 255;
//    for (int i = 0; i < yres; ++i)
//    {
//        for (int j = 0; j < xres; ++j){
//            memcpy(p_data + (i+j) * sizeof(uchar), testImg.data + (i+j) * sizeof(uchar), sizeof(color));
//
//        }
//    }
    auto memsize = testImg.cols*testImg.rows * testImg.channels() * sizeof(uint8_t);
    // In order to make a proper copy of the image, you need to pass the pointer to its COPY, not ITSELF.
    memcpy(p_data, (uint8_t*)testImg.clone().data, memsize);
    std::cout << std::endl;
    for (int i = 0; i < 50; i++){
        for (int j = 0; j < 50; j++){
            std::cout << (int)p_data[j*i + j] << " ";
        }
        std::cout << std::endl;
    }
    cv::Mat recImg(yres, xres, CV_8UC4, p_data);
    cv::imshow("recovered image", recImg);
    cv::waitKey(0);

}