这个问题已经在这里回答: Copy vtkImageData to cv::Mat
但是答案的链接不再起作用。那么如何从vtkImageData
转换为cv::Mat
?
答案 0 :(得分:1)
我在这里使用此功能将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;
}