Opencv系列1_opencv对单张DCM文件的读取并显示

 实例1:opencv对单张DCM文件的读取并显示

#include 
#include   // 当中含有_finddata_t
#include 
#include 

#include 
#include 
#include 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
using namespace cv;

// 读入一个CT图,返回它的像素矩阵,使用OpenCV的Mat类型返回
// VTK读取DICOM图像并将像素值转给OpenCV的Mat对象
void dicomread(string inputFilename, Mat& img, vtkSmartPointer& reader)
{
	img.create(512, 512, CV_32SC1);

	vtkSmartPointer imageCast =
		vtkSmartPointer::New();

	reader->SetFileName(inputFilename.c_str());

	reader->Update();

	imageCast->SetInputConnection(reader->GetOutputPort());
	imageCast->SetOutputScalarTypeToInt();
	imageCast->Update();

	// 图像的基本信息
	int dims[3];
	reader->GetOutput()->GetDimensions(dims);

	//图像的像素值
	for (int k = 0; k < dims[2]; k++)
	{
		for (int j = 0; j < dims[1]; j++)
		{
			for (int i = 0; i < dims[0]; i++)
			{
				//转换数据类型,使用imagecast转到double(或float)
				int* pixel =
					(int*)(imageCast->GetOutput()->GetScalarPointer(i, j, k)); // 第i列第j行的像素值
				img.at(j, i) = int(*pixel); // 第j行第i列的像素值
			}
		}
	}
}
//可视化DICOM图像
void showdicom(Mat I)
{
	double maxx = 0, minn = 0;
	double* max = &maxx;
	double* min = &minn;
	I.convertTo(I, CV_64FC1);
	minMaxIdx(I, min, max);
	for (int i = 0; i < I.rows; i++)
	{
		for (int j = 0; j < I.cols; j++)
		{
			I.at(i, j) = 255 * (I.at(i, j) - minn) * 1 / (maxx - minn);
		}
	}

	minMaxIdx(I, min, max);
	for (int i = 0; i < I.rows; i++)
	{
		for (int j = 0; j < I.cols; j++)
			I.at(i, j) = (I.at(i, j) - minn) * 1 / (maxx - minn);
	}
	//cout << I < reader =
			vtkSmartPointer::New();
		// 读入dicom图
		dicomread(filename, I1, reader);
		//反转图像
		flip(I1, I1, 0);
		//显示得到的Mat对象I1的信息*(单通道 大小512*512)
		cout << I1.channels() << "  " << I1.size() << endl;
		showdicom(I1);
}

要读取的dcm文件放在工程目录下:

可见读取的为单通道的512*512像素大小的图像:

本例程配套素材见源码整理文章下载(点击进入)

你可能感兴趣的:(openCV,图像分割,C++基础编程,opencv,dcm,文件读取,文件显示)