image_stack.h 2.53 KB
#ifndef STIM_IMAGE_STACK_H
#define STIM_IMAGE_STACK_H

#include "../parser/wildcards.h"
#include "../parser/filename.h"
#include "../grids/grid_data.h"
#include "../image/image.h"

namespace stim{

//this creates a class that can be used to load 3D grid data from stacks of images
//	The class uses a 4D grid_data object, where the first dimension is color
template<typename T>
class image_stack : public virtual grid_data<T, 4>{

	enum image_type {stimAuto, stimMono, stimRGB, stimRGBA};

protected:
	using grid_data<T, 4>::R;
	using grid_data<T, 4>::ptr;
	using grid_data<T, 4>::samples;

public:

	void load_images(std::string file_mask){

		stim::filename file_path(file_mask);

		//if the file path is relative, update it with the current working directory
		if(file_path.is_relative()){
			stim::filename wd = stim::filename::cwd();
			file_path = wd.get_relative(file_mask);
		}

		//get the list of files
		std::vector<stim::filename> file_list = file_path.get_list();

		//if there are no matching files, exit
		if(file_list.size() == 0){
			std::cout<<"STIM ERROR (image_stack): No matching files for loading a stack."<<std::endl;
			exit(1);
		}

		//load the first image and set all of the image_stack properties
		std::cout<<"File to Load: "<<file_list[0].str()<<std::endl;
		stim::image<T> I(file_list[0].str());

		//set the image resolution and number of channels
		R[0] = I.channels();
		R[1] = I.width();
		R[2] = I.height();
		R[3] = file_list.size();

		//allocate storage space
		ptr = (T*)malloc(sizeof(T) * samples());

		//load and copy each image into the grid
		for(unsigned int i = 0; i<R[3]; i++){

			//load the image
			stim::image<T> I(file_list[i].str());

			//retrieve the interlaced data from the image - store it in the grid
			I.data_interleaved(&ptr[ i * R[0] * R[1] * R[2] ]);
		}
	}

	void save_image(std::string file_name, unsigned int i){

		//create an image
		stim::image<T> I;

		//retrieve the interlaced data from the image - store it in the grid
		I.set_interleaved(&ptr[ i * R[0] * R[1] * R[2] ], R[1], R[2], R[0]);

		I.save(file_name);
	}

	void save_images(std::string file_mask){

		stim::filename file_path(file_mask);

		//if the file path is relative, update it with the current working directory
		if(file_path.is_relative()){
			stim::filename wd = stim::filename::cwd();
			file_path = wd.get_relative(file_mask);
		}

		//create a list of file names
		std::vector<std::string> file_list = stim::wildcards::increment(file_path.str(), 0, R[3]-1, 1);

		for(int i=0; i<R[3]; i++)
			save_image(file_list[i], i);
	}



	

};


}

#endif