diff --git a/Modules/Python/PythonPath.h.in b/Modules/Python/PythonPath.h.in index 2f06a8943c..1c01e76078 100644 --- a/Modules/Python/PythonPath.h.in +++ b/Modules/Python/PythonPath.h.in @@ -1,7 +1,7 @@ -#define PYTHONPATH_ITK_LIBRARY_DIRS "@ITK_LIBRARY_DIRS@" -#define PYTHONPATH_WRAP_ITK_DIR "@ITK_DIR@/Wrapping/WrapITK/Python" - -#define PYTHONPATH_VTK_LIBRARY_DIRS "@VTK_LIBRARY_DIRS@" -#define PYTHONPATH_VTK_PYTHON_WRAPPING_DIR "@VTK_DIR@/Wrapping/Python" - -#define PYTHONPATH_OPEN_CV_LIBRARY_DIRS "@OpenCV_DIR@/lib" +#define PYTHONPATH_COMMAND "import sys\n"\ +"sys.path.append('@ITK_LIBRARY_DIRS@')\n"\ +"sys.path.append('@ITK_DIR@/Wrapping/WrapITK/Python')\n"\ +"sys.path.append('@ITK_LIBRARY_DIRS@')\n"\ +"sys.path.append('@VTK_LIBRARY_DIRS@')\n"\ +"sys.path.append('@VTK_DIR@/Wrapping/Python')\n"\ +"sys.path.append('@OpenCV_DIR@/lib')" diff --git a/Modules/Python/QmitkCtkPythonShell.cpp b/Modules/Python/QmitkCtkPythonShell.cpp index 58b62e522e..cabe523711 100644 --- a/Modules/Python/QmitkCtkPythonShell.cpp +++ b/Modules/Python/QmitkCtkPythonShell.cpp @@ -1,80 +1,81 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkCtkPythonShell.h" #include #include #include #include #include #include "mitkPythonService.h" #include #include #include struct QmitkCtkPythonShellData { mitk::PythonService* m_PythonService; }; QmitkCtkPythonShell::QmitkCtkPythonShell(QWidget* parent) : ctkPythonConsole(parent), d( new QmitkCtkPythonShellData ) { mitk::ModuleContext* context = mitk::GetModuleContext(); mitk::ServiceReference serviceRef = context->GetServiceReference(); d->m_PythonService = dynamic_cast ( context->GetService(serviceRef) ); assert( d->m_PythonService ); this->initialize( d->m_PythonService->GetPythonManager() ); } QmitkCtkPythonShell::~QmitkCtkPythonShell() { delete d; } void QmitkCtkPythonShell::dragEnterEvent(QDragEnterEvent *event) { event->accept(); } void QmitkCtkPythonShell::dropEvent(QDropEvent *event) { QList urls = event->mimeData()->urls(); for(int i = 0; i < urls.size(); i++) { d->m_PythonService->Execute( urls[i].toString(), mitk::IPythonService::SINGLE_LINE_COMMAND ); } } bool QmitkCtkPythonShell::canInsertFromMimeData( const QMimeData *source ) const { return true; } void QmitkCtkPythonShell::executeCommand(const QString& command) { + MITK_DEBUG("QmitkCtkPythonShell") << "executing command " << command.toStdString(); ctkPythonConsole::executeCommand(command); d->m_PythonService->NotifyObserver(command); } void QmitkCtkPythonShell::Paste(const QString &command) { if( this->isVisible() ) { this->executeCommand( command ); } } diff --git a/Modules/Python/QmitkPythonVariableStackTableModel.cpp b/Modules/Python/QmitkPythonVariableStackTableModel.cpp index 68e25862ee..fec5626ce7 100755 --- a/Modules/Python/QmitkPythonVariableStackTableModel.cpp +++ b/Modules/Python/QmitkPythonVariableStackTableModel.cpp @@ -1,218 +1,219 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkPythonVariableStackTableModel.h" #include #include #include #include #include #include #include const QString QmitkPythonVariableStackTableModel::MITK_IMAGE_VAR_NAME = "mitkImage"; const QString QmitkPythonVariableStackTableModel::MITK_SURFACE_VAR_NAME = "mitkSurface"; QmitkPythonVariableStackTableModel::QmitkPythonVariableStackTableModel(QObject *parent) :QAbstractTableModel(parent) { mitk::ModuleContext* context = mitk::GetModuleContext(); mitk::ServiceReference serviceRef = context->GetServiceReference(); m_PythonService = context->GetService(serviceRef); m_PythonService->AddPythonCommandObserver( this ); } QmitkPythonVariableStackTableModel::~QmitkPythonVariableStackTableModel() { m_PythonService->RemovePythonCommandObserver( this ); } bool QmitkPythonVariableStackTableModel::dropMimeData ( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent ) { // Early exit, returning true, but not actually doing anything (ignoring data). if (action == Qt::IgnoreAction) return true; // Note, we are returning true if we handled it, and false otherwise bool returnValue = false; if(data->hasFormat("application/x-mitk-datanodes")) { MITK_DEBUG("QmitkPythonVariableStackTableModel") << "dropped MITK DataNode"; returnValue = true; QString arg = QString(data->data("application/x-mitk-datanodes").data()); QStringList listOfDataNodeAddressPointers = arg.split(","); QStringList::iterator slIter; int i = 0; int j = 0; for (slIter = listOfDataNodeAddressPointers.begin(); slIter != listOfDataNodeAddressPointers.end(); slIter++) { long val = (*slIter).toLong(); mitk::DataNode* node = static_cast((void*)val); mitk::Image* mitkImage = dynamic_cast(node->GetData()); + MITK_DEBUG("QmitkPythonVariableStackTableModel") << "mitkImage is not null " << (mitkImage != 0? "true": "false"); if( mitkImage ) { QString varName = MITK_IMAGE_VAR_NAME; if( i > 0 ) varName = QString("%1%2").arg(MITK_IMAGE_VAR_NAME).arg(i); - MITK_DEBUG("varName") << "varName" << varName; + MITK_DEBUG("varName") << "varName" << varName.toStdString(); bool exportAsCvImage = m_PythonService->IsOpenCvPythonWrappingAvailable(); if( mitkImage->GetDimension() == 2 && exportAsCvImage ) { int ret = QMessageBox::question(NULL, "Export option", "2D image detected. Export as OpenCV image to Python instead of an ITK image?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); exportAsCvImage = ret == QMessageBox::Yes; if(exportAsCvImage) { m_PythonService->CopyToPythonAsCvImage( mitkImage, MITK_IMAGE_VAR_NAME ); ++i; } } if( !exportAsCvImage ) { if( m_PythonService->IsItkPythonWrappingAvailable() ) { m_PythonService->CopyToPythonAsItkImage( mitkImage, MITK_IMAGE_VAR_NAME ); ++i; } else { MITK_ERROR << "ITK Python wrapping not available. Skipping export for image " << node->GetName(); } } } else { mitk::Surface* surface = dynamic_cast(node->GetData()); if( surface ) { QString varName = MITK_SURFACE_VAR_NAME; if( j > 0 ) varName = QString("%1%2").arg(MITK_SURFACE_VAR_NAME).arg(j); MITK_DEBUG("varName") << "varName" << varName; if( m_PythonService->IsVtkPythonWrappingAvailable() ) { m_PythonService->CopyToPythonAsVtkPolyData( surface, MITK_SURFACE_VAR_NAME ); ++j; } else { MITK_ERROR << "VTK Python wrapping not available. Skipping export for surface " << node->GetName(); } } } } } return returnValue; } QVariant QmitkPythonVariableStackTableModel::headerData(int section, Qt::Orientation orientation, int role) const { QVariant headerData; // show only horizontal header if ( role == Qt::DisplayRole ) { if( orientation == Qt::Horizontal ) { // first column: "Attribute" if(section == 0) headerData = "Attribute"; else if(section == 1) headerData = "Value"; else if(section == 2) headerData = "Type"; } } return headerData; } Qt::ItemFlags QmitkPythonVariableStackTableModel::flags(const QModelIndex &index) const { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if(index.isValid()) return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags; else return Qt::ItemIsDropEnabled | flags; } int QmitkPythonVariableStackTableModel::rowCount(const QModelIndex &) const { return m_VariableStack.size(); } int QmitkPythonVariableStackTableModel::columnCount(const QModelIndex &) const { return 3; } QVariant QmitkPythonVariableStackTableModel::data(const QModelIndex &index, int role) const { if (index.isValid() && !m_VariableStack.empty()) { if(role == Qt::DisplayRole) { mitk::PythonVariable item = m_VariableStack.at(index.row()); if(index.column() == 0) return item.m_Name; if(index.column() == 1) return item.m_Value; if(index.column() == 2) return item.m_Type; } } return QVariant(); } QStringList QmitkPythonVariableStackTableModel::mimeTypes() const { return QAbstractTableModel::mimeTypes(); QStringList types; types << "application/x-mitk-datanodes"; types << "application/x-qabstractitemmodeldatalist"; return types; } Qt::DropActions QmitkPythonVariableStackTableModel::supportedDropActions() const { return Qt::CopyAction | Qt::MoveAction; } void QmitkPythonVariableStackTableModel::CommandExecuted(const QString &pythonCommand) { MITK_DEBUG("QmitkPythonVariableStackTableModel") << "command was executed " << pythonCommand.toStdString(); m_VariableStack = m_PythonService->GetVariableStack(); QAbstractTableModel::reset(); } QList QmitkPythonVariableStackTableModel::GetVariableStack() const { return m_VariableStack; } diff --git a/Modules/Python/QmitkPythonVariableStackTableView.cpp b/Modules/Python/QmitkPythonVariableStackTableView.cpp index 53273e136a..f3bf206bb1 100755 --- a/Modules/Python/QmitkPythonVariableStackTableView.cpp +++ b/Modules/Python/QmitkPythonVariableStackTableView.cpp @@ -1,75 +1,84 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkPythonVariableStackTableView.h" #include #include #include #include QmitkPythonVariableStackTableView::QmitkPythonVariableStackTableView(QWidget *parent) :QTableView(parent) { m_TableModel = new QmitkPythonVariableStackTableModel(parent); m_TableModel->CommandExecuted(""); this->setSelectionBehavior( QAbstractItemView::SelectRows ); this->setAlternatingRowColors(true); this->setDropIndicatorShown(true); this->setAcceptDrops(true); this->setModel( m_TableModel ); mitk::ModuleContext* context = mitk::GetModuleContext(); mitk::ServiceReference serviceRef = context->GetServiceReference(); m_PythonService = context->GetService(serviceRef); connect( this, SIGNAL(doubleClicked ( const QModelIndex& )), this, SLOT( OnVariableStackDoubleClicked(const QModelIndex&) ) ); } QmitkPythonVariableStackTableView::~QmitkPythonVariableStackTableView() { } void QmitkPythonVariableStackTableView::SetDataStorage(mitk::DataStorage *_DataStorage) { m_DataStorage = _DataStorage; } void QmitkPythonVariableStackTableView::OnVariableStackDoubleClicked(const QModelIndex &index) { if( m_DataStorage.IsNull() || m_PythonService == 0 ) { MITK_ERROR << "QmitkPythonVariableStackTableView not configured correctly. Quit"; return; } + int row = index.row(); QList variableStack = m_TableModel->GetVariableStack(); - QString varName = variableStack.at(index.row()).m_Name; + { + MITK_DEBUG("QmitkPythonVariableStackTableView") << "row " << row; + MITK_DEBUG("QmitkPythonVariableStackTableView") << "variableStack.size(): " << variableStack.size(); + } + + QString varName = variableStack.at(row).m_Name; - MITK_DEBUG("QmitkPythonVariableStackTableView") << varName; + { + MITK_DEBUG("QmitkPythonVariableStackTableView") << varName.toStdString(); + } mitk::Image::Pointer mitkImage = m_PythonService->CopyItkImageFromPython(varName); if( mitkImage.IsNotNull() ) { std::string nodeName = varName.toStdString(); mitk::DataNode::Pointer node = mitk::DataNode::New(); + node->SetName ( nodeName ); m_DataStorage->Add(node); node->SetData( mitkImage ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } diff --git a/Modules/Python/mitkPythonActivator.cpp b/Modules/Python/mitkPythonActivator.cpp index 7de905e7c4..62963304e8 100644 --- a/Modules/Python/mitkPythonActivator.cpp +++ b/Modules/Python/mitkPythonActivator.cpp @@ -1,101 +1,61 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkPythonActivator_h #define mitkPythonActivator_h // Microservices #include #include "mitkModuleContext.h" #include "mitkPythonService.h" #include -#include "PythonPath.h" namespace mitk { /// /// installs the PythonService /// runs all initial commands (setting env paths etc) /// class PythonActivator : public mitk::ModuleActivator { public: void Load(mitk::ModuleContext* context) { - // Registering PythonService as MicroService - m_PythonService = itk::SmartPointer(new PythonService()); + // Registering PythonService as MicroService + m_PythonService = itk::SmartPointer(new PythonService()); - ServiceProperties _PythonServiceProps; - _PythonServiceProps["Name"] = std::string("PythonService"); + ServiceProperties _PythonServiceProps; + _PythonServiceProps["Name"] = std::string("PythonService"); - context->RegisterService(m_PythonService, _PythonServiceProps); - - MITK_DEBUG("PythonActivator") << "registering python paths"; - - QString _PYTHONPATH_ITK_LIBRARY_DIRS(PYTHONPATH_ITK_LIBRARY_DIRS); - MITK_DEBUG("PythonActivator") << "_PYTHONPATH_ITK_LIBRARY_DIRS" << _PYTHONPATH_ITK_LIBRARY_DIRS.toStdString(); - - QString _PYTHONPATH_WRAP_ITK_DIR(PYTHONPATH_WRAP_ITK_DIR); - MITK_DEBUG("PythonActivator") << "_PYTHONPATH_WRAP_ITK_DIR" << _PYTHONPATH_WRAP_ITK_DIR.toStdString(); - - QString _PYTHONPATH_VTK_LIBRARY_DIRS(PYTHONPATH_VTK_LIBRARY_DIRS); - MITK_DEBUG("PythonActivator") << "_PYTHONPATH_VTK_LIBRARY_DIRS" << _PYTHONPATH_VTK_LIBRARY_DIRS.toStdString(); - - QString _PYTHONPATH_VTK_PYTHON_WRAPPING_DIR(PYTHONPATH_VTK_PYTHON_WRAPPING_DIR); - MITK_DEBUG("PythonActivator") << "_PYTHONPATH_VTK_PYTHON_WRAPPING_DIR" << _PYTHONPATH_VTK_PYTHON_WRAPPING_DIR.toStdString(); - - QString _PYTHONPATH_OPEN_CV_LIBRARY_DIRS(PYTHONPATH_OPEN_CV_LIBRARY_DIRS); - MITK_DEBUG("PythonActivator") << "_PYTHONPATH_OPEN_CV_LIBRARY_DIRS" << _PYTHONPATH_OPEN_CV_LIBRARY_DIRS.toStdString(); - - QString basecommand = "sys.path.append('%1');"; - QString pythonCommand; - - pythonCommand = basecommand.arg(_PYTHONPATH_ITK_LIBRARY_DIRS); - MITK_DEBUG("PythonActivator") << "issuing command " << pythonCommand.toStdString(); - m_PythonService->Execute(pythonCommand, mitk::IPythonService::SINGLE_LINE_COMMAND ); - - pythonCommand = basecommand.arg(_PYTHONPATH_WRAP_ITK_DIR); - MITK_DEBUG("PythonActivator") << "issuing command " << pythonCommand.toStdString(); - m_PythonService->Execute(pythonCommand, mitk::IPythonService::SINGLE_LINE_COMMAND ); - - pythonCommand = basecommand.arg(_PYTHONPATH_VTK_LIBRARY_DIRS); - MITK_DEBUG("PythonActivator") << "issuing command " << pythonCommand.toStdString(); - m_PythonService->Execute(pythonCommand, mitk::IPythonService::SINGLE_LINE_COMMAND ); - - pythonCommand = basecommand.arg(_PYTHONPATH_VTK_PYTHON_WRAPPING_DIR); - MITK_DEBUG("PythonActivator") << "issuing command " << pythonCommand.toStdString(); - m_PythonService->Execute(pythonCommand, mitk::IPythonService::SINGLE_LINE_COMMAND ); - - pythonCommand = basecommand.arg(_PYTHONPATH_OPEN_CV_LIBRARY_DIRS); - MITK_DEBUG("PythonActivator") << "issuing command " << pythonCommand.toStdString(); - m_PythonService->Execute(pythonCommand, mitk::IPythonService::SINGLE_LINE_COMMAND ); + context->RegisterService(m_PythonService, _PythonServiceProps); } - void Unload(mitk::ModuleContext* ) + void Unload(mitk::ModuleContext* context) { + m_PythonService = 0; } ~PythonActivator() { } private: itk::SmartPointer m_PythonService; }; } US_EXPORT_MODULE_ACTIVATOR(mitkPython, mitk::PythonActivator) #endif diff --git a/Modules/Python/mitkPythonService.cpp b/Modules/Python/mitkPythonService.cpp index b45a36a4f7..ae86c6c6d6 100644 --- a/Modules/Python/mitkPythonService.cpp +++ b/Modules/Python/mitkPythonService.cpp @@ -1,379 +1,422 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPythonService.h" #include #include #include #include +#include +#include "PythonPath.h" const QString mitk::PythonService::m_TmpImageName("temp_mitk_image"); mitk::PythonService::PythonService() + : m_ItkWrappingAvailable( true ), m_OpenCVWrappingAvailable( true ), m_VtkWrappingAvailable( true ) { + if( !m_PythonManager.isPythonInitialized() ) + { + MITK_DEBUG("PythonService") << "initialize python"; + m_PythonManager.setInitializationFlags(PythonQt::RedirectStdOut); m_PythonManager.initialize(); + + QVariant result = m_PythonManager.executeString( "sys.path", ctkAbstractPythonManager::EvalInput ); + MITK_DEBUG("mitk::PythonService") << "result of 'sys.path': " << result.toString().toStdString(); + + QString pythonCommand(PYTHONPATH_COMMAND); + MITK_DEBUG("PythonService") << "registering python paths" << PYTHONPATH_COMMAND; + m_PythonManager.executeString( pythonCommand, ctkAbstractPythonManager::FileInput ); + + MITK_DEBUG("mitk::PythonService") << "Trying to import ITK"; + m_PythonManager.executeString( "import itk", ctkAbstractPythonManager::SingleInput ); + m_ItkWrappingAvailable = !m_PythonManager.pythonErrorOccured(); + MITK_DEBUG("mitk::PythonService") << "m_ItkWrappingAvailable: " << (m_ItkWrappingAvailable? "yes": "no"); + if( !m_ItkWrappingAvailable ) + { + MITK_WARN << "ITK Python wrapping not available. Please check build settings or PYTHON_PATH settings."; + } + + MITK_DEBUG("mitk::PythonService") << "Trying to import OpenCv"; + m_PythonManager.executeString( "import cv2", ctkAbstractPythonManager::SingleInput ); + m_OpenCVWrappingAvailable = !m_PythonManager.pythonErrorOccured(); + MITK_DEBUG("mitk::PythonService") << "m_OpenCVWrappingAvailable: " << (m_OpenCVWrappingAvailable? "yes": "no"); + if( !m_OpenCVWrappingAvailable ) + { + MITK_WARN << "OpenCV Python wrapping not available. Please check build settings or PYTHON_PATH settings."; + } + + MITK_DEBUG("mitk::PythonService") << "Trying to import VTK"; + m_PythonManager.executeString( "import vtk", ctkAbstractPythonManager::SingleInput ); + m_VtkWrappingAvailable = !m_PythonManager.pythonErrorOccured(); + MITK_DEBUG("mitk::PythonService") << "m_VtkWrappingAvailable: " << (m_VtkWrappingAvailable? "yes": "no"); + if( !m_VtkWrappingAvailable ) + { + MITK_WARN << "VTK Python wrapping not available. Please check build settings or PYTHON_PATH settings."; + } + + } + //QVariant result = m_PythonManager.executeString( "5+5", ctkAbstractPythonManager::EvalInput ); + //MITK_DEBUG("mitk::PythonService") << "result of '5+5': " << result.toString().toStdString(); } mitk::PythonService::~PythonService() { } QVariant mitk::PythonService::Execute(const QString &pythonCommand, int commandType) { { MITK_DEBUG("mitk::PythonService") << "pythonCommand = " << pythonCommand.toStdString(); MITK_DEBUG("mitk::PythonService") << "commandType = " << commandType; } QVariant result; bool commandIssued = true; if(commandType == IPythonService::SINGLE_LINE_COMMAND ) result = m_PythonManager.executeString(pythonCommand, ctkAbstractPythonManager::SingleInput ); else if(commandType == IPythonService::MULTI_LINE_COMMAND ) result = m_PythonManager.executeString(pythonCommand, ctkAbstractPythonManager::FileInput ); else if(commandType == IPythonService::EVAL_COMMAND ) result = m_PythonManager.executeString(pythonCommand, ctkAbstractPythonManager::EvalInput ); else commandIssued = false; if(commandIssued) this->NotifyObserver(pythonCommand); return result; } QList mitk::PythonService::GetVariableStack() const { QList list; PyObject* dict = PyImport_GetModuleDict(); PyObject* object = PyDict_GetItemString(dict, "__main__"); PyObject* dirMain = PyObject_Dir(object); PyObject* tempObject; if(dirMain) { QString attr, attrValue, attrType; for(int i = 0; iob_type->tp_name; if(PyUnicode_Check(tempObject) || PyString_Check(tempObject)) attrValue = PyString_AsString(tempObject); else attrValue = ""; mitk::PythonVariable var; var.m_Name = attr; var.m_Value = attrValue; var.m_Type = attrType; list.append(var); } } return list; } void mitk::PythonService::AddPythonCommandObserver(mitk::PythonCommandObserver *observer) { if(!m_Observer.contains(observer)) m_Observer.append(observer); } void mitk::PythonService::RemovePythonCommandObserver(mitk::PythonCommandObserver *observer) { m_Observer.removeOne(observer); } void mitk::PythonService::NotifyObserver(const QString &command) { MITK_DEBUG("mitk::PythonService") << "number of observer " << m_Observer.size(); foreach(mitk::PythonCommandObserver* observer, m_Observer) { observer->CommandExecuted(command); } } QString mitk::PythonService::GetTempImageName(const QString& ext) const { QString tmpFolder = QDir::tempPath(); QString fileName = tmpFolder + QDir::separator() + m_TmpImageName + ext; return fileName; } bool mitk::PythonService::CopyToPythonAsItkImage(mitk::Image *image, const QString &varName) { // save image QString fileName = this->GetTempImageName( QString::fromStdString(mitk::IOUtil::DEFAULTIMAGEEXTENSION) ); MITK_DEBUG("PythonService") << "Saving temporary file " << fileName.toStdString(); if( !mitk::IOUtil::SaveImage(image, fileName.toStdString()) ) { MITK_ERROR << "Temporary file could not be created."; } else { // TODO CORRECT TYPE SETUP, MAKE MITK_DEBUG("PythonService") MITK_DEBUG("PythonService") int dim = image->GetDimension(); mitk::PixelType pixelType = image->GetPixelType(); itk::ImageIOBase::IOPixelType ioPixelType = image->GetPixelType().GetPixelTypeId(); // default pixeltype: unsigned short QString type = "US"; if( ioPixelType == itk::ImageIOBase::SCALAR ) { if( pixelType.GetTypeId() == typeid(double) ) type = "D"; else if( pixelType.GetTypeId() == typeid(float) ) type = "F"; if( pixelType.GetTypeId() == typeid(long double) ) type = "LD"; else if( pixelType.GetTypeId() == typeid(short) ) type = "SS"; else if( pixelType.GetTypeId() == typeid(signed char) ) type = "SC"; else if( pixelType.GetTypeId() == typeid(signed int) ) type = "SI"; else if( pixelType.GetTypeId() == typeid(signed long) ) type = "SL"; else if( pixelType.GetTypeId() == typeid(signed short) ) type = "SS"; else if( pixelType.GetTypeId() == typeid(unsigned char) ) type = "UC"; else if( pixelType.GetTypeId() == typeid(unsigned int) ) type = "UI"; else if( pixelType.GetTypeId() == typeid(unsigned long) ) type = "UL"; else if( pixelType.GetTypeId() == typeid(unsigned short) ) type = "US"; } MITK_DEBUG("PythonService") << "Got mitk image with type " << type.toStdString() << " and dim " << dim; QString command; - command.append( QString("import itk\n") ); - command.append( QString("imageType = itk.Image[%1, %2]\n") .arg( type ).arg( dim ) ); + command.append( QString("imageType = itk.Image[itk.%1, %2]\n") .arg( type ).arg( dim ) ); command.append( QString("readerType = itk.ImageFileReader[imageType]\n") ); command.append( QString("reader = readerType.New()\n") ); command.append( QString("reader.SetFileName( \"%1\" )\n") .arg(fileName) ); command.append( QString("reader.Update()\n") ); command.append( QString("%1 = reader.GetOutput()\n").arg( varName ) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command, IPythonService::MULTI_LINE_COMMAND ); QFile file(fileName); MITK_DEBUG("PythonService") << "Removing file " << fileName.toStdString(); file.remove(); return true; } return false; } mitk::Image::Pointer mitk::PythonService::CopyItkImageFromPython(const QString &varName) { mitk::Image::Pointer mitkImage; QString command; QString fileName = GetTempImageName( QString::fromStdString( mitk::IOUtil::DEFAULTIMAGEEXTENSION ) ); MITK_DEBUG("PythonService") << "Saving temporary file with python itk code " << fileName.toStdString(); - command.append( QString("import itk\n") ); command.append( QString( "writer = itk.ImageFileWriter[ %1 ].New()\n").arg( varName ) ); command.append( QString( "writer.SetFileName( \"%1\" )\n").arg(fileName) ); command.append( QString( "writer.SetInput( %1 )\n").arg(varName) ); command.append( QString( "writer.Update()\n" ) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command, IPythonService::MULTI_LINE_COMMAND ); try { MITK_DEBUG("PythonService") << "Loading temporary file " << fileName.toStdString() << " as MITK image"; mitkImage = mitk::IOUtil::LoadImage( fileName.toStdString() ); } catch(std::exception& e) { MITK_ERROR << e.what(); } QFile file(fileName); if( file.exists() ) { MITK_DEBUG("PythonService") << "Removing temporary file " << fileName.toStdString(); file.remove(); } return mitkImage; } bool mitk::PythonService::CopyToPythonAsCvImage( mitk::Image* image, const QString& varName ) { bool convert = false; if(image->GetDimension() != 2) { MITK_ERROR << "Only 2D images allowed for OpenCV images"; return convert; } // try to save mitk image QString fileName = this->GetTempImageName( QString::fromStdString(".bmp") ); MITK_DEBUG("PythonService") << "Saving temporary file " << fileName.toStdString(); if( !mitk::IOUtil::SaveImage(image, fileName.toStdString()) ) { MITK_ERROR << "Temporary file " << fileName.toStdString() << " could not be created."; return convert; } QString command; - command.append( QString("import cv\n") ); + command.append( QString("%1 = cv.LoadImage(\"%2\")\n") .arg( varName ).arg( fileName ) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command, IPythonService::MULTI_LINE_COMMAND ); MITK_DEBUG("PythonService") << "Removing file " << fileName.toStdString(); QFile file(fileName); file.remove(); convert = true; return convert; } mitk::Image::Pointer mitk::PythonService::CopyCvImageFromPython( const QString& varName ) { mitk::Image::Pointer mitkImage; QString command; QString fileName = GetTempImageName( QString::fromStdString( ".bmp" ) ); MITK_DEBUG("PythonService") << "run python command to save image with opencv to " << fileName.toStdString(); - command.append( QString("import cv\n") ); + command.append( QString( "cv.SaveImage(\"%1\", %2)\n").arg( fileName ).arg( varName ) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command, IPythonService::MULTI_LINE_COMMAND ); try { MITK_DEBUG("PythonService") << "Loading temporary file " << fileName.toStdString() << " as MITK image"; mitkImage = mitk::IOUtil::LoadImage( fileName.toStdString() ); } catch(std::exception& e) { MITK_ERROR << e.what(); } QFile file(fileName); if( file.exists() ) { MITK_DEBUG("PythonService") << "Removing temporary file " << fileName.toStdString(); file.remove(); } return mitkImage; } ctkAbstractPythonManager *mitk::PythonService::GetPythonManager() { return &m_PythonManager; } mitk::Surface::Pointer mitk::PythonService::CopyVtkPolyDataFromPython( const QString& varName ) { mitk::Surface::Pointer newSurface; QString command; QString fileName = GetTempImageName( ".stl" ); MITK_DEBUG("PythonService") << "run python command to save polydata with vtk to " << fileName.toStdString(); command = QString ( "vtkStlWriter = vtk.vtkSTLWriter()\n" "vtkStlWriter.SetInput(%1)\n" "vtkStlWriter.SetFileName(\"%2\")\n" "vtkStlWriter.Write()\n").arg(varName).arg(fileName); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command, IPythonService::MULTI_LINE_COMMAND ); try { MITK_DEBUG("PythonService") << "Loading temporary file " << fileName.toStdString() << " as MITK Surface"; newSurface = mitk::IOUtil::LoadSurface( fileName.toStdString() ); } catch(std::exception& e) { MITK_ERROR << e.what(); } QFile file(fileName); if( file.exists() ) { MITK_DEBUG("PythonService") << "Removing temporary file " << fileName.toStdString(); file.remove(); } return newSurface; } bool mitk::PythonService::CopyToPythonAsVtkPolyData( mitk::Surface* surface, const QString& varName ) { bool convert = false; // try to save mitk image QString fileName = this->GetTempImageName( ".stl" ); MITK_DEBUG("PythonService") << "Saving temporary file " << fileName.toStdString(); if( !mitk::IOUtil::SaveSurface( surface, fileName.toStdString() ) ) { MITK_ERROR << "Temporary file " << fileName.toStdString() << " could not be created."; return convert; } QString command; - command.append( QString("import vtk\n") ); + command.append( QString("vtkStlReader = vtk.vtkSTLReader()\n") ); command.append( QString("vtkStlReader.SetFileName(\"%1\")\n").arg( fileName ) ); command.append( QString("%1 = vtkStlReader.GetOutput()").arg( fileName ) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command, IPythonService::MULTI_LINE_COMMAND ); MITK_DEBUG("PythonService") << "Removing file " << fileName.toStdString(); QFile file(fileName); file.remove(); convert = true; return convert; } bool mitk::PythonService::IsItkPythonWrappingAvailable() { - return true; //TODO + return m_ItkWrappingAvailable; //TODO } bool mitk::PythonService::IsOpenCvPythonWrappingAvailable() { - return true; //TODO + return m_OpenCVWrappingAvailable; //TODO } bool mitk::PythonService::IsVtkPythonWrappingAvailable() { - return true; //TODO + return m_VtkWrappingAvailable; //TODO } diff --git a/Modules/Python/mitkPythonService.h b/Modules/Python/mitkPythonService.h index 687e31c163..8428504ee6 100644 --- a/Modules/Python/mitkPythonService.h +++ b/Modules/Python/mitkPythonService.h @@ -1,92 +1,94 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkPythonService_h #define mitkPythonService_h #include "mitkIPythonService.h" #include #include #include "mitkSurface.h" namespace mitk { /// /// implementation of the IPythonService using ctkabstractpythonmanager /// \see IPythonService class PythonService: public itk::LightObject, public mitk::IPythonService { public: /// /// instantiate python manager here PythonService(); /// /// empty implementation... ~PythonService(); /// /// \see IPythonService::Execute() QVariant Execute( const QString& pythonCommand, int commandType = SINGLE_LINE_COMMAND ); /// /// \see IPythonService::GetVariableStack() QList GetVariableStack() const; /// /// \see IPythonService::AddPythonCommandObserver() void AddPythonCommandObserver( PythonCommandObserver* observer ); /// /// \see IPythonService::RemovePythonCommandObserver() void RemovePythonCommandObserver( PythonCommandObserver* observer ); /// /// \see IPythonService::NotifyObserver() void NotifyObserver( const QString& command ); /// /// \see IPythonService::IsItkPythonWrappingAvailable() bool IsItkPythonWrappingAvailable(); /// /// \see IPythonService::CopyToPythonAsItkImage() bool CopyToPythonAsItkImage( mitk::Image* image, const QString& varName ); /// /// \see IPythonService::CopyItkImageFromPython() mitk::Image::Pointer CopyItkImageFromPython( const QString& varName ); /// /// \see IPythonService::IsOpenCvPythonWrappingAvailable() bool IsOpenCvPythonWrappingAvailable(); /// /// \see IPythonService::CopyToPythonAsCvImage() bool CopyToPythonAsCvImage( mitk::Image* image, const QString& varName ); /// /// \see IPythonService::CopyCvImageFromPython() mitk::Image::Pointer CopyCvImageFromPython( const QString& varName ); /// /// \see IPythonService::IsVtkPythonWrappingAvailable() bool IsVtkPythonWrappingAvailable(); /// /// \see IPythonService::CopyToPythonAsVtkPolyData() bool CopyToPythonAsVtkPolyData( mitk::Surface* surface, const QString& varName ); /// /// \see IPythonService::CopyVtkPolyDataFromPython() mitk::Surface::Pointer CopyVtkPolyDataFromPython( const QString& varName ); /// /// \return the ctk abstract python manager instance ctkAbstractPythonManager* GetPythonManager(); protected: QString GetTempImageName(const QString &ext) const; private: QList m_Observer; ctkAbstractPythonManager m_PythonManager; static const QString m_TmpImageName; - + bool m_ItkWrappingAvailable; + bool m_OpenCVWrappingAvailable; + bool m_VtkWrappingAvailable; }; } #endif diff --git a/Modules/Python/resources/PythonSnippets.xml b/Modules/Python/resources/PythonSnippets.xml index 7b9ceb16e7..61fc3cf768 100644 --- a/Modules/Python/resources/PythonSnippets.xml +++ b/Modules/Python/resources/PythonSnippets.xml @@ -1,4 +1,4 @@ - +