VTK 求灰度图和直方图
实现效果:
代码如下:
double leftview[4] = {0,0, 0.33,1}; double midview[4] = {0.33,0, 0.66,1}; double rightview[4] = {0.66,0, 1.0,1}; int bins = 256; int comps = 1; vtkSmartPointer<vtkJPEGReader> reader = vtkSmartPointer<vtkJPEGReader>::New(); reader->SetFileName("d:/lena.jpg"); reader->Update(); vtkSmartPointer<vtkImageActor> actor1 = vtkSmartPointer<vtkImageActor>::New(); actor1->GetMapper()->SetInputConnection(reader->GetOutputPort()); vtkSmartPointer<vtkRenderer> render1 = vtkSmartPointer<vtkRenderer>::New(); render1->AddActor(actor1); render1->SetViewport(leftview); render1->ResetCamera(); render1->SetBackground(0,1,0); vtkSmartPointer<vtkImageLuminance> lum = vtkSmartPointer<vtkImageLuminance>::New(); lum->SetInputConnection(reader->GetOutputPort()); lum->Update(); vtkSmartPointer<vtkImageActor> actorgray = vtkSmartPointer<vtkImageActor>::New(); actorgray->GetMapper()->SetInputConnection(lum->GetOutputPort()); vtkSmartPointer<vtkRenderer> rendergray = vtkSmartPointer<vtkRenderer>::New(); rendergray->AddActor(actorgray); rendergray->SetViewport(midview); rendergray->ResetCamera(); rendergray->SetBackground(1,0,0); vtkSmartPointer<vtkImageAccumulate> his = vtkSmartPointer<vtkImageAccumulate>::New(); his->SetInputData(lum->GetOutput()); his->SetComponentExtent(0, bins-1, 0,0,0,0); his->SetComponentOrigin(0,0,0); his->SetComponentSpacing(256.0/bins, 0,0); his->Update(); vtkSmartPointer<vtkIntArray> freq = vtkSmartPointer<vtkIntArray>::New(); freq->SetNumberOfComponents(1); int *output = static_cast<int*>(his->GetOutput()->GetScalarPointer()); for(int j=0; j < bins; j++){ for(int i=0; i < comps; i++){ freq->InsertNextTuple1(*output); output++; } } vtkSmartPointer<vtkDataObject> dobj = vtkSmartPointer<vtkDataObject>::New(); dobj->GetFieldData()->AddArray(freq); vtkSmartPointer<vtkBarChartActor> actor2=vtkSmartPointer<vtkBarChartActor>::New(); actor2->SetInput(dobj); actor2->SetTitle("histogram"); actor2->GetProperty()->SetColor(1,1,1); actor2->GetLegendActor()->SetNumberOfEntries(dobj->GetFieldData()->GetArray(0)->GetNumberOfTuples()); actor2->LegendVisibilityOff(); actor2->LabelVisibilityOff(); double colors[3][3] = {{1,0,0},{0,1,0},{0,0,1}}; for(int i =0;i < bins; i++){ actor2->SetBarColor(i, colors[0]); } vtkSmartPointer<vtkRenderer> render2 = vtkSmartPointer<vtkRenderer>::New(); render2->AddActor(actor2); render2->SetViewport(rightview); render2->ResetCamera(); render2->SetBackground(0,0,1); pRenderWindow->AddRenderer(render1); pRenderWindow->AddRenderer(rendergray); pRenderWindow->AddRenderer(render2);