void ImageAnalysis::AnalysisImage(IplImage *nw)
{
    double minx,maxy,maxx,miny,time;
    IplImage* rf=cvCreateImage(cvSize(720,576),nw->depth,nw->nChannels);
    IplImage* prevrf=cvCreateImage(cvSize(720,576),prev->depth,prev->nChannels);
    cvCopy(nw,rf);
    cvCopy(prev,prevrf);
    time=clock();
    for(int i=0;i<ZoneNum;i++)
    {
        minx=fmin(fmin(ParkRegionCoord[i][0].x,ParkRegionCoord[i][1].x),fmin(ParkRegionCoord[i][2].x,ParkRegionCoord[i][3].x));
        maxy=fmax(fmax(ParkRegionCoord[i][0].y,ParkRegionCoord[i][1].y),fmax(ParkRegionCoord[i][2].y,ParkRegionCoord[i][3].y));
        miny=fmin(fmin(ParkRegionCoord[i][0].y,ParkRegionCoord[i][1].y),fmin(ParkRegionCoord[i][2].y,ParkRegionCoord[i][3].y));
        maxx=fmax(fmax(ParkRegionCoord[i][0].x,ParkRegionCoord[i][1].x),fmax(ParkRegionCoord[i][2].x,ParkRegionCoord[i][3].x));
        cvSetImageROI(rf,cvRect(minx,miny,maxx-minx,maxy-miny));
        cvSetImageROI(prevrf,cvRect(minx,miny,maxx-minx,maxy-miny));

        rf=maskImage(rf,i);
        prevrf=maskImage(prevrf,i);
        HashCompare(rf,prevrf);
        MakeDecision(HashCompare(rf,prevrf),HistogramCompare(rf,prevrf),ImageDiff(rf,prevrf),i);

        cvResetImageROI(prevrf);
        cvResetImageROI(rf);
        cvCopy(nw,rf);
        cvCopy(prev,prevrf);
    }
    cvReleaseImage(&rf);
    cvReleaseImage(&prevrf);
    cvCopy(nw,prev);//болван, незабывай, что в opencv копируется указатель, если не делать cvCopy
    qDebug()<<"Time to compute:"<<(clock()-time)/CLOCKS_PER_SEC;
}
Example #2
0
bool VglPlus::lineEllipseTangencyByProjection(int imageW, int imageH,
                                              const vgl_line_2d<double> & line,
                                              const vgl_ellipse_2d<double> & ellipseInImage,
                                              vgl_point_2d<double> & pt, int sampleNum)
{
    vil_image_view<vxl_byte> maskImage(imageW, imageH, 3);
    maskImage.fill(0);
    
    VilPlus::draw_line(maskImage, line, VilPlus::white(), 2);
    
    vgl_polygon<double> poly = ellipseInImage.polygon(sampleNum);
    assert(poly.num_sheets() == 1);
    
    const vcl_vector< vgl_point_2d< double > > sheet = poly[0];
    assert( sheet.size() > 1 );
    
    vcl_vector<vgl_point_2d<double>> pts;
    for (int i = 0; i<sheet.size(); i++) {
        int x = vnl_math::rnd_halfinttoeven(sheet[i].x());
        int y = vnl_math::rnd_halfinttoeven(sheet[i].y());
        if (x >= 0 && x < imageW &&
            y >= 0 && y < imageH) {
            if (maskImage(x, y) == 255) {
                pts.push_back(sheet[i]);
            }
        }
    }
    
    if (pts.size() == 0) {
        return false;
    }
    
    // caluclate average position
    double avgX = 0.0;
    double avgY = 0.0;
    for (int i =0; i<pts.size(); i++) {
        avgX += pts[i].x();
        avgY += pts[i].y();
    }
    avgX /= pts.size();
    avgY /= pts.size();
    
    double stdX = 0.0;
    double stdY = 0.0;
    for (int i = 0; i<pts.size(); i++) {
        stdX += (avgX - pts[i].x()) * (avgX - pts[i].x());
        stdY += (avgY - pts[i].y()) * (avgY - pts[i].y());
    }
    
    stdX = sqrt(stdX/pts.size());
    stdY = sqrt(stdY/pts.size());
    printf("std x, y is %f %f\n", stdX, stdY);
    
    pt = vgl_point_2d<double>(avgX, avgY);
    return true;
}
Example #3
0
bool FillLayer::hasNonEmptyMaskImage() const
{
    if (hasMaskImage() && !maskImage()->isCSSValueNone())
        return true;
    
    return (next() ? next()->hasNonEmptyMaskImage() : false);
}
QuillImage TiltShift::apply(const QuillImage& image) const
{
    if (image.isNull()) {
        return image;
    }
    if (image.isFragment()) {
        m_gaussianFilter->setOption(QuillImageFilter::Radius, QVariant(GAUSSIAN_BLUR_RADIUS_TILE));
    } else if (image.size() == QSize(170, 170)) {
        m_gaussianFilter->setOption(QuillImageFilter::Radius, QVariant(GAUSSIAN_BLUR_RADIUS_THUMBNAIL));
    } else {
        m_gaussianFilter->setOption(QuillImageFilter::Radius, QVariant(GAUSSIAN_BLUR_RADIUS_PREVIEW));
    }
    QuillImage blurredImage = m_gaussianFilter->apply(image);

    float** mask = maskImage(image);
    QImage resultImage(image.size(), QImage::Format_RGB32);

    for (int y=0; y<image.height(); y++) {
        const QRgb* originalPixelRow = (const QRgb*)image.constScanLine(y);
        const QRgb* blurredPixelRow = (const QRgb*)blurredImage.constScanLine(y);
        QRgb* resultPixelRow = (QRgb*)resultImage.scanLine(y);

        for (int x=0; x<image.width(); x++) {
            int red = qRed(originalPixelRow[x]) * mask[x][y] + qRed(blurredPixelRow[x]) * (1 - mask[x][y]);
            int blue = qBlue(originalPixelRow[x]) * mask[x][y] + qBlue(blurredPixelRow[x]) * (1 - mask[x][y]);
            int green = qGreen(originalPixelRow[x]) * mask[x][y] + qGreen(blurredPixelRow[x]) * (1 - mask[x][y]);
            QColor result(red, green, blue);
            result.setHsvF(result.hueF(), qMin(SATURATION_FACTOR * result.saturationF(), 1.0), result.valueF());

            resultPixelRow[x] = result.rgb();
        }
    }

    for (int i = 0; i < image.size().width(); i ++) {
        delete[] mask[i];
    }

    delete[] mask;

    return QuillImage(image, resultImage);
}
Example #5
0
//the main function of the unwrapper
void
unwrap2D(double* wrapped_image, double* UnwrappedImage, unsigned char* input_mask,
	 int image_width, int image_height,
	 int wrap_around_x, int wrap_around_y)
{
  params_t params = {TWOPI, wrap_around_x, wrap_around_y, 0};
  unsigned char *extended_mask;
  PIXELM *pixel;
  EDGE *edge;
  int image_size = image_height * image_width;
  int No_of_Edges_initially = 2 * image_width * image_height;

  extended_mask = (unsigned char *) calloc(image_size, sizeof(unsigned char));
  pixel = (PIXELM *) calloc(image_size, sizeof(PIXELM));
  edge = (EDGE *) calloc(No_of_Edges_initially, sizeof(EDGE));

  extend_mask(input_mask, extended_mask, image_width, image_height, &params);
  initialisePIXELs(wrapped_image, input_mask, extended_mask, pixel, image_width, image_height);
  calculate_reliability(wrapped_image, pixel, image_width, image_height, &params);
  horizontalEDGEs(pixel, edge, image_width, image_height, &params);
  verticalEDGEs(pixel, edge, image_width, image_height, &params);

  //sort the EDGEs depending on their reiability. The PIXELs with higher
  //relibility (small value) first
  quicker_sort(edge, edge + params.no_of_edges - 1);

  //gather PIXELs into groups
  gatherPIXELs(edge, &params);

  unwrapImage(pixel, image_width, image_height);
  maskImage(pixel, input_mask, image_width, image_height);

  //copy the image from PIXELM structure to the unwrapped phase array
  //passed to this function
  //TODO: replace by (cython?) function to directly write into numpy array ?
  returnImage(pixel, UnwrappedImage, image_width, image_height);

  free(edge);
  free(pixel);
  free(extended_mask);
}
void BrowserUtils::generateIconFromFile(const QString inFile, const QString outFile, const QSize imageSize)
{
	QImage inImage(inFile);
	if (inImage.isNull()) {
		qWarning() << "generateIconFromFile - failed to open source file";
		Q_EMIT iconGenerated(false, outFile);
		return;
	}
	const int nMargin = 4;// Must agree with pixel data in image files
	const int nIconSize = 64;// Width & height of output image
	const int nIconWidth = nIconSize-2*nMargin;// Width of icon image within file
	const int nIconHeight = nIconSize-2*nMargin;
	QImage outImage(nIconSize, nIconSize, QImage::Format_ARGB32_Premultiplied);
	outImage.fill(0);
	QPainter painter(&outImage);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);
	QRectF source(0.0, 0.0, imageSize.width(), imageSize.height());
	QRectF target(nMargin, nMargin, nIconWidth, nIconHeight);
	QRectF size(0.0, 0.0, nIconSize, nIconSize);
	painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
	painter.drawImage(target, inImage, source);
	painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
	QImage maskImage(kIconMaskFile);
	painter.drawImage(target, maskImage, target);
	painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
	QImage overlayImage(kIconOverlayFile);
	painter.drawImage(size, overlayImage, size);

	QFileInfo imageInfo(outFile);
	QDir imageDir(imageInfo.path());
	if (!imageDir.exists()) {
		imageDir.mkpath(".");
	}

	bool saved = outImage.save(outFile);
	Q_EMIT iconGenerated(saved, outFile);
}
Example #7
0
int main(int argc, char *argv[])
{
	struct options opts;
	image_t* img;
	image_t* mask;

	parse_arguments(argc, argv, &opts);
	verbose_level = opts.verbose;

	img = readImage(opts.infile);
	if (!img)
		return EXIT_FAILURE;
	if (img->color_type != PNG_COLOR_TYPE_RGB)
	{
		verbose(1, "Input image must be RGB, 8 bits per channel (or fix the code)\n");
		freeImage(img);
		return EXIT_FAILURE;
	}
	if (!img->trans_values)
	{
		verbose(2, "%s has no tRNS chunk, assuming transparent black (RBG 0,0,0)\n",
				opts.infile);
		img->trans_values = &img->trans_values_buf;
	}
	img->num_trans = 0;

	mask = readImage(opts.maskfile);
	if (!mask)
	{
		freeImage(img);
		return EXIT_FAILURE;
	}
	if (mask->w < img->w || mask->h < img->h)
	{
		verbose(1, "Mask image dimensions are smaller than input image\n");
		freeImage(img);
		freeImage(mask);
		return EXIT_FAILURE;
	}
	else if (mask->w != img->w || mask->h != img->h)
		verbose(2, "Warning: input image and mask have different dimensions\n");

	if (mask->color_type != PNG_COLOR_TYPE_GRAY && mask->color_type != PNG_COLOR_TYPE_PALETTE)
	{
		verbose(1, "Mask image must be grayscale or paletted (or fix the code)\n");
		freeImage(img);
		freeImage(mask);
		return EXIT_FAILURE;
	}
	if (opts.alpha && (mask->color_type & PNG_COLOR_MASK_PALETTE))
	{
		verbose(2, "Warning: ignoring palette in mask image; using indices\n");
	}
	if (opts.alpha && mask->bit_depth != 8)
	{
		verbose(1, "Mask image for the alpha channel must be 8bpp\n");
		freeImage(img);
		freeImage(mask);
		return EXIT_FAILURE;
	}
	if (!opts.alpha && mask->trans)
	{
		mask->trans_index = getImageTransIndex(mask);
		verbose(2, "Using mask image transparency info; trans index %d\n", mask->trans_index);
	}
	else if (!opts.alpha)
	{
		mask->trans_index = 0;
		verbose(2, "Mask image has no transparency info; using index %d\n", mask->trans_index);
	}

	if (!opts.maskon && !opts.maskoff && !opts.alpha)
	{
		freeImage(img);
		freeImage(mask);
		verbose(1, "Nothing to do; specify -0 or -1, or use -a\n");
		return EXIT_SUCCESS;
	}

	if (opts.alpha && (opts.maskon || opts.maskoff))
	{
		verbose(2, "Options -0 and -1 have no effect when -a specified\n");
	}

	if (opts.alpha)
		alphaImage(img, mask);
	else
		maskImage(img, mask, opts.maskon, opts.maskoff);
	
	writeImage(img, opts.outfile);

	freeImage(img);
	freeImage(mask);

	return EXIT_SUCCESS;
}
int TractogramAngularError(int argc, char* argv[])
{
    ctkCommandLineParser parser;
    parser.setArgumentPrefix("--", "-");
    parser.addArgument("input", "i", ctkCommandLineParser::String, "input tractogram (.fib, vtk ascii file format)", us::Any(), false);
    parser.addArgument("reference", "r", ctkCommandLineParser::StringList, "reference direction images", us::Any(), false);
    parser.addArgument("out", "o", ctkCommandLineParser::String, "output root", us::Any(), false);
    parser.addArgument("mask", "m", ctkCommandLineParser::String, "mask image");
    parser.addArgument("verbose", "v", ctkCommandLineParser::Bool, "output optional and intermediate calculation results");
    parser.addArgument("ignore", "n", ctkCommandLineParser::Bool, "don't increase error for missing or too many directions");
    parser.addArgument("trilinear", "t", ctkCommandLineParser::Bool, "use trilinear instead of nearest neighbor interpolation");

    map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
    if (parsedArgs.size()==0)
        return EXIT_FAILURE;

    ctkCommandLineParser::StringContainerType referenceImages = us::any_cast<ctkCommandLineParser::StringContainerType>(parsedArgs["reference"]);

    string fibFile = us::any_cast<string>(parsedArgs["input"]);

    string maskImage("");
    if (parsedArgs.count("mask"))
        maskImage = us::any_cast<string>(parsedArgs["mask"]);

    string outRoot = us::any_cast<string>(parsedArgs["out"]);

    bool verbose = false;
    if (parsedArgs.count("verbose"))
        verbose = us::any_cast<bool>(parsedArgs["verbose"]);

    bool ignore = false;
    if (parsedArgs.count("ignore"))
        ignore = us::any_cast<bool>(parsedArgs["ignore"]);

    bool interpolate = false;
    if (parsedArgs.count("interpolate"))
        interpolate = us::any_cast<bool>(parsedArgs["interpolate"]);

    try
    {
        RegisterDiffusionCoreObjectFactory();
        RegisterFiberTrackingObjectFactory();

        typedef itk::Image<unsigned char, 3>                                    ItkUcharImgType;
        typedef itk::Image< itk::Vector< float, 3>, 3 >                         ItkDirectionImage3DType;
        typedef itk::VectorContainer< int, ItkDirectionImage3DType::Pointer >   ItkDirectionImageContainerType;
        typedef itk::EvaluateTractogramDirectionsFilter< float >                EvaluationFilterType;

        // load fiber bundle
        mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast<mitk::FiberBundleX*>(mitk::IOUtil::LoadDataNode(fibFile)->GetData());
        if (!inputTractogram)
            return EXIT_FAILURE;

        // load reference directions
        ItkDirectionImageContainerType::Pointer referenceImageContainer = ItkDirectionImageContainerType::New();
        for (int i=0; i<referenceImages.size(); i++)
        {
            try
            {
                mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(referenceImages.at(i))->GetData());
                typedef mitk::ImageToItk< ItkDirectionImage3DType > CasterType;
                CasterType::Pointer caster = CasterType::New();
                caster->SetInput(img);
                caster->Update();
                ItkDirectionImage3DType::Pointer itkImg = caster->GetOutput();
                referenceImageContainer->InsertElement(referenceImageContainer->Size(),itkImg);
            }
            catch(...) {
                MITK_INFO << "could not load: " << referenceImages.at(i);
            }
        }

        // load/create mask image
        ItkUcharImgType::Pointer itkMaskImage = ItkUcharImgType::New();
        if (maskImage.compare("")==0)
        {
            ItkDirectionImage3DType::Pointer dirImg = referenceImageContainer->GetElement(0);
            itkMaskImage->SetSpacing( dirImg->GetSpacing() );
            itkMaskImage->SetOrigin( dirImg->GetOrigin() );
            itkMaskImage->SetDirection( dirImg->GetDirection() );
            itkMaskImage->SetLargestPossibleRegion( dirImg->GetLargestPossibleRegion() );
            itkMaskImage->SetBufferedRegion( dirImg->GetLargestPossibleRegion() );
            itkMaskImage->SetRequestedRegion( dirImg->GetLargestPossibleRegion() );
            itkMaskImage->Allocate();
            itkMaskImage->FillBuffer(1);
        }
        else
        {
            mitk::Image::Pointer mitkMaskImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(maskImage)->GetData());
            mitk::CastToItkImage<ItkUcharImgType>(mitkMaskImage, itkMaskImage);
        }

        // evaluate directions
        EvaluationFilterType::Pointer evaluationFilter = EvaluationFilterType::New();
        evaluationFilter->SetTractogram(inputTractogram);
        evaluationFilter->SetReferenceImageSet(referenceImageContainer);
        evaluationFilter->SetMaskImage(itkMaskImage);
        evaluationFilter->SetIgnoreMissingDirections(ignore);
        evaluationFilter->SetUseInterpolation(interpolate);
        evaluationFilter->Update();

        if (verbose)
        {
            EvaluationFilterType::OutputImageType::Pointer angularErrorImage = evaluationFilter->GetOutput(0);
            typedef itk::ImageFileWriter< EvaluationFilterType::OutputImageType > WriterType;
            WriterType::Pointer writer = WriterType::New();

            string outfilename = outRoot;
            outfilename.append("_ERROR_IMAGE.nrrd");

            MITK_INFO << "writing " << outfilename;
            writer->SetFileName(outfilename.c_str());
            writer->SetInput(angularErrorImage);
            writer->Update();
        }

        string logFile = outRoot;
        logFile.append("_ANGULAR_ERROR.csv");

        ofstream file;
        file.open (logFile.c_str());

        string sens = "Mean:";
        sens.append(",");
        sens.append(boost::lexical_cast<string>(evaluationFilter->GetMeanAngularError()));
        sens.append(";\n");

        sens.append("Median:");
        sens.append(",");
        sens.append(boost::lexical_cast<string>(evaluationFilter->GetMedianAngularError()));
        sens.append(";\n");

        sens.append("Maximum:");
        sens.append(",");
        sens.append(boost::lexical_cast<string>(evaluationFilter->GetMaxAngularError()));
        sens.append(";\n");

        sens.append("Minimum:");
        sens.append(",");
        sens.append(boost::lexical_cast<string>(evaluationFilter->GetMinAngularError()));
        sens.append(";\n");

        sens.append("STDEV:");
        sens.append(",");
        sens.append(boost::lexical_cast<string>(std::sqrt(evaluationFilter->GetVarAngularError())));
        sens.append(";\n");

        file << sens;

        file.close();

        MITK_INFO << "DONE";
    }
    catch (itk::ExceptionObject e)
    {
        MITK_INFO << e;
        return EXIT_FAILURE;
    }
    catch (std::exception e)
    {
        MITK_INFO << e.what();
        return EXIT_FAILURE;
    }
    catch (...)
    {
        MITK_INFO << "ERROR!?!";
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
Example #9
0
//思い出を残す
void MainWindow::Private::captureGame(bool andEdit)
{
    qDebug() << "captureGame";

    //設定確認
    checkSavePath();

    QImage img = ui.webView->capture();
    if (img.isNull())
    {
        ui.statusBar->showMessage(tr("failed capture image"), STATUS_BAR_MSG_TIME);
        return;
    }

    GameScreen gameScreen(img);

    if (gameScreen.isVisible(GameScreen::HeaderPart)) {
        //提督名をマスク
        if(settings.value(SETTING_GENERAL_MASK_ADMIRAL_NAME, false).toBool()) {
            maskImage(&img, ADMIRAL_RECT_HEADER);
        }
        //司令部レベルをマスク
        if(settings.value(SETTING_GENERAL_MASK_HQ_LEVEL, false).toBool()) {
            maskImage(&img, HQ_LEVEL_RECT_HEADER);
        }
    }

    QString format;
    if(settings.value(SETTING_GENERAL_SAVE_PNG, false).toBool())
        format = QStringLiteral("png");
    else
        format = QStringLiteral("jpg");

    QString path = makeFileName(format);
//    qDebug() << "path:" << path;

    if(andEdit){
        //編集もする
        QString tempPath = makeTempFileName(format);
        QString editPath = makeFileName(format);
//        qDebug() << "temp path:" << tempPath;

        //保存する
        ui.statusBar->showMessage(tr("saving to %1...").arg(tempPath), STATUS_BAR_MSG_TIME);
        if (img.save(tempPath, format.toUtf8().constData())) {
            //編集ダイアログ
            openImageEditDialog(path, tempPath, editPath);
        } else {
            ui.statusBar->showMessage(tr("failed save image"), STATUS_BAR_MSG_TIME);
        }
        //テンポラリのファイルを消す
        QFile::remove(tempPath);
    }else{
        //キャプチャーだけ

        //保存する
        ui.statusBar->showMessage(tr("saving to %1...").arg(path), STATUS_BAR_MSG_TIME);
        if (img.save(path, format.toUtf8().constData())) {
            //つぶやくダイアログ
            openTweetDialog(path);
        } else {
            ui.statusBar->showMessage(tr("failed save image"), STATUS_BAR_MSG_TIME);
        }
    }
}