Example #1
0
 void MaskingItem::confirmMask()
 {
     mitk::DataNode::Pointer node = this->m_node;
     mitk::DataStorage::SetOfObjects::ConstPointer sourceNodes = storage->GetSources(node);
     mitk::DataNode::Pointer sourceNode = sourceNodes->front();
     
     if(node.IsNull() || sourceNode.IsNull())
     {
         return;
     }
     
     mitk::Image* referenceImage = dynamic_cast<mitk::Image*>(sourceNode->GetData());
     mitk::Image* maskImage = dynamic_cast<mitk::Image*>(node->GetData());
     
     if(!referenceImage && !maskImage)
     {
         return;
     }
     
     mitk::Image::Pointer resultImage(nullptr);
     
     if(referenceImage->GetLargestPossibleRegion().GetSize() == maskImage->GetLargestPossibleRegion().GetSize())
     {
         resultImage = this->maskImage(referenceImage, maskImage);
     }
     
     if(resultImage.IsNull())
     {
         return;
     }
     
     mitk::DataNode::Pointer resultNode = mitk::DataNode::New();
     resultNode->SetData(resultImage);
     resultNode->SetName(node->GetName() + "_" + sourceNode->GetName());
     resultNode->SetBoolProperty("image", true);
     storage->Add(resultNode);
     
     mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll();
 }
