我在这里使用此函数将 vtkImageData
转换为 cv::Mat
:
cv::Mat convertVtkImageDataToCVMat(const vtkSmartPointer<vtkImageData> &vtkImage) {
int imageDimensions[3] = {0, 0, 0}; // Width, Hight, Depth --> Depth is not equal to number of image channels!
vtkImage->GetDimensions(imageDimensions);
int imageWidth = imageDimensions[0];
int imageHeight = imageDimensions[1];
int numberOfImageChannels = vtkImage->GetNumberOfScalarComponents();
int cvType = 0;
switch(numberOfImageChannels){
case 1: cvType = CV_8UC1; break;
case 3: cvType = CV_8UC3; break;
case 4: cvType = CV_8UC4; break;
default: std::cerr << "Check number of vtk image channels!" << std::endl;
}
auto resultingCVMat = cv::Mat(imageHeight, imageWidth, cvType);
// Loop over the vtkImageData contents.
for ( int heightPos = 0; heightPos < imageHeight; heightPos++ ){
for ( int widthPos = 0; widthPos < imageWidth; widthPos++ ){
auto pixel = static_cast<unsigned char *>(vtkImage->GetScalarPointer(widthPos, heightPos, 0));
resultingCVMat.at<unsigned char>(heightPos, widthPos) = *pixel;
}
}
return resultingCVMat;
}
我是一名优秀的程序员,十分优秀!