VTK学习之边缘检测(梯度算子)

参考博客:VTK修炼之道32:边缘检测_梯度算子_基于梯度的边缘检测算子_沈子恒的博客-CSDN博客

直接上源码:

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

VTK_MODULE_INIT(vtkRenderingOpenGL2);
VTK_MODULE_INIT(vtkInteractionStyle);

void main()
{
	//输入原始图像
	vtkSmartPointer reader = vtkSmartPointer::New();
	reader->SetFileName("234.jpg");
	reader->Update();

	//先转换为灰度图
	vtkSmartPointer luminanceFilter = vtkSmartPointer::New();
	luminanceFilter->SetInputConnection(reader->GetOutputPort());
	luminanceFilter->Update();

	//开始加入边缘检测,计算图像梯度,图像梯度是一个向量,具有方向和大小
	vtkSmartPointer imgGradient = vtkSmartPointer::New();
	imgGradient->SetInputConnection(luminanceFilter->GetOutputPort());
	imgGradient->SetDimensionality(2);//设置计算图像的维数,默认是二维

	vtkSmartPointer imgMagnitude = vtkSmartPointer::New();
	imgMagnitude->SetInputConnection(imgGradient->GetOutputPort());
	imgMagnitude->Update();

	//设置灰度范围
	double Range[2];
	vtkSmartPointer getRange = vtkSmartPointer::New();
	imgMagnitude->GetOutput()->GetScalarRange(Range);//图像灰度范围最小值、最大值


	vtkSmartPointer imgShift = vtkSmartPointer::New();
	imgShift->SetOutputScalarTypeToUnsignedChar(); //强制类型转换 0~255
	imgShift->SetScale(255 / Range[1]); //灰度映射间距
	imgShift->SetInputConnection(imgMagnitude->GetOutputPort());
	imgShift->Update();

	vtkSmartPointer origActor = vtkSmartPointer::New();
	origActor->SetInputData(reader->GetOutput());

	vtkSmartPointer GradientActor = vtkSmartPointer::New();
	GradientActor->SetInputData(imgShift->GetOutput());

	double origView[4] = { 0, 0, 0.5, 1 };
	double gradientView[4] = { 0.5, 0, 1, 1 };
	vtkSmartPointer origRender = vtkSmartPointer::New();
	origRender->SetViewport(origView);
	origRender->AddActor(origActor);
	origRender->ResetCamera();
	origRender->SetBackground(1.0, 0, 0);

	vtkSmartPointer gradientRender = vtkSmartPointer::New();
	gradientRender->SetViewport(gradientView);
	gradientRender->AddActor(GradientActor);
	gradientRender->ResetCamera();
	gradientRender->SetBackground(1, 1, 1);

	vtkSmartPointer renderWindow = vtkSmartPointer::New();
	renderWindow->AddRenderer(origRender);
	renderWindow->AddRenderer(gradientRender);
	renderWindow->SetSize(640, 320);
	renderWindow->Render();
	renderWindow->SetWindowName("Gradient Show");

	vtkSmartPointer interactor = vtkSmartPointer::New();
	vtkSmartPointer style = vtkSmartPointer::New();
	interactor->SetRenderWindow(renderWindow);
	interactor->SetInteractorStyle(style);
	interactor->Initialize();
	interactor->Start();
}

 最终效果:

VTK学习之边缘检测(梯度算子)_第1张图片

 

 

你可能感兴趣的:(学习,数学建模,算法)