直方图均衡化

以下代码完成了itkImg的直方图均衡化

void image_enhance_grayhis(ImageType::Pointer image, ImageType::Pointer OriImage)
{
	
	int width = image->GetLargestPossibleRegion().GetSize()[0];
	int heigth = image->GetLargestPossibleRegion().GetSize()[1];

	using PixelType = float;
	enum { ImageDimension = 2 };
	
	using IndexType =ImageType::IndexType;
	using SizeType = ImageType::SizeType;
	using RegionType = ImageType::RegionType;

	ImageType::SizeValueType sizeArray[ImageDimension] = { width, heigth };
	SizeType size;
	size.SetSize(sizeArray);

	IndexType index;
	index.Fill(0);

	RegionType region;
	region.SetSize(size);
	region.SetIndex(index);

	OriImage->SetLargestPossibleRegion(region);
	OriImage->SetBufferedRegion(region);
	OriImage->Allocate();
	OriImage->SetOrigin(image->GetOrigin());
	OriImage->SetSpacing(image->GetSpacing());
	OriImage->SetDirection(image->GetDirection());

	
	unsigned int his[256] = { 0 };
	float p_hist[256] = { 0 };
	float s_hist[256] = { 0 };
	float total = width * heigth;

	for (int i = 0; i < width; i++)
	{
		for (int j = 0; j < heigth; j++)
		{
			ImageType::IndexType pixelIndex;
			pixelIndex[0] = i;
			pixelIndex[1] = j;
			float fPixel = image->GetPixel(pixelIndex);
			OriImage->SetPixel(pixelIndex, fPixel);
			int nPixel = fPixel;
			if (nPixel < 0)
				nPixel = 0;
			else if (nPixel > 255)
				nPixel = 255;
			his[nPixel]++;
		}
	}
		
	for (int i = 0; i < 256; i++)
	{
		p_hist[i] = (float)his[i] / total;
		if (i == 0)s_hist[i] = p_hist[i];
		else s_hist[i] = s_hist[i - 1] + p_hist[i];
	}

	ImageType::IndexType pixelIndex;
	float fPrePixel;
	int nPrePixel;
	unsigned char nPreValue;
	for (int i = 0; i < width; i++)
		for (int j = 0; j < heigth; j++)
		{
			
			pixelIndex[0] = i;
			pixelIndex[1] = j;

			fPrePixel = image->GetPixel(pixelIndex);
			nPrePixel = fPrePixel;
			if (nPrePixel < 0)
				nPrePixel = 0;
			else if (nPrePixel > 255)
				nPrePixel = 255;

			nPreValue =int( s_hist[nPrePixel] * 255 + 0.5);
			image->SetPixel(pixelIndex, nPreValue);
		}
}

你可能感兴趣的:(ITK,itk,直方图均衡化)