Example #2
0
void FELighting::apply(Filter* filter)
{
    m_in->apply(filter);
    if (!m_in->resultImage())
        return;

    if (!getEffectContext())
        return;

    setIsAlphaImage(false);

    IntRect effectDrawingRect = calculateDrawingIntRect(m_in->scaledSubRegion());
    RefPtr<ImageData> srcImageData(m_in->resultImage()->getUnmultipliedImageData(effectDrawingRect));
    CanvasPixelArray* srcPixelArray(srcImageData->data());

    // FIXME: support kernelUnitLengths other than (1,1). The issue here is that the W3
    // standard has no test case for them, and other browsers (like Firefox) has strange
    // output for various kernelUnitLengths, and I am not sure they are reliable.
    // Anyway, feConvolveMatrix should also use the implementation

    if (drawLighting(srcPixelArray, effectDrawingRect.width(), effectDrawingRect.height()))
        resultImage()->putUnmultipliedImageData(srcImageData.get(), IntRect(IntPoint(), resultImage()->size()), IntPoint());
}
Example #3
0
int TestCreator::compareImageLists() {
    _progressBar->setMinimum(0);
    _progressBar->setMaximum(_expectedImagesFullFilenames.length() - 1);
    _progressBar->setValue(0);
    _progressBar->setVisible(true);

    // Loop over both lists and compare each pair of images
    // Quit loop if user has aborted due to a failed test.
    bool keepOn{ true };
    int numberOfFailures{ 0 };
    for (int i = 0; keepOn && i < _expectedImagesFullFilenames.length(); ++i) {
        // First check that images are the same size
        QImage resultImage(_resultImagesFullFilenames[i]);
        QImage expectedImage(_expectedImagesFullFilenames[i]);

        double similarityIndex;  // in [-1.0 .. 1.0], where 1.0 means images are identical
        double worstTileValue;   // in [-1.0 .. 1.0], where 1.0 means images are identical

        bool isInteractiveMode = (!_isRunningFromCommandLine && _checkBoxInteractiveMode->isChecked() && !_isRunningInAutomaticTestRun);
                                 
        // similarityIndex is set to -100.0 to indicate images are not the same size
        if (isInteractiveMode && (resultImage.width() != expectedImage.width() || resultImage.height() != expectedImage.height())) {
            QMessageBox::critical(0, "Internal error: " + QString(__FILE__) + ":" + QString::number(__LINE__), "Images are not the same size");
            similarityIndex = -100.0;
            worstTileValue = 0.0;
        } else {
            _imageComparer.compareImages(resultImage, expectedImage);
            similarityIndex = _imageComparer.getSSIMValue();
            worstTileValue = _imageComparer.getWorstTileValue();
        }

        TestResult testResult = TestResult{
            similarityIndex,
            worstTileValue,
            _expectedImagesFullFilenames[i].left(_expectedImagesFullFilenames[i].lastIndexOf("/") + 1),  // path to the test (including trailing /)
            QFileInfo(_expectedImagesFullFilenames[i].toStdString().c_str()).fileName(),                 // filename of expected image
            QFileInfo(_resultImagesFullFilenames[i].toStdString().c_str()).fileName(),                   // filename of result image
            _imageComparer.getSSIMResults()                                                              // results of SSIM algoritm
        };

        _mismatchWindow.setTestResult(testResult);
        
        if (similarityIndex < THRESHOLD_GLOBAL || worstTileValue < THRESHOLD_LOCAL) {
            if (!isInteractiveMode) {
                ++numberOfFailures;
                appendTestResultsToFile(testResult, _mismatchWindow.getComparisonImage(), _mismatchWindow.getSSIMResultsImage(testResult._ssimResults), true);
            } else {
                _mismatchWindow.exec();

                switch (_mismatchWindow.getUserResponse()) {
                    case USER_RESPONSE_PASS:
                        break;
                    case USE_RESPONSE_FAIL:
                        ++numberOfFailures;
                        appendTestResultsToFile(testResult, _mismatchWindow.getComparisonImage(), _mismatchWindow.getSSIMResultsImage(testResult._ssimResults), true);
                        break;
                    case USER_RESPONSE_ABORT:
                        keepOn = false;
                        break;
                    default:
                        assert(false);
                        break;
                }
            }
        } else {
            appendTestResultsToFile(testResult, _mismatchWindow.getComparisonImage(), _mismatchWindow.getSSIMResultsImage(testResult._ssimResults), false);
        }

        _progressBar->setValue(i);
    }

    _progressBar->setVisible(false);
    return numberOfFailures;
}
void FEMorphology::apply(Filter* filter)
{
    m_in->apply(filter);
    if (!m_in->resultImage())
        return;
    
    if (!getEffectContext())
        return;

    setIsAlphaImage(m_in->isAlphaImage());

    int radiusX = static_cast<int>(m_radiusX * filter->filterResolution().width());
    int radiusY = static_cast<int>(m_radiusY * filter->filterResolution().height());
    if (radiusX <= 0 || radiusY <= 0)
        return;

    IntRect imageRect(IntPoint(), resultImage()->size());
    IntRect effectDrawingRect = calculateDrawingIntRect(m_in->scaledSubRegion());
    RefPtr<CanvasPixelArray> srcPixelArray(m_in->resultImage()->getPremultipliedImageData(effectDrawingRect)->data());
    RefPtr<ImageData> imageData = ImageData::create(imageRect.width(), imageRect.height());

    int effectWidth = effectDrawingRect.width() * 4;
    
    // Limit the radius size to effect dimensions
    radiusX = min(effectDrawingRect.width() - 1, radiusX);
    radiusY = min(effectDrawingRect.height() - 1, radiusY);
    
    Vector<unsigned char> extrema;
    for (int y = 0; y < effectDrawingRect.height(); ++y) {
        int startY = max(0, y - radiusY);
        int endY = min(effectDrawingRect.height() - 1, y + radiusY);
        for (unsigned channel = 0; channel < 4; ++channel) {
            // Fill the kernel
            extrema.clear();
            for (int j = 0; j <= radiusX; ++j) {
                unsigned char columnExtrema = srcPixelArray->get(startY * effectWidth + 4 * j + channel);
                for (int i = startY; i <= endY; ++i) {
                    unsigned char pixel = srcPixelArray->get(i * effectWidth + 4 * j + channel);
                    if ((m_type == FEMORPHOLOGY_OPERATOR_ERODE && pixel <= columnExtrema) ||
                        (m_type == FEMORPHOLOGY_OPERATOR_DILATE && pixel >= columnExtrema))
                        columnExtrema = pixel;
                }
                extrema.append(columnExtrema);
            }
            
            // Kernel is filled, get extrema of next column 
            for (int x = 0; x < effectDrawingRect.width(); ++x) {
                unsigned endX = min(x + radiusX, effectDrawingRect.width() - 1);
                unsigned char columnExtrema = srcPixelArray->get(startY * effectWidth + endX * 4 + channel);
                for (int i = startY; i <= endY; ++i) {
                    unsigned char pixel = srcPixelArray->get(i * effectWidth + endX * 4 + channel);
                    if ((m_type == FEMORPHOLOGY_OPERATOR_ERODE && pixel <= columnExtrema) ||
                        (m_type == FEMORPHOLOGY_OPERATOR_DILATE && pixel >= columnExtrema))
                        columnExtrema = pixel;
                }
                if (x - radiusX >= 0)
                    extrema.remove(0);
                if (x + radiusX <= effectDrawingRect.width())
                    extrema.append(columnExtrema);
                unsigned char entireExtrema = extrema[0];
                for (unsigned kernelIndex = 0; kernelIndex < extrema.size(); ++kernelIndex) {
                    if ((m_type == FEMORPHOLOGY_OPERATOR_ERODE && extrema[kernelIndex] <= entireExtrema) ||
                        (m_type == FEMORPHOLOGY_OPERATOR_DILATE && extrema[kernelIndex] >= entireExtrema))
                        entireExtrema = extrema[kernelIndex];
                }
                imageData->data()->set(y * effectWidth + 4 * x + channel, entireExtrema);
            }
        }
    }
    resultImage()->putPremultipliedImageData(imageData.get(), imageRect, IntPoint());
}
Example #5
0
QString ImageConverter::toSpin(QString filename)
{
    LameImage newimage = resultImage();

    QString output;
    QTextStream stream(&output);

    stream  << "' *********************************************************\n"
            << "' " << QFileInfo(filename).fileName() << "\n"
            << "' generated by img2dat v" << qApp->applicationVersion() << "\n"
            << "' *********************************************************\n"
            << "PUB Addr\n"
            << "    return @gfx_data\n\n"
            << "DAT\n\n"
            << "gfx_data\n\n"
            << "word    " << newimage.frameboost() << "\n"
            << "word    " << newimage.frameWidth() << ", " << newimage.frameHeight() << "\n";

    // print data
    unsigned short word = 0;
    for (int fy = 0; fy < newimage.frameCountY(); fy++)
    {
        for (int fx = 0; fx < newimage.frameCountX(); fx++)
        {
            for (int y = 0; y < _newframeheight; y++)
            {
                stream << "word    ";
                word = 0;
                for (int x = 0; x < _newframewidth; x++)
                {
                    if (x % 8 == 0)
                    {
                        word = 0;
                    }
                    word += (newimage.pixelIndex(fx*_newframewidth+x, fy*_newframeheight+y) << ((x % 8)*2));

                    if (x % 8 == 7)
                    {
                        stream << QString("$%1").arg(word,4,16,QChar('0'));
                        if (x < _newframewidth-1)
                            stream << ",";
                    }
                }

                stream << " ' ";
                for (int x = 0; x < _newframewidth; x++)
                {
                    QString s;
                    switch (newimage.pixelIndex(fx*_newframewidth+x, fy*_newframeheight+y))
                    {
                        case 2: s = " ";
                                break;
                        case 1: s = "░";
                                break;
                        case 3: s = "▓";
                                break;
                        case 0: s = "█";
                                break;
                    }
                    stream << s;
                }

                stream << "\n";
            }
            stream << "\n";
        }
    }

    return output;
}
/** \brief Create progessive icon

Do QIcon with top and bottom image mixed and percent writed on it.
The icon it be search in the style path.
Do by mongaulois, remake by alpha_one_x86.
\param percent indique how many percent need be showed, sould be between 0 and 100
\param text The showed text if needed (optionnal)
\return QIcon of the final image
\note Can be used as it: dynaIcon(75,"...")
*/
QIcon Themes::dynaIcon(int percent,QString text) const
{
    #ifdef ULTRACOPIER_PLUGIN_DEBUG
    if(pixmapTop.isNull() || pixmapBottom.isNull())
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Error loading the icons");
    #endif
    if(percent==-1)
        percent=getOldProgression;
    if(percent<0)
        percent=0;
    if(percent>100)
        percent=100;
    //pixmap avec un fond transparent
    #ifdef Q_OS_WIN32
    quint8 imageSize=16;
    #else
    quint8 imageSize=22;
    #endif
    QPixmap resultImage(imageSize,imageSize);
    resultImage.fill(Qt::transparent);
    {
        QPainter painter(&resultImage);
        #ifndef Q_OS_WIN32
        QFont font(QStringLiteral("Courier New"),9);
        font.setBold(true);
        font.setKerning(true);
        painter.setFont(font);
        #endif
        #ifdef Q_OS_WIN32
        QFont font(QStringLiteral("Courier New"),8);
        font.setBold(true);
        font.setKerning(true);
        painter.setFont(font);
        #endif

        //preprocessing the calcul
        quint8 bottomPixel=(percent*imageSize)/100;
        quint8 topPixel=imageSize-bottomPixel;

        //top image
        if(topPixel>0)
        {
            QRect target(0, 0, imageSize, topPixel);
            QRect source(0, 0, imageSize, topPixel);
            painter.drawPixmap(target, pixmapTop, source);
        }

        //bottom image
        if(bottomPixel>0)
        {
            QRect target2(0, topPixel, imageSize, bottomPixel);
            QRect source2(0, topPixel, imageSize, bottomPixel);
            painter.drawPixmap(target2, pixmapBottom, source2);
        }

        qint8 textxOffset=0;
        qint8 textyOffset=0;
        if(text.isEmpty())
        {
            if(percent!=100)
                text=QString::number(percent);
            else
            {
                text=QStringLiteral(":)");
                #ifdef Q_OS_WIN32
                textyOffset-=2;
                #else
                textyOffset-=1;
                #endif
            }
        }
        if(text.size()==1)
        {
            textxOffset+=3;
            #ifdef Q_OS_WIN32
            textxOffset-=1;
            #endif
        }
        else
        {
            #ifdef Q_OS_WIN32
            textxOffset-=1;
            #endif
        }
        #ifndef Q_OS_WIN32
        textxOffset+=2;
        textyOffset+=3;
        #endif
        painter.setPen(QPen(Qt::black));
        painter.drawText(3+textxOffset,13+textyOffset,text);
        painter.setPen(QPen(Qt::white));
        painter.drawText(2+textxOffset,12+textyOffset,text);
    }
    return QIcon(resultImage);
}
Example #7
0
IntRect FilterEffect::calculateDrawingIntRect(const FloatRect& effectRect)
{
    IntPoint location = roundedIntPoint(FloatPoint(scaledSubRegion().x() - effectRect.x(),
                                                   scaledSubRegion().y() - effectRect.y()));
    return IntRect(location, resultImage()->size());
}
  void onImport()
  {
    // The user don't select a sheet yet.
    if (!m_document) {
      Alert::show("Import Sprite Sheet<<Select a sprite first.||&Close");
      return;
    }

    // The list of frames imported from the sheet
    std::vector<Image*> animation;

    try {
      Sprite* sprite = m_document->getSprite();
      FrameNumber currentFrame = m_context->getActiveLocation().frame();

      // As first step, we cut each tile and add them into "animation" list.
      for (int y=m_rect.y; y<sprite->getHeight(); y += m_rect.h) {
        for (int x=m_rect.x; x<sprite->getWidth(); x += m_rect.w) {
          base::UniquePtr<Image> resultImage(Image::create(sprite->getPixelFormat(), m_rect.w, m_rect.h));

          // Clear the image with mask color.
          image_clear(resultImage, 0);

          // Render the portion of sheet.
          sprite->render(resultImage, -x, -y, currentFrame);
          animation.push_back(resultImage);
          resultImage.release();
        }
      }

      if (animation.size() == 0) {
        Alert::show("Import Sprite Sheet"
                    "<<The specified rectangle does not create any tile."
                    "<<Select a rectangle inside the sprite region."
                    "||&OK");
        return;
      }

      // The following steps modify the sprite, so we wrap all
      // operations in a undo-transaction.
      ContextWriter writer(m_context);
      UndoTransaction undoTransaction(writer.context(), "Import Sprite Sheet", undo::ModifyDocument);
      DocumentApi api = m_document->getApi();

      // Add the layer in the sprite.
      LayerImage* resultLayer = api.newLayer(sprite);

      // Add all frames+cels to the new layer
      for (size_t i=0; i<animation.size(); ++i) {
        int indexInStock;

        // Add the image into the sprite's stock
        indexInStock = api.addImageInStock(sprite, animation[i]);
        animation[i] = NULL;

        // Create the cel.
        base::UniquePtr<Cel> resultCel(new Cel(FrameNumber(i), indexInStock));

        // Add the cel in the layer.
        api.addCel(resultLayer, resultCel);
        resultCel.release();
      }

      // Copy the list of layers (because we will modify it in the iteration).
      LayerList layers = sprite->getFolder()->getLayersList();

      // Remove all other layers
      for (LayerIterator it=layers.begin(), end=layers.end(); it!=end; ++it) {
        if (*it != resultLayer)
          api.removeLayer(*it);
      }

      // Change the number of frames
      api.setTotalFrames(sprite, FrameNumber(animation.size()));

      // Set the size of the sprite to the tile size.
      api.setSpriteSize(sprite, m_rect.w, m_rect.h);

      undoTransaction.commit();
    }
    catch (...) {
      for (size_t i=0; i<animation.size(); ++i)
        delete animation[i];
      throw;
    }

    update_screen_for_document(m_document);
    closeWindow(NULL);
  }