IAM

OPENSOURCEFAN STUDYING
STUDYINGCOMPUTERSCIENCEANDMATH COMPUTERSCIENCE

Check out the latest superpixel benchmark — Superpixel Benchmark (2016) — and let me know your opinion! @david_stutz
23thSEPTEMBER2016

SNIPPET

C++

Using CNPY to read/write OpenCV images to .npy files from C++.

main.cpp
#include <iostream>
#include <cnpy/cnpy.h>
#include <opencv2/opencv.hpp>

int main(int argc, char** argv) {
    cv::Mat cvLenna = cv::imread("Lenna.png");
    
    unsigned int* shape = new unsigned int[3];
    shape[0] = cvLenna.rows;
    shape[1] = cvLenna.cols;
    shape[2] = cvLenna.channels();
    
    cnpy::npy_save("Lenna.npy", cvLenna.data, shape, 3);
    std::cout << "Wrote " << cvLenna.rows << " rows, " << cvLenna.cols << " cols." << std::endl;
    
    cnpy::NpyArray npyLenna = cnpy::npy_load("Lenna.npy");
    std::cout << "Read " << npyLenna.shape[0] << " rows, " << npyLenna.shape[1] << " cols." << std::endl;
    
    if (npyLenna.shape[2] == 3)
    {
        cvLenna.create(npyLenna.shape[0], npyLenna.shape[1], CV_8UC3);
        for (int i = 0; i < npyLenna.shape[0]*npyLenna.shape[1]*npyLenna.shape[2]; i++)
        {
            cvLenna.data[i] = static_cast<unsigned char>(npyLenna.data[i]);
        }
        
        cv::imshow("Lenna", cvLenna);
        cv::waitKey();
    }
    else if (npyLenna.shape[2] == 1)
    {
        cvLenna.create(npyLenna.shape[0], npyLenna.shape[1], CV_8UC1);
        for (int i = 0; i < npyLenna.shape[0]*npyLenna.shape[1]*npyLenna.shape[2]; i++)
        {
            cvLenna.data[i] = static_cast<unsigned char>(npyLenna.data[i]);
        }
        
        cv::imshow("Lenna", cvLenna);
        cv::waitKey();
    }
    else
    {
        std::cout << "Invalid number of channels read." << std::endl;
    }
    delete[] shape;
    return 0;
}


What is your opinion on the code snippet? Is it working? Let me know your thoughts in the comments below or using the following platforms: