예제 #1
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ImageWindow w;
    w.show();
    return a.exec();
}
예제 #2
0
void NewImageInterface::__SetToActiveImage_Click( Button& /*sender*/, bool /*checked*/ )
{
   ImageWindow w = ImageWindow::ActiveWindow();

   if ( !w.IsNull() )
   {
      ImageVariant v = w.MainView().Image();
      AbstractImage* img = v.AnyImage();

      if ( img != 0 )
      {
         if ( v.IsFloatSample() )
            switch ( v.BitsPerSample() )
            {
            case 32: instance.sampleFormat = NewImageSampleFormat::F32; break;
            case 64: instance.sampleFormat = NewImageSampleFormat::F64; break;
            }
         else
            switch ( v.BitsPerSample() )
            {
            case  8: instance.sampleFormat = NewImageSampleFormat::I8; break;
            case 16: instance.sampleFormat = NewImageSampleFormat::I16; break;
            case 32: instance.sampleFormat = NewImageSampleFormat::I32; break;
            }

         instance.colorSpace = img->IsColor() ? NewImageColorSpace::RGB : NewImageColorSpace::Gray;
         instance.width = img->Width();
         instance.height = img->Height();
         instance.numberOfChannels = img->NumberOfChannels();

         UpdateControls();
      }
   }
}
예제 #3
0
bool CropInstance::ExecuteOn( View& view )
{
   if ( !view.IsMainView() )
      return false;  // should not happen!

   if ( p_margins == 0.0 )
   {
      Console().WriteLn( "<end><cbr>&lt;* Identity *&gt;" );
      return true;
   }

   AutoViewLock lock( view );

   ImageWindow window = view.Window();
   ImageVariant image = view.Image();

   Crop C( p_margins );
   C.SetMode( static_cast<Crop::crop_mode>( p_mode ) );
   C.SetResolution( p_resolution.x, p_resolution.y );
   C.SetMetricResolution( p_metric );
   C.SetFillValues( p_fillColor );

   // Dimensions of target image
   int w0 = image.Width();
   int h0 = image.Height();

   // Dimensions of transformed image
   int width = w0, height = h0;
   C.GetNewSizes( width, height );

   if ( width < 1 || height < 1 )
      throw Error( "Crop: Invalid operation: Null target image dimensions" );

   // On 32-bit systems, make sure the resulting image requires less than 4 GB.
   if ( sizeof( void* ) == sizeof( uint32 ) )
   {
      uint64 sz = uint64( width )*uint64( height )*image.NumberOfChannels()*image.BytesPerSample();
      if ( sz > uint64( uint32_max-256 ) )
         throw Error( "Crop: Invalid operation: Target image dimensions would exceed four gigabytes" );
   }

   DeleteAstrometryMetadataAndPreviewsAndMask( window );

   Console().EnableAbort();

   StandardStatus status;
   image.SetStatusCallback( &status );

   C >> image;

   if ( p_forceResolution )
   {
      Console().WriteLn( String().Format( "Setting resolution: h:%.3lf, v:%.3lf, u:px/%s",
                                          p_resolution.x, p_resolution.y, p_metric ? "cm" : "inch" ) );
      window.SetResolution( p_resolution.x, p_resolution.y, p_metric );
   }

   return true;
}
예제 #4
0
void AnnotationInterface::Execute()
{
   // can't execute if annotation is not placed in a valid view
   if (view == 0 || !annotationPlaced)
   {
      MessageBox mb("Can't execute. Use left mouse button to place annotation on the image first.",
         "Not executed",
         StdIcon::Information);
      mb.Execute();
      return;
   }

   // check mask. if enabled, offer user to temporarily disable it
   bool disableMask = false;
   if ( view->Window().IsMaskEnabled() && !view->Window().Mask().IsNull() )
   {
      MessageBox mb("The view has a mask enabled. Mask will probably interfere with the annotation rendering.<br/>"
         "Do you want to temporarily disable the mask?",
         "Mask Enabled",
         StdIcon::Question,
         StdButton::Yes, StdButton::No, StdButton::Cancel, 0, 2);
      MessageBox::std_button result = mb.Execute();
      if (result == StdButton::Cancel) return;
      disableMask = result == StdButton::Yes;
   }

   // Obtain local working references to the target view and window.
   View v = *view;
   ImageWindow w = v.Window();

   // Reset reference to the target view in the dynamic interface. This
   // prevents inconsistent behavior during execution.
   delete view, view = 0;
   ClearBitmaps();

   // Since active dynamic targets cannot be modified, we have to remove our
   // target view from the dynamic targets set before attempting to process.
   v.RemoveFromDynamicTargets();

   // Ensure that our target view is selected as the current view.
   w.BringToFront();
   w.SelectView( v );

   // Disable mask if required
   if ( disableMask )
      w.EnableMask( false );

   // Execute the instance on the target window.
   instance.LaunchOn( w );

   // Re-enable mask if required
   if ( disableMask )
      w.EnableMask( true );

   // keep parameters but reset state
   annotationPlaced = false;
   leaderPlaced = false;
}
예제 #5
0
void AnnotationInterface::UpdateView()
{
   // update current invalidate rect of the view
   if ( view != 0 && annotationPlaced )
   {
      annotationBmp = Bitmap::Null();
      ImageWindow w = view->Window();
      w.UpdateImageRect( invalidateRect );
   }
}
예제 #6
0
void AnnotationInterface::DynamicMouseMove( View& v, const DPoint& p, unsigned buttons, unsigned modifiers )
{
   // mouse move is processed only on active view
   if (view == 0 || v != *view)
      return;

   // get view image window
   ImageWindow w = view->Window();

   // and image coordinates of the mouse position
   int imageX = RoundI(p.x);
   int imageY = RoundI(p.y);

   // set cursor to dragging cursor if mouse is inside one of the grip rectangles
   if (annotationPlaced && textRect.Includes(imageX, imageY))
      w.SetDynamicCursor(move_all_XPM, 10, 10);
   else if (leaderPlaced && instance.annotationShowLeader && leaderRect.Includes(imageX, imageY))
      w.SetDynamicCursor(move_all_XPM, 10, 10);
   else // otherwise, reset cursor
      w.ResetDynamicCursor();

   // if we are currently dragging something
   if ( dragging != DraggingType::None )
   {
      // compute delta
      int deltaX = imageX-lastX;
      int deltaY = imageY-lastY;

      // update text position if needed
      if (dragging == DraggingType::Text || dragging == DraggingType::Both)
      {
         instance.annotationPositionX += deltaX;
         instance.annotationPositionY += deltaY;
      }

      // update leader endpoint position if needed
      if (dragging == DraggingType::Leader || dragging == DraggingType::Both)
      {
         instance.annotationLeaderPositionX += deltaX;
         instance.annotationLeaderPositionY += deltaY;
      }

      // update annotation rectangle
      UpdateAnnotationRect();

      // redraw dynamic view
      UpdateView();

      // remember current point
      lastX = imageX;
      lastY = imageY;
   }
}
예제 #7
0
void KuickShow::slotConfigApplied()
{
    dialog->applyConfig();

    initImlib();
    kdata->save();

    ImageWindow *viewer;
    QValueListIterator<ImageWindow*> it = s_viewers.begin();
    while ( it != s_viewers.end() ) {
        viewer = *it;
        viewer->updateActions();
        ++it;
    }

    fileWidget->reloadConfiguration();
}
예제 #8
0
static void FindPreviews( StringList& items, const ImageWindow& w, const String& previewId )
{
   if ( previewId.HasWildcards() )
   {
      Array<View> P = w.Previews();
      for ( size_type i = 0; i < P.Length(); ++i )
         if ( String( P[i].Id() ).WildMatch( previewId ) )
            AddView( items, P[i] );
   }
   else
   {
      View p = w.PreviewById( IsoString( previewId ) );
      if ( p.IsNull() )
         throw ParseError( "Preview not found", previewId );
      AddView( items, p );
   }
}
예제 #9
0
static void FindPreviews( StringList& items, const String& imageId, const String& previewId )
{
   if ( imageId.HasWildcards() )
   {
      Array<ImageWindow> W = ImageWindow::AllWindows();
      for ( size_type i = 0; i < W.Length(); ++i )
         if ( String( W[i].MainView().Id() ).WildMatch( imageId ) )
            FindPreviews( items, W[i], previewId );
   }
   else
   {
      ImageWindow w = ImageWindow::WindowById( IsoString( imageId ) );
      if ( w.IsNull() )
         throw ParseError( "Image not found", imageId );
      FindPreviews( items, w, previewId );
   }
}
예제 #10
0
InspectorApp::InspectorApp()
	: BApplication(APP_SIG)
{
	fpActivesWin = NULL;
	fpInfoWin = NULL;
	
	be_locale->GetAppCatalog(&fAppCatalog);
	
	AddToTranslatorsList("/system/add-ons/Translators",
		SYSTEM_TRANSLATOR);
	AddToTranslatorsList("/boot/home/config/add-ons/Translators",
		USER_TRANSLATOR);
	
	// Show application window
	BRect rect(100, 100, 500, 400);
	ImageWindow *pwin = new ImageWindow(rect, IMAGEWINDOW_TITLE);
	pwin->Show();
}
예제 #11
0
void AnnotationInterface::DynamicPaint( const View& v, VectorGraphics& g, const DRect& r ) const
{
   // we need valid view and annotation must be placed
   if ( view == 0 || v != *view || !annotationPlaced )
      return;

   // are we painting to rect with annotation?
   if ( !totalRect.Intersects( r ) )
      return;

   // get the image window
   ImageWindow w = view->Window();

   // render annotation to bitmap if needed
   if ( annotationBmp.IsNull() )
   {
      relPosX = 0;
      relPosY = 0;
      annotationBmp = AnnotationRenderer::CreateAnnotationBitmap( instance, relPosX, relPosY, true );
      screenBmp = Bitmap::Null();
   }

   // compute viewport coordinates of annotation text
   int posX = instance.annotationPositionX - relPosX;
   int posY = instance.annotationPositionY - relPosY;
   w.ImageToViewport( posX, posY );

   // compute zoom factor
   int zoomFactor = w.ZoomFactor();
   double z = (zoomFactor < 0) ? -1.0/zoomFactor : double( zoomFactor );

   // draw bitmap, scaled according to zoom factor
   Rect zr( RoundI( annotationBmp.Width()*z ), RoundI( annotationBmp.Height()*z ) );
   if ( screenBmp.IsNull() || zr != screenBmp.Bounds() )
      if ( zoomFactor < 0 )
         screenBmp = annotationBmp.Scaled( z );
      else
         screenBmp = annotationBmp;

   if ( zoomFactor < 0 )
      g.DrawBitmap( posX, posY, screenBmp );
   else
      g.DrawScaledBitmap( zr.MovedTo( posX, posY ), screenBmp );
}
예제 #12
0
// prints the selected files in the filebrowser
void KuickShow::slotPrint()
{
    const KFileItemList *items = fileWidget->selectedItems();
    if ( !items )
        return;

    KFileItemListIterator it( *items );

    // don't show the image, just print
    ImageWindow *iw = new ImageWindow( 0, id, this, "printing image" );
    KFileItem *item;
    while ( (item = it.current()) ) {
        if (FileWidget::isImage( item ) && iw->loadImage( item->url() ))
            iw->printImage();
        ++it;
    }

    iw->close( true );
}
예제 #13
0
void FilteringService::applyAlgorithm(Filtering* algo)
{
    //StandardImageWindow* siw = dynamic_cast<StandardImageWindow*>(_ws->getCurrentImageWindow());
    if (_siw != NULL)
    {
        const Image_t<double>* image;
        if(_siw->isStandard()) {
            const Image* whole_image = _siw->getDisplayImage();
            const Image* im = whole_image->crop(_siw->selection());
            image = Converter<Image_t<double> >::convert(*im);
            delete im;
        }
        else if(_siw->isDouble()) {
           DoubleImageWindow* diw = dynamic_cast<DoubleImageWindow*>(_siw);
           image = diw->getImage();
        }
        Image_t<double>* dblResImg = (*algo)(image);
        ImageWindow* riw;
        if(_siw->isStandard()) {
            delete image;
        }
        if(_dblResult) {
            DoubleImageWindow* diw = dynamic_cast<DoubleImageWindow*>(_siw);
            if(diw != NULL) {
                riw = new DoubleImageWindow(dblResImg, _siw->getPath(), diw->isNormalized(), diw->isLogScaled());
            }
            else {
                riw = new DoubleImageWindow(dblResImg, _siw->getPath());
            }
        }
        else {
            Image_t<int>* intResImg = Converter<Image_t<int> >::convert(*dblResImg);
            delete dblResImg;
            Image* resImg = Converter<Image>::makeDisplayable(*intResImg);
            delete intResImg;
            riw = new StandardImageWindow(resImg, _siw->getPath());
        }
        riw->setWindowTitle(_siw->windowTitle());
        emit newImageWindowCreated(_ws->getNodeId(_siw), riw);
    }
}
예제 #14
0
LRESULT CALLBACK MainWndProc(
	HWND hwnd,
	UINT uMsg,
	WPARAM wParam,
	LPARAM lParam)
{
	switch (uMsg) 
	{ 
	case WM_CREATE: 
		return 0; 

	case WM_PAINT: 
		{
			LONG_PTR ptr = GetWindowLongPtr( hwnd, GWLP_USERDATA );
			if( ptr )
			{
				ImageWindow* iw = (ImageWindow*)ptr;
				iw->OnPaint();
			}
		}
		
		return 0; 

	case WM_SIZE: 
		// Set the size and position of the window. 
		return 0; 

	case WM_DESTROY: 
		// Clean up window-specific data objects. 
		return 0; 

		// 
		// Process other messages. 
		// 

	default: 
		return DefWindowProc(hwnd, uMsg, wParam, lParam); 
	} 
	//return 0; 
}
예제 #15
0
void FilteringService::applyFiltering()
{
    ImageWindow* siw = dynamic_cast<ImageWindow*>(_ws->getCurrentImageWindow());
    if (siw != NULL)
    {
        _siw = siw;

        _filterChoice = new FilterChoice(_gi);
        _filterChoice->setDoubleResult(siw->isDouble());
//        QMdiArea* area = (QMdiArea*)_gi->centralWidget();
//        area->addSubWindow(_filterChoice);
        QDialog::DialogCode code = static_cast<QDialog::DialogCode>(_filterChoice->exec());

        if(code!=QDialog::Accepted) {
            return;
        }
        _dblResult = _filterChoice->doubleResult();

        Filtering* filtering = _filterChoice->getFiltering();
        this->applyAlgorithm(filtering);

    }
}
예제 #16
0
bool AnnotationInterface::ImportProcess( const ProcessImplementation& p )
{
   const AnnotationInstance* i = dynamic_cast<const AnnotationInstance*>( &p );

   if ( i == 0 )
      throw Error( "Not an Annotation instance." );

   if ( view == 0 )
   {
      ImageWindow w = ImageWindow::ActiveWindow();

      if ( w.IsNull() )
      {
         throw Error( "The Annotation interface requires an active image window to import a process instance." );
         return false;
      }

      view = new View( w.MainView() );

      view->AddToDynamicTargets();
   }

   ClearBitmaps();

   instance.Assign( *i );

   annotationPlaced = false;
   leaderPlaced = false;

   if ( view->Window().CurrentView() != *view )
      view->Window().SelectView( *view );

   UpdateControls();

   return true;
}
예제 #17
0
bool RotationInstance::ExecuteOn( View& view )
{
   if ( !view.IsMainView() )
      return false;  // should never reach this point!

   AutoViewLock lock( view );

   ImageVariant image = view.Image();

   if ( image.IsComplexSample() )
      return false;

   double degrees = Round( Deg( p_angle ), 4 );
   if ( degrees == 0 )
   {
      Console().WriteLn( "<end><cbr>&lt;* Identity *&gt;" );
      return true;
   }

   ImageWindow window = view.Window();

   window.RemoveMaskReferences();
   window.RemoveMask();
   window.DeletePreviews();

   Console().EnableAbort();

   StandardStatus status;
   image.SetStatusCallback( &status );

   if ( p_optimizeFast )
      switch ( TruncI( degrees ) )
      {
      case 90:
         Rotate90CCW() >> image;
         return true;
      case -90:
         Rotate90CW() >> image;
         return true;
      case 180:
      case -180:
         Rotate180() >> image;
         return true;
      default:
         break;
      }

   AutoPointer<PixelInterpolation> interpolation( NewInterpolation(
         p_interpolation, 1, 1, 1, 1, true, p_clampingThreshold, p_smoothness, image ) );

   Rotation T( *interpolation, p_angle );

   /*
    * On 32-bit systems, make sure the resulting image requires less than 4 GB.
    */
   if ( sizeof( void* ) == sizeof( uint32 ) )
   {
      int width = image.Width(), height = image.Height();
      T.GetNewSizes( width, height );
      uint64 sz = uint64( width )*uint64( height )*image.NumberOfChannels()*image.BytesPerSample();
      if ( sz > uint64( uint32_max-256 ) )
         throw Error( "Rotation: Invalid operation: Target image dimensions would exceed four gigabytes" );
   }

   T.SetFillValues( p_fillColor );
   T >> image;

   return true;
}
int 
main(int argc, char* argv[])
{
    LibraryInitializer li;

    // parse arguments

    CommandLineOptions opt;
    opt.addOption('v', "videosource",            true,  "Use video source");
    opt.addOption('i', "images",                 false, "Use images");
    opt.addOption('d', "face-detector",          true,  "face detector file");
    opt.addOption('e', "eye-detector",           true,  "eye detector file");
    opt.addOption('m', "mouth-detector",         true,  "mouth detector file");
    opt.addOption('l', "low-resolution",         false, "Use resolution of 320x240 pixels");
    opt.addOption('s', "search-regions",         false, "Show eye and mouth search regions");
    opt.addOption(     "fps",                    false, "Display frames per second");
    opt.addOption('r', "draw-search-rectangles", false, "Draw the search rectangles (i.e. head, eye, etc.)");

    if (argc < 3)
    {
        printf(help_str, opt.helpString().c_str());
        exit(1);
    }

    string fd_fn, ed_fn, md_fn, videosource;
    bool low_resolution, display_fps, use_videosource, use_images, search_regions, display_search_rectangles;
    vector<string> images;
    try
    {
        images                    = opt.parse(argc, argv);
        fd_fn                     = opt.getArgument<string>("face-detector");
        ed_fn                     = opt.getArgument<string>("eye-detector", "");
        md_fn                     = opt.getArgument<string>("mouth-detector", "");
        videosource               = opt.getArgument<string>("videosource", "");
        low_resolution            = opt.parameterSet("low-resolution") > 0;
        display_fps               = opt.parameterSet("fps") > 0;
        use_videosource           = opt.parameterSet("videosource") > 0;
        use_images                = opt.parameterSet("images") > 0;
        search_regions            = opt.parameterSet("search-regions") > 0;
        display_search_rectangles = opt.parameterSet("draw-search-rectangles") > 0;
    }
    catch (CommandLineOptionException e)
    {
        printf(help_str, opt.helpString().c_str());
        exit(1);
    }

    if (!use_videosource && !use_images)
    {
        printf("Either '-v' or '-i' must be given\n");
        printf(help_str, opt.helpString().c_str());
        exit(1);
    }

    // Set up detectors
    BinaryPatternFaceDetector fd(fd_fn);
    fd.setScaleStep(1.2);
    fd.setNeighborDist(1.3);
    auto_ptr<BinaryPatternEyeDetector> ed;
    if (!ed_fn.empty())
        ed.reset(new BinaryPatternEyeDetector(ed_fn));
    auto_ptr<BinaryPatternMouthDetector> md;
    if (!md_fn.empty())
        md.reset(new BinaryPatternMouthDetector(md_fn));

    // Eye center detector
    typedef IsophoteEyeCenterDetector<double> iecd_t; // can be instantiated as float and double (choice defines the algorithmic precision [vs. run-time])
    iecd_t iecd;

    /* default parameters */
    // ...
    double isophote_row_sigma = 1;
    double isophote_col_sigma = 1;
    // options
    bool set_auto_isophote_sigma = false;

    // Set up GUI
    GuiThread thread;
    ImageWindow* imgwin = new ImageWindow("Detector Demo (cam)");
    thread.addClient(imgwin);
    // parameter control 
    okapi::WidgetWindow* win_params = new okapi::WidgetWindow("Parameter Window", 350/*widget width*/, 250/*label width*/);
    thread.addClient(win_params);
    // start the GUI thread
    thread.start();
    // set initial values
    win_params->setSlider("isophote row sigma (sigma)",          isophote_row_sigma, 0, 5);
    win_params->setSlider("isophote col sigma (sigma)",          isophote_col_sigma, 0, 5);     
    win_params->setButton("set auto sigma",                      set_auto_isophote_sigma);     
    win_params->setButton("display search rectangles",           display_search_rectangles);

    double old_ts = -1;
    double fps = -1;

    // Set up VideoSource
    auto_ptr<VideoSource> src;
    if (use_videosource)
    {
        if (videosource.empty() || videosource == "")
        {
            if (low_resolution)
                src.reset(createDefaultCamera(320, 240));
            else
                //src.reset(createDefaultCamera(640, 480));
                src.reset(createDefaultCamera(1024,768));
                //src.reset(createDefaultCamera(1600,1200));
        }
        else
        {
            if (videosource == "")
                src.reset(createVideoSourceFromString(videosource));
            else
                src.reset(createVideoSource("/home/bschauer/devel/local/share/okapi/videoio/videosources.xml","grasshopper"));
        }

        if (!src.get())
        {
            printf("Error opening camera device, make sure cam is connected!\n");
            exit(1);
        }
    }

    while (imgwin->getWindowState() && (use_images || src->getNextFrame()))
    {
        if (use_images && images.empty())
        {
            sleep_ms(20);
            continue;
        }

        string fn;
        cv::Mat img;
        if (use_videosource)
           img = src->getImage();
        else
        {
            fn = images.front();
            images.erase(images.begin());
            img = loadImage(fn);
        }
        cv::Mat aimg = img.clone();
        cv::Mat gimg;
        cv::cvtColor(aimg,gimg,CV_RGB2GRAY);
        ImageDeco deco(aimg);
        deco.setAntiAlias(true);

        /* get current parameter values */
        // ...
        set_auto_isophote_sigma = win_params->getButton("set auto sigma");
        if (!set_auto_isophote_sigma)
        {
            win_params->toggleActivated("isophote row sigma (sigma)", true);
            win_params->toggleActivated("isophote col sigma (sigma)", true);
            isophote_row_sigma = win_params->getSlider("isophote row sigma (sigma)");
            isophote_col_sigma = win_params->getSlider("isophote col sigma (sigma)");
        }
        else
        {
            win_params->toggleActivated("isophote row sigma (sigma)", false);
            win_params->toggleActivated("isophote col sigma (sigma)", false);
        }
        display_search_rectangles = win_params->getButton("display search rectangles");

        // Detect faces
        OKAPI_TIMER_START("detect faces");
        vector<RectDetection> faces = fd.detectFaces(img);
        OKAPI_TIMER_STOP("detect faces");

        double fsize=0; //faces[0].box.width * faces[0].box.height;
        size_t i=0;
        for (size_t j=0; j<faces.size(); j++)
        {
            if ((faces[j].box.width * faces[j].box.height) > fsize)
                i = j;
        }

        //for (size_t i=0; i<faces.size(); ++i)
        if (faces.size() > 0)
        {
            EyeLocations eyes(cv::Point(-1, -1), cv::Point(-1, -1));

            // Detect Mouth
            if (md.get())
            {
                cv::Point2f mouth = fd.getMeanMouthCenter(faces[i].box);
                double mouth_width = fd.getMeanMouthWidth(faces[i].box);

                OKAPI_TIMER_START("detect mouth");
                mouth = md->detectMouth(img, mouth, mouth_width);
                OKAPI_TIMER_STOP("detect mouth");

                if (mouth.x >= 0)
                {
                    deco.setColor(255, 0, 255);
                    deco.setThickness(1);
                    deco.drawCircle(cvRound(mouth.x), cvRound(mouth.y), 3);
                }
            }

            // Detect eyes
            if (ed.get())
            {
                cv::Point2f le, re;
                le = fd.getMeanLeftEye(faces[i].box);
                re = fd.getMeanRightEye(faces[i].box);

                OKAPI_TIMER_START("detect eyes");
                eyes = ed->detectEyes(img, le, re);
                OKAPI_TIMER_STOP("detect eyes");

                /*if (search_regions)
                {
                    cv::Rect left_eye_roi, right_eye_roi;
                    int min_result_width, max_result_width;
                    ed->getSearchRegions(img, le, re, left_eye_roi, right_eye_roi,
                                         min_result_width, max_result_width);
                    deco.setThickness(1);
                    deco.setColor(255, 127, 127);
                    deco.drawRect(left_eye_roi);
                    deco.drawRect(right_eye_roi);
                }*/

                // Draw eye locations
                deco.setThickness(1);
                deco.setColor(0, 127, 0);
                if (eyes.left.x > 0)
                    deco.drawCircle(eyes.left.x, eyes.left.y, 3);
                if (eyes.right.x > 0)
                    deco.drawCircle(eyes.right.x, eyes.right.y, 3);
            }

            // Draw rotated face bounding box
            if (eyes.isValid())
            {
                // Draw detected face (lightly)
                deco.setColor(127, 127, 127);
                deco.setThickness(1);
                deco.drawRect(faces[i].box);

                // Draw rotated face box
                cv::Point2f eye_center(eyes.right + eyes.left);
                eye_center *= 0.5f;
                double eye_dist = cv::norm(eyes.right - eyes.left);
                double angle = atan2(eyes.left.y - eyes.right.y, eyes.right.x - eyes.left.x);
                cv::Point2f offset(sin(angle), cos(angle));
                offset *= 0.25f * (float)eye_dist;
                cv::RotatedRect rrect(eye_center + offset, cv::Size2f(eye_dist * 2.0, eye_dist * 1.75), - angle / CV_PI * 180);
                deco.setColor(0, 255, 0);
                deco.setThickness(2);
                deco.drawRect(rrect);

                // Run the eye detector
                if (set_auto_isophote_sigma)
                    iecd.setAutoSigma();
                else
                    iecd.setSigma(isophote_row_sigma,isophote_col_sigma);
                OKAPI_TIMER_START("iecd.detectEyeCenters");
                EyeCenterLocations<iecd_t::coord_t> eye_centers = iecd.detectEyeCenters(gimg,faces[i].box,eyes.left,eyes.right);
                OKAPI_TIMER_STOP("iecd.detectEyeCenters");
                if (set_auto_isophote_sigma)
                {
                    win_params->setSlider("isophote row sigma (sigma)",          iecd.getRowSigma(), 0, 5);
                    win_params->setSlider("isophote col sigma (sigma)",          iecd.getColSigma(), 0, 5);    
                }
                deco.setThickness(2);
                deco.setColor(255,0,0);
                deco.drawCircle(eye_centers.left.x,eye_centers.left.y,3);
                deco.drawCircle(eye_centers.right.x,eye_centers.right.y,3);
                deco.setThickness(1);
                deco.drawLine(eye_centers.left.x,eye_centers.left.y,eye_centers.right.x,eye_centers.right.y);

                // Draw search regions, i.e. regions of interest
                cv::Rect_<iecd_t::coord_t> left_roi, right_roi;
                iecd.getCurrentSearchRegions(left_roi, right_roi);
                if (display_search_rectangles)
                {
                    if (iecd_t::isValidCoord(left_roi))
                    {
                        deco.setThickness(1);
                        deco.setColor(255, 127, 127);
                        deco.drawRect(left_roi);
                    }
                    if (iecd_t::isValidCoord(right_roi))
                    {
                        deco.setThickness(1);
                        deco.setColor(255, 127, 127);
                        deco.drawRect(right_roi); 
                    }
                }
                //cv::Mat left_eye_image(left_roi.height,left_roi.width,img.type());
                //cv::Mat right_eye_image(left_roi.height,left_roi.width,img.type());
                cv::Mat left_eye_image(img,left_roi);
                cv::Mat right_eye_image(img,right_roi);
                cv::Mat left_eye_image_resized;
                cv::Mat right_eye_image_resized;
                cv::resize(left_eye_image,left_eye_image_resized,cv::Size(), 3, 3);
                cv::resize(right_eye_image,right_eye_image_resized,cv::Size(), 3, 3);
                ImageDeco dleir(left_eye_image_resized);
                ImageDeco dreir(right_eye_image_resized);
                dleir.setThickness(2);
                dleir.setColor(255,0,0);
                dleir.drawCircle(3*(eye_centers.left.x - left_roi.x),3*(eye_centers.left.y - left_roi.y),3);
                dreir.setThickness(2);
                dreir.setColor(255,0,0);
                dreir.drawCircle(3*(eye_centers.right.x - right_roi.x),3*(eye_centers.right.y - right_roi.y),3); 
                imgwin->setImage("left_eye_image", left_eye_image_resized);
                imgwin->setImage("right_eye_image", right_eye_image_resized);
            }
            else
            {
                // Draw detected face (strongly)
                deco.setColor(127, 0, 0);
                deco.setThickness(1);
                deco.drawRect(faces[i].box);

                // Run the eye detector
                if (set_auto_isophote_sigma)
                    iecd.setAutoSigma();
                else
                    iecd.setSigma(isophote_row_sigma,isophote_col_sigma);
                OKAPI_TIMER_START("iecd.detectEyeCenters");
                EyeCenterLocations<iecd_t::coord_t> eye_centers = iecd.detectEyeCenters(gimg,faces[i].box,iecd_t::getInvalidCoordPoint(),iecd_t::getInvalidCoordPoint());
                OKAPI_TIMER_STOP("iecd.detectEyeCenters");
                if (set_auto_isophote_sigma)
                {
                    win_params->setSlider("isophote row sigma (sigma)",          iecd.getRowSigma(), 0, 5);
                    win_params->setSlider("isophote col sigma (sigma)",          iecd.getColSigma(), 0, 5);    
                }
                deco.setThickness(1);
                deco.setColor(127,0,0);
                deco.drawCircle(eye_centers.left.x,eye_centers.left.y,3);
                deco.drawCircle(eye_centers.right.x,eye_centers.right.y,3);
                deco.drawLine(eye_centers.left.x,eye_centers.left.y,eye_centers.right.x,eye_centers.right.y);
            }
        }

        if (display_fps)
        {
            double new_ts = src->getTimestamp();

            if (old_ts < 0)
                old_ts = new_ts - 0.1;

            // Compute fps
            double new_fps = 1 / (new_ts - old_ts);
            if (fps < 0)
                fps = new_fps;
            else
                fps = 0.95 * fps + 0.05 * new_fps;

            char buf[1000];
            sprintf(buf, "%4.1f fps\n", fps);
            old_ts = new_ts;

            // Write frame rate
            deco.setColor(255, 255, 255);
            deco.setThickness(1);
            deco.drawText(buf, 0, 15);
        }

        // Display annotated image
        string name;
        if (use_videosource)
            name = "Video";
        else
            name = basename(fn);
        imgwin->setImage(name, aimg, low_resolution ? 2 : 1);
        imgwin->setImage("accumulator",iecd.getMatAcc(), low_resolution ? 2 : 1);
    }

    return 0;
}
예제 #19
0
Fl_Double_Window* make_window() {
  Fl_Double_Window* w;
  { Fl_Double_Window* o = controls = new Fl_Double_Window(255, 60, "Rotation Angle");
    w = o;
    { Fl_Value_Input* o = angle_value = new Fl_Value_Input(180, 5, 70, 25, "Angle");
      o->minimum(-65000);
      o->maximum(65000);
      o->callback((Fl_Callback*)cb_angle_value);
      o->when(FL_WHEN_ENTER_KEY);
    }
    { Fl_Roller* o = angle_roller = new Fl_Roller(5, 35, 245, 20);
      o->type(1);
      o->minimum(65000);
      o->maximum(-65000);
      o->step(0.1);
      o->callback((Fl_Callback*)cb_angle_roller);
    }
    { Fl_Button* o = new Fl_Button(70, 5, 55, 25, "next");
      o->shortcut(0x66);
      o->callback((Fl_Callback*)cb_next);
    }
    { Fl_Button* o = new Fl_Button(5, 5, 55, 25, "prev");
      o->shortcut(0x64);
      o->callback((Fl_Callback*)cb_prev);
    }
    o->end();
    o->resizable(o);
  }
  { ImageWindow* o = iw1 = new ImageWindow(100, 100);
    w = o;
    o->box(FL_FLAT_BOX);
    o->color(FL_BACKGROUND_COLOR);
    o->selection_color(FL_BACKGROUND_COLOR);
    o->labeltype(FL_NO_LABEL);
    o->labelfont(0);
    o->labelsize(14);
    o->labelcolor(FL_FOREGROUND_COLOR);
    o->align(FL_ALIGN_TOP);
    o->when(FL_WHEN_RELEASE);
    o->end();
  }
  { ImageWindow* o = iw2 = new ImageWindow(100, 100);
    w = o;
    o->box(FL_FLAT_BOX);
    o->color(FL_BACKGROUND_COLOR);
    o->selection_color(FL_BACKGROUND_COLOR);
    o->labeltype(FL_NO_LABEL);
    o->labelfont(0);
    o->labelsize(14);
    o->labelcolor(FL_FOREGROUND_COLOR);
    o->align(FL_ALIGN_TOP);
    o->when(FL_WHEN_RELEASE);
    o->end();
  }
  return w;
}
예제 #20
0
bool KuickShow::showImage( const KFileItem *fi,
                           bool newWindow, bool fullscreen, bool moveToTopLeft )
{
    newWindow  |= !m_viewer;
    fullscreen |= (newWindow && kdata->fullScreen);
    if ( FileWidget::isImage( fi ) ) {

        if ( newWindow ) {
            m_viewer = new ImageWindow( kdata->idata, id, 0L, "image window" );
            m_viewer->setFullscreen( fullscreen );
            s_viewers.append( m_viewer );

            connect( m_viewer, SIGNAL( destroyed() ), SLOT( viewerDeleted() ));
            connect( m_viewer, SIGNAL( sigFocusWindow( ImageWindow *) ),
                     this, SLOT( slotSetActiveViewer( ImageWindow * ) ));
            connect( m_viewer, SIGNAL( sigImageError(const KuickFile *, const QString& ) ),
                     this, SLOT( messageCantLoadImage(const KuickFile *, const QString &) ));
            connect( m_viewer, SIGNAL( requestImage( ImageWindow *, int )),
                     this, SLOT( slotAdvanceImage( ImageWindow *, int )));
	    connect( m_viewer, SIGNAL( pauseSlideShowSignal() ),
		     this, SLOT( pauseSlideShow() ) );
            connect( m_viewer, SIGNAL (deleteImage (ImageWindow *)),
                     this, SLOT (slotDeleteCurrentImage (ImageWindow *)));
            connect( m_viewer, SIGNAL (trashImage (ImageWindow *)),
                     this, SLOT (slotTrashCurrentImage (ImageWindow *)));
            if ( s_viewers.count() == 1 && moveToTopLeft ) {
                // we have to move to 0x0 before showing _and_
                // after showing, otherwise we get some bogus geometry()
                m_viewer->move( Kuick::workArea().topLeft() );
            }

            m_viewer->installEventFilter( this );
        }

        // for some strange reason, m_viewer sometimes changes during the
        // next few lines of code, so as a workaround, we use safeViewer here.
        // This happens when calling KuickShow with two or more remote-url
        // arguments on the commandline, where the first one is loaded properly
        // and the second isn't (e.g. because it is a pdf or something else,
        // Imlib can't load).
        ImageWindow *safeViewer = m_viewer;

//        file->waitForDownload( this );
//        QString filename;
//        KIO::NetAccess::download(fi->url(), filename, this);

        if ( !safeViewer->showNextImage( fi->url() ) ) {
            m_viewer = safeViewer;
            safeViewer->close( true ); // couldn't load image, close window
        }
        else {
//            safeViewer->setFullscreen( fullscreen );

            if ( newWindow ) {
//                safeViewer->show();

                if ( !fullscreen && s_viewers.count() == 1 && moveToTopLeft ) {
                    // the WM might have moved us after showing -> strike back!
                    // move the first image to 0x0 workarea coord
                    safeViewer->move( Kuick::workArea().topLeft() );
                }
            }

            if ( kdata->preloadImage && fileWidget ) {
                KFileItem *item = 0L;                 // don't move cursor
                item = fileWidget->getItem( FileWidget::Next, true );
                if ( item )
                    safeViewer->cacheImage( item->url() );
            }

            m_viewer = safeViewer;
	    return true;
        } // m_viewer created successfully
    } // isImage

    return false;
}
예제 #21
0
void AnnotationInterface::DynamicMousePress( View& v, const DPoint& p, int button, unsigned buttons, unsigned modifiers )
{
   // we only use left mouse button
   if ( button != MouseButton::Left )
      return;

   if (view == 0)
   {
      // can not run on previews
      if ( !v.IsMainView() )
         throw Error( "Annotation cannot run on previews. Please select a main view." );

      view = new View( v );
   }

   // only handle events in our active view
   if (v != *view)
      return;

   // get view image window
   ImageWindow w = view->Window();

   // and image coordinates of the click point
   int imageX = RoundI(p.x);
   int imageY = RoundI(p.y);

   // if annotation is not yet placed, place it now
   if (!annotationPlaced)
   {
      // set annotation position
      instance.annotationPositionX = imageX;
      instance.annotationPositionY = imageY;
      annotationPlaced = true;

      // place leader if needed
      if (instance.annotationShowLeader)
      {
         PlaceLeaderDefault();
      }

      // update annotation rectangle
      UpdateAnnotationRect( true );

      // redraw dynamic view
      UpdateView();

      // start dragging mode until user release the mouse
      dragging = DraggingType::Text;
      w.SetDynamicCursor(move_all_XPM, 10, 10);
   }
   // if the annotation is already placed
   else
   {
      // if mouse is pressed on annotation text rectangle
      // let's start dragging
      if (textRect.Includes(imageX, imageY))
      {
         // with Ctrl, both text and leader are dragged simulaneously
         if (modifiers & KeyModifier::Control)
         {
            dragging = DraggingType::Both;
         }
         // otherwise, just text is dragged
         else
         {
            dragging = DraggingType::Text;
         }
      }
      // if mouse is pressed on annotation leader rectangle and leader is visible
      // let's start dragging
      else if (instance.annotationShowLeader && leaderRect.Includes(imageX, imageY))
      {
         // with Ctrl, both text and leader are dragged simulaneously
         if (modifiers & KeyModifier::Control)
         {
            dragging = DraggingType::Both;
         }
         // otherwise, just leader endpoint is dragged
         else
         {
            dragging = DraggingType::Leader;
         }
      }
   }

   // if any dragging is started, remember current point
   if (dragging != DraggingType::None)
   {
      lastX = imageX;
      lastY = imageY;
   }
}
예제 #22
0
void ProcessImplementation::LaunchOn( ImageWindow& w ) const
{
   View mv( w.MainView() );
   LaunchOn( mv );
}
Widget RenderingOptionsDialog::createDialog(Widget parent)
{
    Arg arg[10];
    ImageWindow *iw = this->imageWindow;

    XtSetArg(arg[0], XmNautoUnmanage, False);
//    Widget dialog = XmCreateFormDialog( parent, this->name, arg, 1);
    Widget dialog = this->CreateMainForm( parent, this->name, arg, 1);

    XtVaSetValues(XtParent(dialog), XmNtitle, "Rendering...", NULL);

    Widget modeLabel = XtVaCreateManagedWidget(
	"modeLabel", xmLabelWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_FORM,
        XmNtopOffset       , 10,
        XmNleftAttachment  , XmATTACH_FORM,
        XmNleftOffset      , 5,
        XmNrightAttachment , XmATTACH_FORM,
        XmNrightOffset     , 5,
	NULL);

    Widget modeSection = XtVaCreateManagedWidget(
	"modeSection", xmRowColumnWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , modeLabel,
        XmNtopOffset       , 10,
        XmNleftAttachment  , XmATTACH_FORM,
        XmNleftOffset      , 5,
        XmNrightAttachment , XmATTACH_FORM,
        XmNrightOffset     , 5,

        XmNorientation     , XmHORIZONTAL,
        XmNspacing         , 21,
        XmNmarginWidth     , 21,
        XmNradioBehavior   , True,
	NULL);

    this->softwareButton = new ToggleButtonInterface(modeSection,
	  "softwareButton", iw->getSoftwareCmd(), TRUE);
    XtVaSetValues(this->softwareButton->getRootWidget(),
        XmNindicatorType   , XmONE_OF_MANY,
        XmNshadowThickness , 0,
	NULL);
    this->hardwareButton = new ToggleButtonInterface(modeSection,
	  "hardwareButton", iw->getHardwareCmd(), FALSE);
    XtVaSetValues(this->hardwareButton->getRootWidget(),
        XmNindicatorType   , XmONE_OF_MANY,
        XmNshadowThickness , 0,
	NULL);

    Widget separator1 = XtVaCreateManagedWidget(
	"separator1", xmSeparatorWidgetClass, dialog,
        XmNtopAttachment    , XmATTACH_WIDGET,
        XmNtopWidget        , modeSection,
        XmNtopOffset        , 10,
        XmNleftAttachment   , XmATTACH_FORM,
        XmNleftOffset       , 2,
        XmNrightAttachment  , XmATTACH_FORM,
        XmNrightOffset      , 2,
	NULL);

    Widget upLabel = XtVaCreateManagedWidget(
	"upLabel", xmLabelWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , separator1,
        XmNtopOffset       , 10,
        XmNleftAttachment  , XmATTACH_FORM,
        XmNleftOffset      , 5,
        XmNrightAttachment , XmATTACH_FORM,
        XmNrightOffset     , 5,
	NULL);

    Widget upApproxLabel = XtVaCreateManagedWidget(
	"upApproxLabel", xmLabelWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , upLabel,
        XmNtopOffset       , 10,
        XmNleftAttachment  , XmATTACH_FORM,
        XmNleftOffset      , 5,
	NULL);

#if defined(aviion)
    XmString xmstr = XmStringCreateLtoR ("", "bold");
#endif
    Widget upPulldown = this->createUpPulldown(dialog);
    Widget buttonUpOptionMenu = this->buttonUpOptionMenu =
	     XtVaCreateManagedWidget(
	"buttonUpOptionMenu", xmRowColumnWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , upLabel,
        XmNtopOffset       , 10,
        XmNrightAttachment , XmATTACH_FORM,
        XmNrightOffset     , 2,
        XmNentryAlignment  , XmALIGNMENT_CENTER,
	XmNrowColumnType   , XmMENU_OPTION,
	XmNsubMenuId       , upPulldown,
#if defined(aviion)
	XmNlabelString     , xmstr,
#endif
	NULL);

    Widget upDensityLabel = XtVaCreateManagedWidget(
	"upDensityLabel", xmLabelWidgetClass, dialog,
        XmNtopAttachment  , XmATTACH_WIDGET,
        XmNtopWidget      , buttonUpOptionMenu,
        XmNtopOffset      , 10,
        XmNleftAttachment , XmATTACH_FORM,
        XmNleftOffset     , 5,
	NULL);

    this->upEveryNumber = XtVaCreateManagedWidget(
       "upEveryNumber", xmNumberWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , buttonUpOptionMenu,
        XmNtopOffset       , 10,
        XmNrightAttachment , XmATTACH_FORM,
        XmNrightOffset     , 5,
        XmNiMinimum        , 1,
        XmNiMaximum        , 1000000,
        XmNrecomputeSize   , False,
        XmNdataType        , INTEGER,
        XmNcharPlaces      , 7,
        XmNeditable        , True,
	NULL);
    XtAddCallback(this->upEveryNumber, XmNactivateCallback,
        (XtCallbackProc)RenderingOptionsDialog_NumberCB, (XtPointer)this);


    Widget separator2 = XtVaCreateManagedWidget(
	"separator2", xmSeparatorWidgetClass, dialog,
        XmNtopAttachment    , XmATTACH_WIDGET,
        XmNtopWidget        , this->upEveryNumber,
        XmNtopOffset        , 10,
        XmNleftAttachment   , XmATTACH_FORM,
        XmNleftOffset       , 2,
        XmNrightAttachment  , XmATTACH_FORM,
        XmNrightOffset      , 2,
	NULL);

    Widget downLabel = XtVaCreateManagedWidget(
	"downLabel", xmLabelWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , separator2,
        XmNtopOffset       , 10,
        XmNleftAttachment  , XmATTACH_FORM,
        XmNleftOffset      , 5,
        XmNrightAttachment , XmATTACH_FORM,
        XmNrightOffset     , 5,
	NULL);

    Widget downApproxLabel = XtVaCreateManagedWidget(
	"downApproxLabel", xmLabelWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , downLabel,
        XmNtopOffset       , 10,
        XmNleftAttachment  , XmATTACH_FORM,
        XmNleftOffset      , 5,
	NULL);

    Widget downPulldown = this->createDownPulldown(dialog);
    Widget buttonDownOptionMenu = this->buttonDownOptionMenu =
	     XtVaCreateManagedWidget(
	"buttonDownOptionMenu", xmRowColumnWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , downLabel,
        XmNtopOffset       , 10,
        XmNrightAttachment , XmATTACH_FORM,
        XmNrightOffset     , 2,
        XmNentryAlignment  , XmALIGNMENT_CENTER,
	XmNrowColumnType   , XmMENU_OPTION,
	XmNsubMenuId       , downPulldown,
#if defined(aviion)
	XmNlabelString     , xmstr,
	NULL);
    XmStringFree(xmstr);
#else
	NULL);
#endif

    Widget downDensityLabel = XtVaCreateManagedWidget(
	"downDensityLabel", xmLabelWidgetClass, dialog,
        XmNtopAttachment  , XmATTACH_WIDGET,
        XmNtopWidget      , buttonDownOptionMenu,
        XmNtopOffset      , 10,
        XmNleftAttachment , XmATTACH_FORM,
        XmNleftOffset     , 5,
	NULL);

    this->downEveryNumber = XtVaCreateManagedWidget(
       "downEveryNumber", xmNumberWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , buttonDownOptionMenu,
        XmNtopOffset       , 10,
        XmNrightAttachment , XmATTACH_FORM,
        XmNrightOffset     , 5,
        XmNiMinimum        , 1,
        XmNiMaximum        , 1000000,
        XmNrecomputeSize   , False,
        XmNdataType        , INTEGER,
        XmNcharPlaces      , 7,
        XmNeditable        , True,
	NULL);
    XtAddCallback(this->downEveryNumber, XmNactivateCallback,
        (XtCallbackProc)RenderingOptionsDialog_NumberCB, (XtPointer)this);

    Widget separator3 = XtVaCreateManagedWidget(
	"separator3", xmSeparatorWidgetClass, dialog,
        XmNtopAttachment   , XmATTACH_WIDGET,
        XmNtopWidget       , this->downEveryNumber,
        XmNtopOffset       , 10,
        XmNleftAttachment  , XmATTACH_FORM,
        XmNleftOffset      , 5,
        XmNrightAttachment , XmATTACH_FORM,
        XmNrightOffset     , 5,
	NULL);

    this->cancel =  XtVaCreateManagedWidget(
	"closeButton", xmPushButtonWidgetClass, dialog,
	XmNtopAttachment  , XmATTACH_WIDGET,
	XmNtopWidget      , separator3,
	XmNtopOffset      , 10,
	XmNleftAttachment , XmATTACH_FORM,
	XmNleftOffset     , 5,
	XmNbottomAttachment, XmATTACH_FORM,
	XmNbottomOffset   , 5,
	XmNrecomputeSize  , False,
	NULL);
    
    this->sensitizeRenderMode(! iw->isRenderModeConnected());
    this->sensitizeButtonUpApprox(! iw->isButtonUpApproxConnected());
    this->sensitizeButtonDownApprox(! iw->isButtonDownApproxConnected());
    this->sensitizeButtonUpDensity(! iw->isButtonUpDensityConnected());
    this->sensitizeButtonDownDensity(! iw->isButtonDownDensityConnected());

    return dialog;    
}
예제 #24
0
bool interpret(string cmd, vector<string> args){
    if(cmd == "help"){
        if(args.size()==0){
            cout << "Current commands:" << endl;
            for(auto it:help)
                cout << " -" << it.first << endl;
        }else if(args.size()==1){
            auto it = help.find(args[0]);
            if(it!=help.end())
                cout << it->second << endl;
            else
                cout << "Unknown command" << endl;
        }else{
            cout << help[cmd] << endl;
        }
    }else if(cmd == "exit"){
        running = false;
    }else if(cmd == "show"){
        if(args.size()!=1){
            cout << help[cmd] << endl;
        }else{
            if(args[0]=="windows"){
                cout << "Windows(Image): " << windows.size() << endl;
                for(auto it:windows)
                    cout << " -" << it.first << "(" << it.second->getImageName() << ")" << endl;
            }else if(args[0]=="images"){
                cout << "Images: " << images.size() << endl;
                for(auto it:images)
                    cout << " -" << it.first << endl;
            }else if(args[0]=="options"){
                cout << "Options: " << options.size() << endl;
                for(const string& opt:options)
                    cout << " -" << opt << endl;
            }else if(args[0]=="imageInfo"){
                if(bindedImage==""){
                    cout << "Not image binded" << endl;
                }else{
                    auto it = images[bindedImage];
                    Image* img = it->lock();
                    if(!img->isValid()){
                        cout << "Uninitialized or invalid image" << endl;
                    }else{
                        cout << "Image information:" << endl
                             << "-Width: " << img->getX() << endl
                             << "-Height: " << img->getY() << endl;
                    }
                    it->unlock();
                }
            }else{
                cout << help[cmd] << endl;
            }
        }
    }else if(cmd == "open"){
        if(args.size()!=1 || args[0].size()<4){
            cout << help[cmd] << endl;
        }else{
            if(bindedImage==""){
                cout << "Not image binded" << endl;
            }else if((args[0].substr(args[0].size()-4,4)==".pbm" && !images[bindedImage]->call<bool>([](Image*& image, void* data)->bool{return image->loadFromPBM(*(string*)data);}, &args[0]))
            || (args[0].substr(args[0].size()-4,4)==".bmp" && !images[bindedImage]->call<bool>([](Image*& image, void* data)->bool{return image->loadFromBMP(*(string*)data);}, &args[0]))){
                cout << "Couldn't open file..." << endl;
            }else{
                cout << "Image loaded.\n-Width: " << images[bindedImage]->getX() << "\n-Height: " << images[bindedImage]->getY() << endl;
            }
        }
    }else if(cmd == "save"){
        if(args.size()!=1 || args[0].size()<4){
            cout << help[cmd] << endl;
        }else{
            if(bindedImage==""){
                cout << "Not image binded" << endl;
            }else if(!images[bindedImage]->call<bool>([](Image*& image, void* data)->bool{return image->saveToBMP(*(string*)data);}, &args[0])){
                cout << "Couldn't save file..." << endl;
            }
        }
    }else if(cmd == "saveascii"){
        if(args.size()!=1 || args[0].size()<4){
            cout << help[cmd] << endl;
        }else{
            if(bindedImage==""){
                cout << "Not image binded" << endl;
            }else if(!images[bindedImage]->call<bool>([](Image*& image, void* data)->bool{return image->saveToAsciiArt(*(string*)data);}, &args[0])){
                cout << "Couldn't save file..." << endl;
            }
        }
    }else if(cmd == "bind"){
        if(args.size()!=2){
            cout << help[cmd] << endl;
        }else{
            if(args[0]=="window"){
                if(windows.find(args[1])!=windows.end())
                    bindedWindow = args[1];
                else
                    cout << "Inexistent window" << endl;
            }else if(args[0]=="image"){
                if(images.find(args[1])!=images.end())
                    bindedImage = args[1];
                else
                    cout << "Inexistent image" << endl;
            }else{
                cout << help[cmd] << endl;
            }
        }
    }else if(cmd == "create"){
        if(args.size()!=2){
            cout << help[cmd] << endl;
        }else{
            if(args[0]=="window"){
                if(windows.find(args[1])==windows.end()){
                    windows[args[1]] = new ImageWindow();
                    if(options.find("bindOnCreate")!=options.end())
                        bindedWindow = args[1];
                }else
                    cout << "Existent window" << endl;
            }else if(args[0]=="image"){
                if(images.find(args[1])==images.end()){
                    images[args[1]] = new MutexedImage(new Image(), true);
                    if(options.find("bindOnCreate")!=options.end())
                        bindedImage = args[1];
                }else
                    cout << "Existent image" << endl;
            }else{
                cout << help[cmd] << endl;
            }
        }
    }else if(cmd == "destroy"){
        if(args.size()!=2){
            cout << help[cmd] << endl;
        }else{
            if(args[0]=="window"){
                auto it = windows.find(args[1]);
                if(it!=windows.end()){
                    lock_guard<mutex> _l(globalMutex);
                    delete it->second;
                    windows.erase(it);
                    bindedWindow = "";
                }else
                    cout << "Inexistent window" << endl;
            }else if(args[0]=="image"){
                auto it = images.find(args[1]);
                if(it!=images.end()){
                    lock_guard<mutex> _l(globalMutex);
                    it->second->setDeleteOnDestroy(true);
                    delete it->second;
                    images.erase(it);
                    cout << "Windows detached:";
                    for(auto p : windows){
                        if(p.second->getImageName()==args[1]){
                            cout << " " << p.first;
                            p.second->setImageName("");
                        }
                    }
                    cout << endl;
                    bindedImage = "";
                }else
                    cout << "Inexistent image" << endl;
            }else{
                cout << help[cmd] << endl;
            }
        }
    }else if(cmd == "copy"){
        if(args.size()!=2){
            cout << help[cmd] << endl;
        }else{
            auto it = images.find(args[0]);
            auto it2 = images.find(args[1]);
            if(it==images.end()){
                cout << "Inexistent image in first argument" << endl;
            }else if(it2==images.end()){
                cout << "Inexistent image in second argument" << endl;
            }else{
                Image* img = it->second->lock();
                Image* img2 = it2->second->lock();
                (*img2) = *img;
                it->second->unlock();
                it2->second->unlock();
            }
        }
    }else if(cmd == "attach"){
        if(args.size()!=0){
            cout << help[cmd] << endl;
        }else{
            if(bindedImage==""){
                cout << "Not image binded" << endl;
            }else if(bindedWindow==""){
                cout << "Not window binded" << endl;
            }else{
                lock_guard<mutex> _l(globalMutex);
                windows[bindedWindow]->setImageName(bindedImage);
            }
        }
    }else if(cmd == "detach"){
        if(args.size()!=0){
            cout << help[cmd] << endl;
        }else{
            if(bindedWindow==""){
                cout << "Not window binded" << endl;
            }else{
                lock_guard<mutex> _l(globalMutex);
                ImageWindow* w = windows[bindedWindow];
                if(w->getImageName()=="")
                    cout << "Window not attached" << endl;
                else
                    w->setImageName("");
            }
        }
    }else if(cmd == "option"){
        if(args.size()!=2){
            cout << help[cmd] << endl;
        }else{
            if(args[0] == "set"){
                if(options.find(args[1]) == options.end())
                    options.insert(args[1]);
                else
                    cout << "Option already set" << endl;
            }else if(args[0] == "unset"){
                if(options.find(args[1]) == options.end())
                    options.erase(args[1]);
                else
                    cout << "Inexistent option" << endl;
            }else{
                cout << help[cmd] << endl;
            }
        }
    }else{
        cout << "Unknown command. Type 'help' for see commands." << endl;
    }
    return false;
}
예제 #25
0
bool KuickShow::eventFilter( QObject *o, QEvent *e )
{
    if ( m_delayedRepeatItem ) // we probably need to install an eventFilter over
	{
        return true;    // kapp, to make it really safe
	}

    bool ret = false;
    int eventType = e->type();
    QKeyEvent *k = 0L;
    if ( eventType == QEvent::KeyPress )
        k = static_cast<QKeyEvent *>( e );

    if ( k ) {
        if ( KStdAccel::quit().contains( KKey( k ) ) ) {
            saveSettings();
            deleteAllViewers();
            FileCache::shutdown();
            ::exit(0);
        }
        else if ( KStdAccel::help().contains( KKey( k ) ) ) {
            appHelpActivated();
            return true;
        }
    }


    ImageWindow *window = dynamic_cast<ImageWindow*>( o );

    if ( window ) {
        // The XWindow used to display Imlib's image is being resized when
        // switching images, causing enter- and leaveevents for this
        // ImageWindow, leading to the cursor being unhidden. So we simply
        // don't pass those events to KCursor to prevent that.
        if ( eventType != QEvent::Leave && eventType != QEvent::Enter )
            KCursor::autoHideEventFilter( o, e );

        m_viewer = window;
        QString img;
        KFileItem *item = 0L;      // the image to be shown
        KFileItem *item_next = 0L; // the image to be cached

        if ( k ) { // keypress
            ret = true;
            int key = k->key();

            // Key_Shift shouldn't load the browser in nobrowser mode, it
            // is used for zooming in the imagewindow
            // Key_Alt shouldn't either - otherwise Alt+F4 doesn't work, the
            // F4 gets eaten (by NetAccess' modal dialog maybe?)

            if ( !fileWidget )
            {
                if ( key != Key_Escape && key != Key_Shift && key != Key_Alt )
                {
                    KuickFile *file = m_viewer->currentFile();
//                    QFileInfo fi( m_viewer->filename() );
//                    start.setPath( fi.dirPath( true ) );
                    initGUI( file->url().upURL() );

                    // the fileBrowser will list the start-directory
                    // asynchronously so we can't immediately continue. There
                    // is no current-item and no next-item (actually no item
                    // at all). So we tell the browser the initial
                    // current-item and wait for it to tell us when it's ready.
                    // Then we will replay this KeyEvent.
                    delayedRepeatEvent( m_viewer, k );

                    // OK, once again, we have a problem with the now async and
                    // sync KDirLister :( If the startDir is already cached by
                    // KDirLister, we won't ever get that finished() signal
                    // because it is emitted before we can connect(). So if
                    // our dirlister has a rootFileItem, we assume the
                    // directory is read already and simply call
                    // slotReplayEvent() without the need for the finished()
                    // signal.

                    // see slotAdvanceImage() for similar code
                    if ( fileWidget->dirLister()->isFinished() )
                    {
                        if ( fileWidget->dirLister()->rootItem() )
                        {
                            fileWidget->setCurrentItem( file->url().fileName() );
                            QTimer::singleShot( 0, this, SLOT( slotReplayEvent()));
                        }
                        else // finished, but no root-item -- probably an error, kill repeat-item!
                        {
                            abortDelayedEvent();
                        }
                    }
                    else // not finished yet
                    {
                        fileWidget->setInitialItem( file->url().fileName() );
                        connect( fileWidget, SIGNAL( finished() ),
                                 SLOT( slotReplayEvent() ));
                    }

                    return true;
                }

                return KMainWindow::eventFilter( o, e );
            }

            // we definitely have a fileWidget here!

            KKey kkey( k );
            if ( key == Key_Home || KStdAccel::home().contains( kkey ) )
            {
                item = fileWidget->gotoFirstImage();
                item_next = fileWidget->getNext( false );
            }

            else if ( key == Key_End || KStdAccel::end().contains( kkey ) )
            {
                item = fileWidget->gotoLastImage();
                item_next = fileWidget->getPrevious( false );
            }

            else if ( fileWidget->actionCollection()->action("delete")->shortcut().contains( key ))
            {
                kdDebug() << "WOW, deletion happens here!" << endl;
//      KFileItem *cur = fileWidget->getCurrentItem( false );
                (void) fileWidget->getCurrentItem( false );
                item = fileWidget->getNext( false ); // don't move
                if ( !item )
                    item = fileWidget->getPrevious( false );
                KFileItem it( KFileItem::Unknown, KFileItem::Unknown,
                              m_viewer->url() );
                KFileItemList list;
                list.append( &it );
                if ( fileWidget->del(list, window,
                                     (k->state() & ShiftButton) == 0) == 0L )
                    return true; // aborted deletion

                // ### check failure asynchronously and restore old item?
                fileWidget->setCurrentItem( item );
            }

            else if ( m_toggleBrowserAction->shortcut().contains( key ) )
            {
                toggleBrowser();
                return true; // don't pass keyEvent
            }

            else
                ret = false;


            if ( FileWidget::isImage( item ) ) {
//                QString filename;
//                KIO::NetAccess::download(item->url(), filename, this);
                m_viewer->showNextImage( item->url() );

                if ( kdata->preloadImage && item_next ) { // preload next image
                    if ( FileWidget::isImage( item_next ) )
                        m_viewer->cacheImage( item_next->url() );
                }

                ret = true; // don't pass keyEvent
            }
        } // keyPressEvent on ImageWindow


        // doubleclick closes image window
        // and shows browser when last window closed via doubleclick
        else if ( eventType == QEvent::MouseButtonDblClick )
        {
            QMouseEvent *ev = static_cast<QMouseEvent*>( e );
            if ( ev->button() == LeftButton )
            {
                if ( s_viewers.count() == 1 )
                {
                    if ( !fileWidget )
                    {
//                        KURL start;
//                        QFileInfo fi( window->filename() );
//                        start.setPath( fi.dirPath( true ) );
                        initGUI( window->currentFile()->url().fileName() );
                    }
                    show();
                    raise();
                }

                window->close( true );

                ev->accept();
                ret = true;
            }
        }

    } // isA ImageWindow


    if ( ret )
        return true;

    return KMainWindow::eventFilter( o, e );
}
예제 #26
0
ArgumentList ExtractArguments( const StringList& argv, argument_item_mode mode, ArgumentOptions options )
{
   bool noItems             = mode == ArgumentItemMode::NoItems;
   bool itemsAsFiles        = mode == ArgumentItemMode::AsFiles;
   bool itemsAsViews        = mode == ArgumentItemMode::AsViews;
   bool allowWildcards      = !noItems && options.IsFlagSet( ArgumentOption::AllowWildcards );
   bool noPreviews          = itemsAsViews && options.IsFlagSet( ArgumentOption::NoPreviews );
   bool recursiveDirSearch  = itemsAsFiles && allowWildcards && options.IsFlagSet( ArgumentOption::RecursiveDirSearch );
   bool recursiveSearchArgs = recursiveDirSearch && options.IsFlagSet( ArgumentOption::RecursiveSearchArgs );

   // This is the recursive search mode flag, controlled by --r[+|-]
   bool recursiveSearch = false;

   // The list of existing view identifiers, in case itemsAsViews = true.
   SortedStringList imageIds;

   // The list of extracted arguments
   ArgumentList arguments;

   for ( StringList::const_iterator i = argv.Begin(); i != argv.End(); ++i )
   {
      if ( i->StartsWith( '-' ) )
      {
         Argument arg( i->At( 1 ) );

         if ( recursiveSearchArgs && arg.Id() == s_recursiveSearchArg )
         {
            if ( arg.IsSwitch() )
               recursiveSearch = arg.SwitchState();
            else if ( arg.IsLiteral() )
               recursiveSearch = true;
            else
               arguments.Add( arg );
         }
         else
            arguments.Add( arg );
      }
      else
      {
         if ( noItems )
            throw ParseError( "Non-parametric arguments are not allowed", *i  );

         StringList items;

         if ( itemsAsFiles )
         {
            String fileName = *i;
            if ( fileName.StartsWith( '\"' ) )
               fileName.Delete( 0 );
            if ( fileName.EndsWith( '\"' ) )
               fileName.Delete( fileName.UpperBound() );

            fileName.Trim();
            if ( fileName.IsEmpty() )
               throw ParseError( "Empty path specification", *i );

            fileName = File::FullPath( fileName );

            if ( fileName.HasWildcards() )
            {
               if ( !allowWildcards )
                  throw ParseError( "Wildcards not allowed", fileName );

               items = SearchDirectory( fileName, recursiveSearch );
            }
            else
               items.Add( fileName );
         }
         else if ( itemsAsViews )
         {
            String viewId = *i;

            if ( !allowWildcards )
               if ( viewId.HasWildcards() )
                  throw ParseError( "Wildcards not allowed", viewId );

            size_type p = viewId.Find( "->" );

            if ( p != String::notFound )
            {
               if ( noPreviews )
                  throw ParseError( "Preview identifiers not allowed", viewId );

               String imageId = viewId.Left( p );
               if ( imageId.IsEmpty() )
                  throw ParseError( "Missing image identifier", viewId );

               String previewId = viewId.Substring( p+2 );
               if ( previewId.IsEmpty() )
                  throw ParseError( "Missing preview identifier", viewId );

               FindPreviews( items, imageId, previewId );
            }
            else
            {
               if ( viewId.HasWildcards() )
               {
                  Array<ImageWindow> W = ImageWindow::AllWindows();
                  for ( size_type i = 0; i < W.Length(); ++i )
                  {
                     View v = W[i].MainView();
                     if ( String( v.Id() ).WildMatch( viewId ) )
                        AddView( items, v );
                  }
               }
               else
               {
                  ImageWindow w = ImageWindow::WindowById( IsoString( viewId ) );
                  if ( w.IsNull() )
                     throw ParseError( "Image not found", viewId );
                  AddView( items, w.MainView() );
               }
            }
         }
         else
            items.Add( *i );

         Argument arg( *i, items );
         arguments.Add( arg );
      }
   }

   return arguments;
}
예제 #27
0
boolean NoUndoImageCommand::doIt(CommandInterface *ci)
{
    ImageWindow *image = this->image;
    boolean  ret = TRUE;
    ImageNode *in = (ImageNode*)image->node;

    ASSERT(image);

    switch (this->commandType) {
    case NoUndoImageCommand::SetBGColor:
	image->postBackgroundColorDialog();
	break;
    case NoUndoImageCommand::DisplayGlobe:
        image->setDisplayGlobe();
        break;
    case NoUndoImageCommand::ViewControl:
	ret = image->postViewControlDialog();
	break;
    case NoUndoImageCommand::RenderingOptions:
	ret = image->postRenderingOptionsDialog();
	break;
    case NoUndoImageCommand::Throttle:
	ret = image->postThrottleDialog();
	break;
    case NoUndoImageCommand::ChangeImageName:
	ret = image->postChangeImageNameDialog();
	break;
    case NoUndoImageCommand::AutoAxes:
	ret = image->postAutoAxesDialog();
	break;
    case NoUndoImageCommand::OpenVPE:
	ret = image->postVPE();	
	break;
    case NoUndoImageCommand::Depth8:
	if( in && image->imageDepth8Option->getState() )
	    image->changeDepth(8);
	break;
    case NoUndoImageCommand::Depth12:
	if( in && image->imageDepth12Option->getState() )
	    image->changeDepth(12);
	break;
    case NoUndoImageCommand::Depth15:
	if( in && image->imageDepth15Option->getState() )
	    image->changeDepth(15);
	break;
    case NoUndoImageCommand::Depth16:
	if( in && image->imageDepth16Option->getState() )
	    image->changeDepth(16);
	break;
    case NoUndoImageCommand::Depth24:
	if( in && image->imageDepth24Option->getState() )
	    image->changeDepth(24);
	break;
    case NoUndoImageCommand::Depth32:
	if( in && image->imageDepth32Option->getState() )
	    image->changeDepth(32);
	break;
    case NoUndoImageCommand::SetCPAccess:
	image->postPanelAccessDialog(
		((DisplayNode*)image->node)->getPanelManager());
	break;
    case NoUndoImageCommand::SaveImage:
	image->saveImage();
	break;
    case NoUndoImageCommand::SaveAsImage:
	 ret = image->postSaveImageDialog();
	break;
    case NoUndoImageCommand::PrintImage:
	 ret = image->postPrintImageDialog();
	break;
    default:
	ASSERT(0);
    }

    return ret;
}
예제 #28
0
bool ChannelCombinationInstance::ExecuteOn( View& view )
{
   ImageWindow sourceWindow[ 3 ];
   ImageVariant sourceImage[ 3 ];

   AutoViewLock lock( view );

   ImageVariant image = view.Image();

   if ( image.IsComplexSample() )
      throw Error( "ChannelCombination cannot be executed on complex images." );

   if ( image->ColorSpace() != ColorSpace::RGB )
      throw Error( "ChannelCombination requires a RGB color image." );

   Console().EnableAbort();

   StandardStatus status;
   image->SetStatusCallback( &status );

   String baseId;
   Rect r;
   int w0, h0;

   if ( view.IsPreview() )
   {
      ImageWindow w = view.Window();
      View mainView = w.MainView();

      baseId = mainView.Id();
      r = w.PreviewRect( view.Id() );
      mainView.GetSize( w0, h0 );
   }
   else
   {
      baseId = view.Id();
      r = image->Bounds();
      w0 = r.Width();
      h0 = r.Height();
   }

   int numberOfSources = 0;

   for ( int i = 0; i < 3; ++i )
      if ( channelEnabled[i] )
      {
         String id = channelId[i];
         if ( id.IsEmpty() )
            id = baseId + '_' + ColorSpaceId::ChannelId( colorSpace, i );

         sourceWindow[i] = ImageWindow::WindowById( id );

         if ( sourceWindow[i].IsNull() )
            throw Error( "ChannelCombination: Source image not found: " + id );

         sourceImage[i] = sourceWindow[i].MainView().Image();

         if ( !sourceImage[i] )
            throw Error( "ChannelCombination: Invalid source image: " + id );

         if ( sourceImage[i]->IsColor() )
            throw Error( "ChannelCombination: Invalid source color space: " + id );

         if ( sourceImage[i]->Width() != w0 || sourceImage[i]->Height() != h0 )
            throw Error( "ChannelCombination: Incompatible source image dimensions: " + id );

         ++numberOfSources;
      }

   if ( numberOfSources == 0 )
      return false;

   const char* what = "";
   switch ( colorSpace )
   {
   case ColorSpaceId::RGB:
      what = "RGB channels";
      break;
   case ColorSpaceId::CIEXYZ:
      what = "normalized CIE XYZ components";
      break;
   case ColorSpaceId::CIELab:
      what = "normalized CIE L*a*b* components";
      break;
   case ColorSpaceId::CIELch:
      what = "normalized CIE L*c*h* components";
      break;
   case ColorSpaceId::HSV:
      what = "normalized HSV components";
      break;
   case ColorSpaceId::HSI:
      what = "normalized HSI components";
      break;
   }
   image->Status().Initialize( String( "Combining " ) + what, image->NumberOfPixels() );

   if ( image.IsFloatSample() )
      switch ( image.BitsPerSample() )
      {
      case 32:
         CombineChannels( static_cast<Image&>( *image ), colorSpace, baseId, r,
                          sourceImage[0], sourceImage[1], sourceImage[2] );
         break;
      case 64:
         CombineChannels( static_cast<DImage&>( *image ), colorSpace, baseId, r,
                          sourceImage[0], sourceImage[1], sourceImage[2] );
         break;
      }
   else
      switch ( image.BitsPerSample() )
      {
      case  8:
         CombineChannels( static_cast<UInt8Image&>( *image ), colorSpace, baseId, r,
                          sourceImage[0], sourceImage[1], sourceImage[2] );
         break;
      case 16:
         CombineChannels( static_cast<UInt16Image&>( *image ), colorSpace, baseId, r,
                          sourceImage[0], sourceImage[1], sourceImage[2] );
         break;
      case 32:
         CombineChannels( static_cast<UInt32Image&>( *image ), colorSpace, baseId, r,
                          sourceImage[0], sourceImage[1], sourceImage[2] );
         break;
      }

   return true;
}