OpenCv Multispectral Image openCV

2.6k views Asked by At

I am trying to import into openCV (c++) an image .TIF which has several bands. Using command imread it shows just the first band. How can I access to the others?

More over I tried to access the file with ifstream but it looks like I made some mistakes!

Thanks for your help,!

Best

2

There are 2 answers

1
BaseballGuy On

Some code would be helpful here to see what went wrong.

However, it seems that you are accessing only the first band instead of all the bands you want.

Try something like this (This example has 3 bands, thus Vec3b):

Vec3b image = imread(filePath, CV_LOAD_IMAGE_UNCHANGED);

This stores the image in a 3-band vector (There are several types with different amounts of bands, like Vec4b or Vec5b). You can then access each band just like accessing an element in a vector:

image[0]
image[1]
image[2]

If what I am assuming is correct, you are attempting to access by using something along the lines of

int bandValue = (int)image;

or something similar. Remember that referencing the name of a vector (or array) is the same as accessing the first element in that vector (or array)

image = image[0]
0
Vasanth On

OpenCV currently doesn't support multipage image reading. It will read only the first image.

For C++ .TIFF reading, libtiff has nice set of examples. Imagemagick also has C++ support. You can read images and copy the data buffer into OpenCV Mat.

Here is a sample c++ code that uses imagemagick's Magick++ routines:

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <string>
#include <Magick++.h>
#include <sstream>
#include <exception>

using namespace Magick;
using namespace std;
using namespace cv;

template < typename T > std::string to_string( const T& n )
{
    std::ostringstream stm ;
    stm << n ;
    return stm.str() ;
}

vector <Mat> read_images( string filename, int num=1, string dpi="300" ) {

    vector <Mat> ret;
    Image image;
    image.density(dpi);

    int cols, rows;
    int i = 0; 
    while( i < num ) {
        cout << filename + "[" + to_string(i) + "]" << endl;
        try { 
            image.read(filename + "[" + to_string(i) + "]");
        }catch ( exception ex ) {
            cout << "read " << i << " pages" << endl;
            break;
        }
        i++;
        cols = image.columns();
        rows = image.rows();
        char* blob = new char[cols*rows*3];

        image.write(0,0, cols, rows, "RGB", MagickCore::CharPixel, blob);

        ret.push_back(Mat(rows, cols, CV_8UC3, blob));
    }

    return ret; 
}


int main ( int argc, char** argv ) {
    vector<Mat> images = read_images(argv[1], 10);

    for( int i = 0; i < images.size(); i++ ) {
        imshow("image", images[i]);
        waitKey();
    } 
}