MatchPacket(const SphericalOccupancyMap&SOM,const DynVolTempl&t,function<bool (const Mat&t_active)> checked)
    {
      //
      float maxRes = fromString<float>(g_params.require("MAX_RES"));
      float zRes   = fromString<float>(g_params.require("Z_RES")); // cm
      float sf = std::sqrt(maxRes/t.t.size().area());
      
      // get inputs
      Mat zSlice = imclamp(SOM.get_OM(),t.z_min,t.z_max);
      Mat valid  = imunclamped(SOM.get_OM(),t.z_min,t.z_max);
      Mat z_active = (zSlice.clone());
      Mat t_active = (t.t.clone());

      // down size if needed
      if(sf < 1)
      {
	cv::resize(t_active,t_active,Size(),sf,sf,params::DEPTH_INTER_STRATEGY);
	cv::resize(z_active,z_active,Size(),sf,sf,params::DEPTH_INTER_STRATEGY);
	stride = std::floor(1/sf);
	assert(stride >= 1);
      }
      else
	stride = 1;
      t_active = imround(t_active,zRes);
      z_active = imround(z_active,zRes);

      // skip duplicates
      if(checked(t_active))
      {
	return;
      }
      
      // match
      //Mat r = matchTemplateL2Normalized(z_active,t_active,valid);
      r; cv::matchTemplate(z_active, t_active, r, CV_TM_SQDIFF_NORMED);

      // upsize if needed
      if(sf < 1)
	cv::resize(r,r,Size(),1/sf,1/sf,params::DEPTH_INTER_STRATEGY);

      // normalize score
      double z_side = (t.z_max - t.z_min);
      r = -r/(z_side*t_active.size().area());

      // extract top detection for visualization and debug
      bb = Rect(extrema(r).maxLoc,t.t.size());
      if(rectContains(zSlice,bb))
      {
	max_resp = extrema(r).max;
      }
      else
	max_resp = -inf;
      this->t = t;
    }
    void log(string prefix,SphericalOccupancyMap&SOM)
    {
      Mat vis_r, vis_t, vis_z, vis_match,message,vis_raw_z;
      Mat zSlice = imclamp(SOM.get_OM(),t.z_min,t.z_max);
      
      // vis
      vis_raw_z = eq(SOM.get_OM());
      vis_r = eq(r);
      vis_t = eq(t.t);
      vis_z = eq(zSlice);
      Mat vis_t_full(vis_z.rows,vis_z.cols,DataType<Vec3b>::type,Scalar::all(255));
      {
	Mat src_roi = imroi(vis_t,Rect(Point(0,0),bb.size()));
	Mat dst_roi = imroi(vis_t_full,bb);
	src_roi.copyTo(dst_roi);
      }
      vis_match = im_merge(
	imroi(vis_r,Rect(Point(0,0),vis_z.size())),
	vis_z,
	vis_t_full);
      cv::rectangle(vis_match,bb.tl(),bb.br(),toScalar(BLUE));
      message = image_text(safe_printf("resp = %",extrema(r).max));
      vector<Mat> vs{vis_r,vis_t,vis_z,vis_match,vis_raw_z,message};
      log_im(prefix,tileCat(vs));
    }
Exemplo n.º 3
0
T banded_rate<T>::operator()
    (T const&              total_amount
    ,std::vector<T> const& cumulative_limits
    ,std::vector<T> const& rates
    ) const
{
    // Cache T(0) in case it's expensive to construct.
    T const zero = T(0);

    LMI_ASSERT(zero <= total_amount);
    LMI_ASSERT(!cumulative_limits.empty());
    LMI_ASSERT(rates.size() == cumulative_limits.size());

    minmax<T> extrema(cumulative_limits);
    LMI_ASSERT(zero <= extrema.minimum());
    LMI_ASSERT(zero <  extrema.maximum());

    std::vector<T> const& z(cumulative_limits);
    LMI_ASSERT(nonstd::is_sorted(z.begin(), z.end()));

    // Ignore the last limit. It's asserted elsewhere to be infinity.
    std::vector<double>::const_iterator band = std::upper_bound
        (cumulative_limits.begin()
        ,cumulative_limits.end() - 1
        ,total_amount
        );
    return rates[band - cumulative_limits.begin()];
}
Exemplo n.º 4
0
bool CFace::GetClosestPoint(const gp_Pnt &pos, gp_Pnt &closest_pnt)const{
	BRepPrimAPI_MakeBox cuboid(gp_Ax2(pos, gp_Vec(1, 0, 0), gp_Vec(0, 1, 0)), 0.0001, 0.0001, 0.0001);

	BRepExtrema_DistShapeShape extrema(m_topods_face, cuboid.Shape());
	if(extrema.Perform() != Standard_True)return false;
	closest_pnt = extrema.PointOnShape1(1);

	return true;
}
Exemplo n.º 5
0
T tiered_product<T>::operator()
    (T const&              new_incremental_amount
    ,T const&              prior_total_amount
    ,std::vector<T> const& incremental_limits
    ,std::vector<T> const& rates
    ) const
{
    // Cache T(0) in case it's expensive to construct.
    T const zero = T(0);

    LMI_ASSERT(zero <= new_incremental_amount);
    LMI_ASSERT(zero <= prior_total_amount);
    LMI_ASSERT(!incremental_limits.empty());
    LMI_ASSERT(rates.size() == incremental_limits.size());

    minmax<T> extrema(incremental_limits);
    LMI_ASSERT(zero <= extrema.minimum());
    LMI_ASSERT(zero <  extrema.maximum());

    T result = zero;
    T remaining_amount = new_incremental_amount;
    T unused_prior_amount = prior_total_amount;
    for
        (typename std::vector<T>::size_type j = 0
        ;j < incremental_limits.size()
        ;++j
        )
        {
        T unfilled_band_increment = incremental_limits[j] - unused_prior_amount;
        unused_prior_amount -= incremental_limits[j];
        unused_prior_amount = std::max(zero, unused_prior_amount);
        if(unfilled_band_increment <= zero)
            {
            continue;
            }
        if(remaining_amount <= zero)
            {
            break;
            }
        if(remaining_amount <= unfilled_band_increment)
            {
            result += rates[j] * remaining_amount;
            break;
            }
        else
            {
            result += rates[j] * unfilled_band_increment;
            remaining_amount -= unfilled_band_increment;
            }
        }

    return result;
}
Exemplo n.º 6
0
bool CShape::GetExtents(double* extents, const double* orig, const double* xdir, const double* ydir, const double* zdir)
{
	gp_Pnt p_orig(0, 0, 0);
	if(orig)p_orig = gp_Pnt(orig[0], orig[1], orig[2]);
	gp_Vec v_x(1, 0, 0);
	if(xdir)v_x = gp_Vec(xdir[0], xdir[1], xdir[2]);
	gp_Vec v_y(0, 1, 0);
	if(ydir)v_y = gp_Vec(ydir[0], ydir[1], ydir[2]);
	gp_Vec v_z(0, 0, 1);
	if(zdir)v_z = gp_Vec(zdir[0], zdir[1], zdir[2]);

	BRepPrimAPI_MakeBox cuboid_plus_x(gp_Ax2(gp_Pnt(p_orig.XYZ() + 2000000 * v_x.XYZ() + (-1000000) * v_z.XYZ() + (-1000000) * v_y.XYZ()), v_x, v_y), 1000000, 1000000, 1000000);
	BRepPrimAPI_MakeBox cuboid_minus_x(gp_Ax2(gp_Pnt(p_orig.XYZ() + (-2000000) * v_x.XYZ() + (-1000000) * v_z.XYZ() + (-1000000) * v_y.XYZ()), -v_x, v_z), 1000000, 1000000, 1000000);
	BRepPrimAPI_MakeBox cuboid_plus_y(gp_Ax2(gp_Pnt(p_orig.XYZ() + 2000000 * v_y.XYZ() + (-1000000) * v_z.XYZ() + (-1000000) * v_x.XYZ()), v_y, v_z), 1000000, 1000000, 1000000);
	BRepPrimAPI_MakeBox cuboid_minus_y(gp_Ax2(gp_Pnt(p_orig.XYZ() + (-2000000) * v_y.XYZ() + (-1000000) * v_z.XYZ() + (-1000000) * v_x.XYZ()), -v_y, v_x), 1000000, 1000000, 1000000);
	BRepPrimAPI_MakeBox cuboid_plus_z(gp_Ax2(gp_Pnt(p_orig.XYZ() + 2000000 * v_z.XYZ() + (-1000000) * v_x.XYZ() + (-1000000) * v_y.XYZ()), v_z, v_x), 1000000, 1000000, 1000000);
	BRepPrimAPI_MakeBox cuboid_minus_z(gp_Ax2(gp_Pnt(p_orig.XYZ() + (-2000000) * v_z.XYZ() + (-1000000) * v_x.XYZ() + (-1000000) * v_y.XYZ()), -v_z, v_y), 1000000, 1000000, 1000000);

	gp_Vec v_orig(p_orig.XYZ());

	TopoDS_Solid shape[6] =
	{
		cuboid_minus_x,
		cuboid_minus_y,
		cuboid_minus_z,
		cuboid_plus_x,
		cuboid_plus_y,
		cuboid_plus_z
	};

	gp_Vec vector[6] =
	{
		v_x,
		v_y,
		v_z,
		v_x,
		v_y,
		v_z
	};

	for(int i = 0; i<6; i++){
		BRepExtrema_DistShapeShape extrema(m_shape, shape[i]);
		extrema.Perform();
		gp_Pnt p = extrema.PointOnShape1(1);
		gp_Vec v(p.XYZ());
		double dp = v * vector[i];
		double dp_o = v_orig * vector[i];
		extents[i] = dp - dp_o;
	}

	return true;
}
Exemplo n.º 7
0
int main (int argc, char **argv){

int i, size;
float total, dev;
float *arr = (float *) malloc((argc - 1)*(sizeof(float)));
total = dev = 0;
size = argc - 1;
/*populate array with argv*/
for(i = 1; i < argc; i++){
	*(arr + (i - 1)) = atof(argv[i]);
	total = total + arr[i-1];
}
/*compute mean and sd*/
extrema (arr, size, &total, &dev);

printf("Mean : %.2f\n", total);
printf("Standard Deviation : %.2f\n", dev);

free(arr);

return 0;
}
Exemplo n.º 8
0
// Returns the point where the distance between the selected fuselage and the ground is at minimum.
// The Fuselage could be turned with a given angle at at given axis, specified by a point and a direction.
gp_Pnt CCPACSFuselage::GetMinumumDistanceToGround(gp_Ax1 RAxis, double angle)
{

    TopoDS_Shape fusedFuselage = GetLoft()->Shape();

    // now rotate the fuselage
    gp_Trsf myTrsf;
    myTrsf.SetRotation(RAxis, angle * M_PI / 180.);
    BRepBuilderAPI_Transform xform(fusedFuselage, myTrsf);
    fusedFuselage = xform.Shape();

    // build cutting plane for intersection
    // We move the "ground" to "-1000" to be sure it is _under_ the fuselage
    gp_Pnt p1(-1.0e7, -1.0e7, -1000);
    gp_Pnt p2( 1.0e7, -1.0e7, -1000);
    gp_Pnt p3( 1.0e7,  1.0e7, -1000);
    gp_Pnt p4(-1.0e7,  1.0e7, -1000);

    Handle(Geom_TrimmedCurve) shaft_line1 = GC_MakeSegment(p1,p2);
    Handle(Geom_TrimmedCurve) shaft_line2 = GC_MakeSegment(p2,p3);
    Handle(Geom_TrimmedCurve) shaft_line3 = GC_MakeSegment(p3,p4);
    Handle(Geom_TrimmedCurve) shaft_line4 = GC_MakeSegment(p4,p1);

    TopoDS_Edge shaft_edge1 = BRepBuilderAPI_MakeEdge(shaft_line1);
    TopoDS_Edge shaft_edge2 = BRepBuilderAPI_MakeEdge(shaft_line2);
    TopoDS_Edge shaft_edge3 = BRepBuilderAPI_MakeEdge(shaft_line3);
    TopoDS_Edge shaft_edge4 = BRepBuilderAPI_MakeEdge(shaft_line4);

    TopoDS_Wire shaft_wire = BRepBuilderAPI_MakeWire(shaft_edge1, shaft_edge2, shaft_edge3, shaft_edge4);
    TopoDS_Face shaft_face = BRepBuilderAPI_MakeFace(shaft_wire);

    // calculate extrema
    BRepExtrema_DistShapeShape extrema(fusedFuselage, shaft_face);
    extrema.Perform();

    return extrema.PointOnShape1(1);
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
    const char *exe = argv[0];

    double t0;
    double t1;

    const char *p    = NULL;
    const char *m    = NULL;
    const char *o    = NULL;
    const char *t    = NULL;
    int         n    = 512;
    int         d    =   0;
    int         b    =  -1;
    int         g    =  -1;
    int         A    =   0;
    int         h    =   0;
    int         l    =   0;
    int         T    =   0;
    double      E[4] = { 0.f, 0.f, 0.f , 0.f};
    double      L[3] = { 0.f, 0.f, 0.f };
    double      P[3] = { 0.f, 0.f, 0.f };
    float       N[2] = { 0.f, 0.f };
    float       R[2] = { 0.f, 1.f };

    int c;
    int r = 0;

    t0 = now();

    setexe(exe);

    opterr = 0;

    while ((c = getopt(argc, argv, "Ab:d:E:g:hL:l:m:n:N:o:p:P:Tt:R:w:")) != -1)
        switch (c)
        {
            case 'A': A = 1;                    break;
            case 'h': h = 1;                    break;
            case 'T': T = 1;                    break;
            case 'p': p = optarg;               break;
            case 'm': m = optarg;               break;
            case 'o': o = optarg;               break;
            case 't': t = optarg;               break;
            case 'n': sscanf(optarg, "%d", &n); break;
            case 'd': sscanf(optarg, "%d", &d); break;
            case 'b': sscanf(optarg, "%d", &b); break;
            case 'g': sscanf(optarg, "%d", &g); break;
            case 'l': sscanf(optarg, "%d", &l); break;

            case 'E':
                sscanf(optarg, "%lf,%lf,%lf,%lf", E + 0, E + 1, E + 2, E + 3);
                break;
            case 'L':
                sscanf(optarg, "%lf,%lf,%lf",     L + 0, L + 1, L + 2);
                break;
            case 'P':
                sscanf(optarg, "%lf,%lf,%lf",     P + 0, P + 1, P + 2);
                break;
            case 'N':
                sscanf(optarg, "%f,%f",           N + 0, N + 1);
                break;
            case 'R':
                sscanf(optarg, "%f,%f",           R + 0, R + 1);
                break;

            case '?': apperr("Bad option -%c", optopt);                   break;
        }

    argc -= optind;
    argv += optind;

    if (p == NULL || h)
        apperr("\nUsage: %s [options] input [...]\n"
                "\t\t-p process . . Select process\n"
                "\t\t-o output  . . Output file\n"
                "\t\t-T . . . . . . Emit timing information\n\n"
                "\t%s -p extrema\n\n"
                "\t%s -p convert [options]\n"
                "\t\t-n n . . . . . Page size\n"
                "\t\t-d d . . . . . Tree depth\n"
                "\t\t-b b . . . . . Channel depth override\n"
                "\t\t-g g . . . . . Channel sign override\n"
                "\t\t-E w,e,s,n . . Equirectangular range\n"
                "\t\t-L c,d0,d1 . . Longitude blend range\n"
                "\t\t-P c,d0,d1 . . Latitude blend range\n"
                "\t\t-N n0,n1 . . . Normalization range\n"
                "\t\t-A . . . . . . Coverage alpha\n\n"
                "\t%s -p combine [-m mode]\n"
                "\t\t-m sum . . . . Combine by sum\n"
                "\t\t-m max . . . . Combine by maximum\n"
                "\t\t-m avg . . . . Combine by average\n"
                "\t\t-m blend . . . Combine by alpha blending\n\n"
                "\t%s -p mipmap [-m mode]\n\n"
                "\t\t-m sum . . . . Combine by sum\n"
                "\t\t-m max . . . . Combine by maximum\n"
                "\t\t-m avg . . . . Combine by average\n\n"
                "\t%s -p border\n\n"
                "\t%s -p finish [options]\n"
                "\t\t-t text  . . . Image description text file\n"
                "\t\t-l l . . . . . Bounding volume oversample level\n\n"
                "\t%s -p normal [options]\n"
                "\t\t-R r0,r1 . . . Radius range\n",

                exe, exe, exe, exe, exe, exe, exe, exe);

    else if (strcmp(p, "extrema") == 0)
        r = extrema(argc, argv);

    else if (strcmp(p, "convert") == 0)
        r = convert(argc, argv, o, n, d, b, g, A, N, E, L, P);

    else if (strcmp(p, "rectify") == 0)
        r = rectify(argc, argv, o, n,             N, E, L, P);

    else if (strcmp(p, "combine") == 0)
        r = combine(argc, argv, o, m);

    else if (strcmp(p, "mipmap") == 0)
        r = mipmap (argc, argv, o, m, A);

    else if (strcmp(p, "border") == 0)
        r = border (argc, argv, o);

    else if (strcmp(p, "finish") == 0)
        r = finish (argc, argv, t, l);

    else if (strcmp(p, "polish") == 0)
        r = polish (argc, argv);

    else if (strcmp(p, "normal") == 0)
        r = normal (argc, argv, o, R);

    else if (strcmp(p, "sample") == 0)
        r = sample (argc, argv, R, d);

    else apperr("Unknown process '%s'", p);

    t1 = now();

    if (T) printhms(t1 - t0);

    return r;
}
Exemplo n.º 10
0
void GUI::apply_filter_from_menu(Controller &controller, Gtk::ImageMenuItem &imagemenuitem) {

  if ( ! controller.image_file_loaded   ) { return ; }


  bool is_alpha = controller.current_image_to_process.channels() == 4 ;

  Sharpen sharpen_filter(3, "diamond")      ;

  Sharpen sharpen_filter_more(3, "diamond") ;


  Find_Edges find_edges_filter(3) ;


  Mean mean_filter(3)      ;

  Mean mean_filter_more(5) ;


  cv::Mat kernel = make_kernel("rect", 3)  ;


  cv::Mat tmp = controller.current_image_to_process.clone() ;

  cv::Mat frame ;

  switch ( stoi(imagemenuitem.get_name()) ) {

    case 0 :
      
      // Pencil Sketch filter.
      pencil_sketch_filter(tmp, frame) ;
      break ;

    case 1 :
    
      // Stylisation filter.
      stylisation_filter(tmp, frame) ;
      break ;

    case 2 :
    
      // Detail Enhance filter.
      detail_enhance_filter(tmp, frame) ;
      break ;

    case 3 :
     
      // Edge Preserving filter.
      edge_preserving_filter(tmp, frame) ;
      break ;

    case 4 :

      // Stroke edges filter:
      stroke_edges(tmp, frame) ;
      break ;

    case 5 :

      // Invert Intensity filter:
      invert_intensity(tmp, frame) ;
      break ;

    case 6 :

      // Light Intensity filter:
      effect_light(tmp, frame) ;
      break ;

    case 7 :

      // Recolor-RC (Red-Cyan) filter:
      recolorRC(tmp, frame) ;
      break ;

    case 8 :

      // Recolor-RC (Red-Green-Value) filter:
      recolorRGV(tmp, frame) ;
      break ;

    case 9 :

      // Recolor-RC (Cyan-Magenta-Value) filter:
      recolorCMV(tmp, frame) ;
      break ;

    case 10 :

      // Extrema Maximal Filter:
      extrema(tmp, frame, "max") ;
      break ;

    case 11 :

      // Extrema Minimal Filter:
      extrema(tmp, frame, "min") ;
      break ;



    case 12 :

      // Sharpen filter:
      sharpen_filter.apply(tmp, frame)   ;
      break ;

    case 13 :

      // Sharpen More filter:
      sharpen_filter_more.apply(tmp, frame)   ;
      break ;

    case 14 :

      // Find Edges filter:

      if (is_alpha) {

        cv::Mat frame_rgb ;
        cv::Mat tmp_1     ;

        cvtColor(tmp, frame_rgb, cv::COLOR_BGRA2BGR) ;

        find_edges_filter.apply(frame_rgb, tmp_1)   ;

        vector<cv::Mat> tmp_2 ;
        vector<cv::Mat> tmp_3 ;

        cv::split(tmp,   tmp_2) ;
        cv::split(tmp_1, tmp_3) ;

        // Assign BGR channels.
        tmp_2[0] = tmp_3[0] ;
        tmp_2[1] = tmp_3[1] ;
        tmp_2[2] = tmp_3[2] ;

        // Final channels merging into result with alpha channel unchanged.
        cv::merge(tmp_2, frame) ;

        break ;


      }

      find_edges_filter.apply(tmp, frame)   ;
      break ;

    case 15 :

      // Mean Blur filter:
      mean_filter.apply(tmp, frame)   ;
      break ;

    case 16 :

      // Mean Blur More filter:
      mean_filter_more.apply(tmp, frame)   ;
      break ;


    case 17 :

      // Blur filter:
      blur_filter(tmp, frame) ;
      break ;

    case 18 :

      // Median Blur filter:
      median_blur_filter(tmp, frame) ;
      break ;

    case 19 :

      // Gaussian Blur filter:
      gaussian_blur_filter(tmp, frame) ;
      break ;

    case 20 :

      denoising_filter(tmp, frame) ;
      break ;

    case 21 :

      // Erode filter:
      erode_filter(tmp, frame, kernel, 1)   ;
      break ;

    case 22 :

      // Dilate filter:
      dilate_filter(tmp, frame, kernel, 1)   ;
      break ;

    case 23 :

      // Wave Horizontally filter:
      wave(tmp, frame, -1) ;
      break ;

    case 24 :

      // Wave Vertically filter:
      wave(tmp, frame,  1) ;
      break ;

    case 25 :

      // Wave Twice (Horizontally and Vertically) filter:
      wave(tmp, frame,  0) ;
      break ;

    case 26 :

      // Contours Sobel White filter.
      sobel_drawning(tmp, frame, 3, false, 1) ;
      break ;

    case 27 :

      // Contours Sobel Black filter.
      sobel_drawning(tmp, frame, 3, false, -1) ;
      break ;

    case 28 :

      // Contours Sobel Emboss filter.
      sobel_drawning(tmp, frame, 3, false, 0) ;
      break ;

    case 29 :

      // Emboss Sobel filter:
      sobel_emboss(tmp, frame, 3) ;
      break ;

    case 30 :

      // Emboss Laplacian filter:
      laplacian_emboss(tmp, frame, 3) ;
      break ;


    case 31 :

      // Binary White OTSU filter:
      // Build a binary image (a black and white only image) with white background (@arg value true)
      // based on the OTSU threshold computing algorithm (@arg value -1).
      build_binary_image(tmp, frame, -1, true) ;
      break ;

    case 32 :

      // Binary White TRIANGLE filter:
      // Build a binary image (a black and white only image) with white background (@arg value true)
      // based on the TRIANGLE threshold computing algorithm (@arg value 1).
      build_binary_image(tmp, frame,  1, true) ;
      break ;

    case 33 :

      // Binary White AVERAGE filter:
      // Build a binary image (a black and white only image) with white background (@arg value true)
      // based on the AVERAGE threshold from OTSU and TRIANGLE (@arg value 0).
      build_binary_image(tmp, frame,  0, true) ;
      break ;

    case 34 :

      // Binary Black OTSU filter:
      // Build a binary image (a black and white only image) with black background (@arg value true)
      // based on the OTSU threshold computing algorithm (@arg value -1).
      build_binary_image(tmp, frame, -1, false) ;
      break ;

    case 35 :

      // Binary Black TRIANGLE filter:
      // Build a binary image (a black and white only image) with black background (@arg value true)
      // based on the TRIANGLE threshold computing algorithm (@arg value 1).
      build_binary_image(tmp, frame,  1, false) ;
      break ;

    case 36 :

      // Binary Black AVERAGE filter:
      // Build a binary image (a black and white only image) with black background (@arg value true)
      // based on the AVERAGE threshold from OTSU and TRIANGLE (@arg value 0).
      build_binary_image(tmp, frame,  0, false) ;
      break ;

    case 37 :

      // Binary Contours White filter:
      // Build a binary image (a black and white only image) with contours detction on white background (@arg value false).
      laplacian_zero_crossing(tmp, frame, 19, false)  ;
      break ;

    case 38 :

      // Binary Contours Black filter:
      // Build a binary image (a black and white only image) with contours detction on black background (@arg value true).
      laplacian_zero_crossing(tmp, frame, 19, true)  ;
      break ;







    #ifdef DEBUG
    default :
      // Cannot append due of the GUI interfacing.
      fprintf(stdout,"Error applying filter !!!\n") ;
      return ;
    #endif

  }

  // We register current frame in vector<cv::Mat> for undo-redo.
  controller.process_after_applying(frame) ;

  // It convert current_image_to_process as src to RGB(A) in dst current_image_to_display.
  set_img(frame, controller.current_image_to_display, controller) ;  // It auto process conversion to RGB(A).

  // Reset some variables.
  after_applying_reset_settings(controller) ;

}
Exemplo n.º 11
0
/*!
   \brief Creates one perimeter from vector area.

   \param points list of vertices represting area
   \param[out] perimeter perimeter
   \param band_region region which determines perimeter cells

   \return 1 on success
   \return 0 on error
 */
int make_perimeter(struct line_pnts *points, IClass_perimeter * perimeter,
		   struct Cell_head *band_region)
{
    IClass_point *tmp_points;

    IClass_point *vertex_points;

    int i, first, prev, skip, next;

    int count, vertex_count;

    int np;			/* perimeter estimate */

    G_debug(5, "iclass_make_perimeter()");
    count = points->n_points;

    tmp_points = (IClass_point *) G_calloc(count, sizeof(IClass_point));	/* TODO test */

    for (i = 0; i < count; i++) {
	G_debug(5, "iclass_make_perimeter(): points: x: %f y: %f",
		points->x[i], points->y[i]);

    /* This functions are no longer used because of the different behavior 
       of Rast_easting_to_col depending whether location is LL or not. 
       It makes problem  in  interactive scatter plot tool, 
       which defines its own coordinates systems for the plots and 
       therefore it requires the function to work always in same way 
       without hidden dependency on location type.

	  tmp_points[i].y = Rast_northing_to_row(points->y[i], band_region);
	  tmp_points[i].x = Rast_easting_to_col(points->x[i], band_region);
   */

   tmp_points[i].y = (band_region->north - points->y[i]) / band_region->ns_res;
   tmp_points[i].x = (points->x[i] - band_region->west) / band_region->ew_res;
    }   

    /* find first edge which is not horizontal */

    first = -1;
    prev = count - 1;
    for (i = 0; i < count; prev = i++) {
	/* non absurd polygon has vertexes with different y coordinate */
	if (tmp_points[i].y != tmp_points[prev].y) {
	    first = i;
	    break;
	}
    }
    if (first < 0) {
	G_free(tmp_points);
	G_warning(_("Absurd polygon."));
	return 0;
    }

    /* copy tmp to vertex list collapsing adjacent horizontal edges */

    /* vertex_count <= count, size of vertex_points is count */
    vertex_points = (IClass_point *) G_calloc(count, sizeof(IClass_point));	/* TODO test */
    skip = 0;
    vertex_count = 0;
    i = first;			/* stmt not necssary */

    do {
	if (!skip) {
	    vertex_points[vertex_count].x = tmp_points[i].x;
	    vertex_points[vertex_count].y = tmp_points[i].y;
	    vertex_count++;
	}

	prev = i++;
	if (i >= count)
	    i = 0;
	if ((next = i + 1) >= count)
	    next = 0;

	skip = ((tmp_points[prev].y == tmp_points[i].y) &&
		(tmp_points[next].y == tmp_points[i].y));
    }
    while (i != first);

    G_free(tmp_points);

    /* count points on the perimeter */

    np = 0;
    prev = vertex_count - 1;
    for (i = 0; i < vertex_count; prev = i++) {
	np += abs(vertex_points[prev].y - vertex_points[i].y);
    }

    /* allocate perimeter list */

    perimeter->points = (IClass_point *) G_calloc(np, sizeof(IClass_point));
    if (!perimeter->points) {
	G_free(vertex_points);
	G_warning(_("Outlined area is too large."));
	return 0;
    }

    /* store the perimeter points */

    perimeter->npoints = 0;
    prev = vertex_count - 1;
    for (i = 0; i < vertex_count; prev = i++) {
	edge2perimeter(perimeter, vertex_points[prev].x,
		       vertex_points[prev].y, vertex_points[i].x,
		       vertex_points[i].y);
    }

    /*
     * now decide which verticies should be included
     *    local extrema are excluded
     *    local non-extrema are included
     *    verticies of horizontal edges which are pseudo-extrema
     *      are excluded.
     *    one vertex of horizontal edges which are pseudo-non-extrema
     *      are included.
     */

    prev = vertex_count - 1;
    i = 0;
    do {
	next = i + 1;
	if (next >= vertex_count)
	    next = 0;

	if (extrema
	    (vertex_points[prev].y, vertex_points[i].y,
	     vertex_points[next].y))
	    skip = 1;
	else if (non_extrema
		 (vertex_points[prev].y, vertex_points[i].y,
		  vertex_points[next].y))
	    skip = 0;
	else {
	    skip = 0;
	    if (++next >= vertex_count)
		next = 0;
	    if (extrema
		(vertex_points[prev].y, vertex_points[i].y,
		 vertex_points[next].y))
		skip = 1;
	}

	if (!skip)
	    perimeter_add_point(perimeter, vertex_points[i].x,
				vertex_points[i].y);

	i = next;
	prev = i - 1;
    }
    while (i != 0);

    G_free(vertex_points);

    /* sort the edge points by row and then by col */
    qsort(perimeter->points, (size_t) perimeter->npoints,
	  sizeof(IClass_point), edge_order);

    return 1;

}
Exemplo n.º 12
0
int main( int ac, char** av )
{
    try
    {
        comma::command_line_options options( ac, av );
        verbose = options.exists( "--verbose,-v" );
        if( options.exists( "--help,-h" ) ) { usage( verbose ); }
        csv = comma::csv::options( options );
        csv.full_xpath = true;
        ascii = comma::csv::ascii< Eigen::Vector3d >( "x,y,z", csv.delimiter );
        const std::vector< std::string >& operations = options.unnamed( "--verbose,-v,--trace,--no-antialiasing,--next,--unit", "-.*" );
        if( operations.size() != 1 ) { std::cerr << "points-calc: expected one operation, got " << operations.size() << ": " << comma::join( operations, ' ' ) << std::endl; return 1; }
        const std::string& operation = operations[0];
        if (vector_calc::has_operation(operation))
        {
            vector_calc::process(operation, options, csv);
            return 0;
        }
        if( operation == "plane-intersection" )
        {
            plane_intersection::process(options, csv);
            return 0;
        }
        if( operation == "distance" )
        {
            if(    csv.has_field( "first" )   || csv.has_field( "second" )
                || csv.has_field( "first/x" ) || csv.has_field( "second/x" )
                || csv.has_field( "first/y" ) || csv.has_field( "second/y" )
                || csv.has_field( "first/z" ) || csv.has_field( "second/z" ) )
            {
                calculate_distance_for_pairs();
                return 0;
            }
            if ( options.exists( "--next" ) ) { calculate_distance_next(); }
            else { calculate_distance( false ); }
            return 0;
        }
        if( operation == "cumulative-distance" )
        {
            calculate_distance( true );
            return 0;
        }
        if( operation == "nearest" )
        {
            if( options.exists( "--point,--to" ) )
            {
                Eigen::Vector3d point = comma::csv::ascii< Eigen::Vector3d >().get( options.value< std::string >( "--point,--to" ) );
                comma::csv::input_stream< Eigen::Vector3d > istream( std::cin, csv );
                std::string record;
                double min_distance = std::numeric_limits< double >::max();
                while( istream.ready() || ( std::cin.good() && !std::cin.eof() ) )
                {
                    const Eigen::Vector3d* p = istream.read();
                    if( !p ) { break; }
                    double d = ( *p - point ).norm();
                    if( d >= min_distance ) { continue; }
                    min_distance = d;
                    record = csv.binary() ? std::string( istream.binary().last(), csv.format().size() ) : comma::join( istream.ascii().last(), csv.delimiter );
                }
                if( !record.empty() ) { std::cout << record; }
                if( csv.binary() ) { std::cout.write( reinterpret_cast< const char* >( &min_distance ), sizeof( double ) ); }
                else { std::cout << csv.delimiter << min_distance << std::endl; }
                return 0;
            }
            else
            {
                
                return 0;
            }
        }
        if( operation == "thin" )
        {
            if( !options.exists( "--resolution" ) ) { std::cerr << "points-calc: --resolution is not specified " << std::endl; return 1; }
            double resolution = options.value( "--resolution" , 0.0 );
            thin( resolution );
            return 0;
        }
        if( operation == "discretise" || operation == "discretize" )
        {
            if( !options.exists( "--step" ) ) { std::cerr << "points-calc: --step is not specified " << std::endl; return 1; }
            double step = options.value( "--step" , 0.0 );
            if( step <= 0 ) { std::cerr << "points-calc: expected positive step, got " << step << std::endl; return 1; }
            // the last discretised point can be very close to the end of the interval, in which case the last two points can be identical in the output since ascii.put uses 12 digits by default
            // setting --tolerance=1e-12 will not allow the last discretised point to be too close to the end of the interval and therefore the output will have two distinct points at the end
            double tolerance = options.value( "--tolerance" , 0.0 ); 
            if( tolerance < 0 ) { std::cerr << "points-calc: expected non-negative tolerance, got " << tolerance << std::endl; return 1; }
            discretise( step, tolerance );
            return 0;
        }
        if( operation == "local-max" || operation == "local-min" ) // todo: if( operation == "local-calc" ? )
        {
            double sign = operation == "local-max" ? 1 : -1;
            if( csv.fields.empty() ) { csv.fields = "x,y,z,scalar"; }
            csv.full_xpath = false;
            bool has_id = csv.has_field( "id" );
            comma::csv::input_stream< local_operation::point > istream( std::cin, csv );
            std::deque< local_operation::record > records;
            double radius = options.value< double >( "--radius" );
            bool trace = options.exists( "--trace" );
            Eigen::Vector3d resolution( radius, radius, radius );
            snark::math::closed_interval< double, 3 > extents;
            comma::uint32 id = 0;
            if( verbose ) { std::cerr << "points-calc: reading input points..." << std::endl; }
            while( istream.ready() || ( std::cin.good() && !std::cin.eof() ) )
            {
                const local_operation::point* p = istream.read();
                if( !p ) { break; }
                std::string line;
                if( csv.binary() ) // quick and dirty
                {
                    line.resize( csv.format().size() );
                    ::memcpy( &line[0], istream.binary().last(), csv.format().size() );
                }
                else
                {
                    line = comma::join( istream.ascii().last(), csv.delimiter );
                }
                local_operation::point q = *p;
                if( !has_id ) { q.id = id++; }
                records.push_back( local_operation::record( q, line ) );
                records.back().reference_record = &records.back();
                extents.set_hull( p->coordinates );
            }
            if( verbose ) { std::cerr << "points-calc: loading " << records.size() << " points into grid..." << std::endl; }
            typedef std::vector< local_operation::record* > voxel_t; // todo: is vector a good container? use deque
            typedef snark::voxel_map< voxel_t, 3 > grid_t;
            grid_t grid( extents.min(), resolution );
            for( std::size_t i = 0; i < records.size(); ++i ) { ( grid.touch_at( records[i].point.coordinates ) )->second.push_back( &records[i] ); }
            if( verbose ) { std::cerr << "points-calc: searching for local extrema..." << std::endl; }
            for( grid_t::iterator it = grid.begin(); it != grid.end(); ++it )
            {
                grid_t::index_type i;
                for( i[0] = it->first[0] - 1; i[0] < it->first[0] + 2; ++i[0] )
                {
                    for( i[1] = it->first[1] - 1; i[1] < it->first[1] + 2; ++i[1] )
                    {
                        for( i[2] = it->first[2] - 1; i[2] < it->first[2] + 2; ++i[2] )
                        {
                            grid_t::iterator git = grid.find( i );
                            if( git == grid.end() ) { continue; }
                            for( voxel_t::iterator vit = it->second.begin(); vit != it->second.end(); ++vit )
                            {
                                for( std::size_t k = 0; k < git->second.size() && ( *vit )->is_extremum; ++k )
                                {
                                    local_operation::evaluate_local_extremum( *vit, git->second[k], radius, sign );
                                }
                            }
                        }
                    }
                }
            }
            #ifdef WIN32
            _setmode( _fileno( stdout ), _O_BINARY );
            #endif
            if( verbose ) { std::cerr << "points-calc: filling extrema grid..." << std::endl; }
            grid_t extrema( extents.min(), resolution );
            for( std::size_t i = 0; i < records.size(); ++i )
            {
                if( records[i].is_extremum )
                { 
                    ( extrema.touch_at( records[i].point.coordinates ) )->second.push_back( &records[i] );
                }
                else
                { 
                    records[i].extremum_id = local_operation::record::invalid_id; // quick and dirty for now
//                     if( records[i].extremum_id == local_operation::record::invalid_id ) { continue; }
//                     while( records[i].reference_record->point.id != records[i].reference_record->reference_record->point.id )
//                     {
//                         records[i].reference_record = records[i].reference_record->reference_record;
//                     }
//                     records[i].extremum_id = records[i].reference_record->point.id;
                }
            }
            if( verbose ) { std::cerr << "points-calc: calculating distances to " << extrema.size() << " local extrema..." << std::endl; }
            for( grid_t::iterator it = grid.begin(); it != grid.end(); ++it )
            {
                grid_t::index_type i;
                for( i[0] = it->first[0] - 1; i[0] < it->first[0] + 2; ++i[0] )
                {
                    for( i[1] = it->first[1] - 1; i[1] < it->first[1] + 2; ++i[1] )
                    {
                        for( i[2] = it->first[2] - 1; i[2] < it->first[2] + 2; ++i[2] )
                        {
                            grid_t::iterator git = extrema.find( i );
                            if( git == extrema.end() ) { continue; }
                            for( std::size_t n = 0; n < it->second.size(); ++n )
                            {                            
                                for( std::size_t k = 0; k < git->second.size(); ++k )
                                {
                                    local_operation::update_nearest_extremum( it->second[n], git->second[k], radius );
                                }
                            }
                        }
                    }
                }
            }
            if( trace )
            {
                if( verbose ) { std::cerr << "points-calc: tracing extrema..." << std::endl; }
                for( std::size_t i = 0; i < records.size(); ++i )
                {
                    if( records[i].extremum_id == local_operation::record::invalid_id ) { continue; }
                    while( records[i].reference_record->point.id != records[i].reference_record->reference_record->point.id )
                    {
                        records[i].reference_record = records[i].reference_record->reference_record;
                    }
                }
            }
            if( verbose ) { std::cerr << "points-calc: outputting..." << std::endl; }
            std::string endl = csv.binary() ? "" : "\n";
            std::string delimiter = csv.binary() ? "" : std::string( 1, csv.delimiter );
            comma::csv::options output_csv;
            if( csv.binary() ) { output_csv.format( "ui,d" ); }
            comma::csv::output_stream< local_operation::output > ostream( std::cout, output_csv );
            for( std::size_t i = 0; i < records.size(); ++i )
            {
                std::cout.write( &records[i].line[0], records[i].line.size() );
                std::cout.write( &delimiter[0], delimiter.size() );
                ostream.write( records[i].output( false ) ); // quick and dirty
            }
            if( verbose ) { std::cerr << "points-calc: done!" << std::endl; }
            return 0;
        }
        if( operation == "nearest-max" || operation == "nearest-min" || operation == "nearest-any" )
        {
            double sign = operation == "nearest-max" ? 1 : -1;
            bool any = operation == "nearest-any";
            if( csv.fields.empty() ) { csv.fields = "x,y,z,scalar"; }
            csv.full_xpath = false;
            bool has_id = csv.has_field( "id" );
            comma::csv::input_stream< local_operation::point > istream( std::cin, csv );
            std::deque< local_operation::record > records;
            double radius = options.value< double >( "--radius" );
            Eigen::Vector3d resolution( radius, radius, radius );
            snark::math::closed_interval< double, 3 > extents;
            comma::uint32 id = 0;
            if( verbose ) { std::cerr << "points-calc: reading input points..." << std::endl; }
            while( istream.ready() || ( std::cin.good() && !std::cin.eof() ) )
            {
                const local_operation::point* p = istream.read();
                if( !p ) { break; }
                std::string line;
                if( csv.binary() ) // quick and dirty
                {
                    line.resize( csv.format().size() );
                    ::memcpy( &line[0], istream.binary().last(), csv.format().size() );
                }
                else
                {
                    line = comma::join( istream.ascii().last(), csv.delimiter );
                }
                local_operation::point q = *p;
                if( !has_id ) { q.id = id++; }
                records.push_back( local_operation::record( q, line ) );
                records.back().reference_record = &records.back();
                extents.set_hull( p->coordinates );
            }
            if( verbose ) { std::cerr << "points-calc: loading " << records.size() << " points into grid..." << std::endl; }
            typedef std::vector< local_operation::record* > voxel_t; // todo: is vector a good container? use deque
            typedef snark::voxel_map< voxel_t, 3 > grid_t;
            grid_t grid( extents.min(), resolution );
            for( std::size_t i = 0; i < records.size(); ++i ) { ( grid.touch_at( records[i].point.coordinates ) )->second.push_back( &records[i] ); }
            if( verbose ) { std::cerr << "points-calc: searching for " << operation << "..." << std::endl; }
            for( grid_t::iterator it = grid.begin(); it != grid.end(); ++it )
            {
                grid_t::index_type i;
                for( i[0] = it->first[0] - 1; i[0] < it->first[0] + 2; ++i[0] )
                {
                    for( i[1] = it->first[1] - 1; i[1] < it->first[1] + 2; ++i[1] )
                    {
                        for( i[2] = it->first[2] - 1; i[2] < it->first[2] + 2; ++i[2] )
                        {
                            grid_t::iterator git = grid.find( i );
                            if( git == grid.end() ) { continue; }
                            for( std::size_t n = 0; n < it->second.size(); ++n )
                            {                            
                                for( std::size_t k = 0; k < git->second.size(); ++k )
                                {
                                    local_operation::update_nearest( it->second[n], git->second[k], radius, sign, any );
                                }
                            }
                        }
                    }
                }
            }
            #ifdef WIN32
            _setmode( _fileno( stdout ), _O_BINARY );
            #endif
            if( verbose ) { std::cerr << "points-calc: outputting..." << std::endl; }
            std::string endl = csv.binary() ? "" : "\n";
            std::string delimiter = csv.binary() ? "" : std::string( 1, csv.delimiter );
            comma::csv::options output_csv;
            if( csv.binary() ) { output_csv.format( "ui,d" ); }
            comma::csv::output_stream< local_operation::output > ostream( std::cout, output_csv );
            for( std::size_t i = 0; i < records.size(); ++i )
            {
                std::cout.write( &records[i].line[0], records[i].line.size() );
                std::cout.write( &delimiter[0], delimiter.size() );
                ostream.write( records[i].output() );
            }
            if( verbose ) { std::cerr << "points-calc: done!" << std::endl; }
            return 0;
        }
        if( operation == "find-outliers" )
        {
            unsigned int size = options.value< unsigned int >( "--min-number-of-points-per-voxel,--size" );
            double r = options.value< double >( "--resolution" );
            Eigen::Vector3d resolution( r, r, r );
            bool no_antialiasing = options.exists( "--no-antialiasing" );            
            comma::csv::input_stream< Eigen::Vector3d > istream( std::cin, csv );
            std::deque< remove_outliers::record > records;
            snark::math::closed_interval< double, 3 > extents;
            if( verbose ) { std::cerr << "points-calc: reading input points..." << std::endl; }
            while( istream.ready() || ( std::cin.good() && !std::cin.eof() ) )
            {
                const Eigen::Vector3d* p = istream.read();
                if( !p ) { break; }
                std::string line;
                if( csv.binary() ) // quick and dirty
                {
                    line.resize( csv.format().size() );
                    ::memcpy( &line[0], istream.binary().last(), csv.format().size() );
                }
                else
                {
                    line = comma::join( istream.ascii().last(), csv.delimiter );
                }
                records.push_back( remove_outliers::record( *p, line ) );
                extents.set_hull( *p );
            }
            if( verbose ) { std::cerr << "points-calc: loading " << records.size() << " points into grid..." << std::endl; }
            typedef std::vector< remove_outliers::record* > voxel_t; // todo: is vector a good container? use deque
            typedef snark::voxel_map< voxel_t, 3 > grid_t;
            grid_t grid( extents.min(), resolution );
            for( std::size_t i = 0; i < records.size(); ++i ) { ( grid.touch_at( records[i].point ) )->second.push_back( &records[i] ); }
            if( verbose ) { std::cerr << "points-calc: removing outliers..." << std::endl; }
            for( grid_t::iterator it = grid.begin(); it != grid.end(); ++it )
            {
                bool rejected = true;
                if( no_antialiasing )
                {
                    rejected = it->second.size() < size;
                }
                else
                {
                    grid_t::index_type i;
                    for( i[0] = it->first[0] - 1; i[0] < it->first[0] + 2 && rejected; ++i[0] )
                    {
                        for( i[1] = it->first[1] - 1; i[1] < it->first[1] + 2 && rejected; ++i[1] )
                        {
                            for( i[2] = it->first[2] - 1; i[2] < it->first[2] + 2 && rejected; ++i[2] )
                            {
                                grid_t::iterator git = grid.find( i );
                                rejected = git == grid.end() || git->second.size() < size;
                            }
                        }
                    }
                }
                if( rejected ) { for( std::size_t i = 0; i < it->second.size(); ++i ) { it->second[i]->rejected = true; } }
            }
            #ifdef WIN32
            _setmode( _fileno( stdout ), _O_BINARY );
            #endif
            if( verbose ) { std::cerr << "points-calc: outputting..." << std::endl; }
            std::string endl = csv.binary() ? "" : "\n";
            std::string delimiter = csv.binary() ? "" : std::string( 1, csv.delimiter );
            for( std::size_t i = 0; i < records.size(); ++i )
            {
                char valid = records[i].rejected ? 0 : 1;
                std::cout.write( &records[i].line[0], records[i].line.size() );
                std::cout.write( &delimiter[0], delimiter.size() );
                std::cout.write( &valid, 1 );
                std::cout.write( &endl[0], endl.size() );
            }
            if( verbose ) { std::cerr << "points-calc: done!" << std::endl; }
            return 0;
        }
        std::cerr << "points-calc: please specify an operation" << std::endl;
        return 1;
    }
    catch( std::exception& ex )
    {
        std::cerr << "points-calc: " << ex.what() << std::endl;
    }
    catch( ... )
    {
        std::cerr << "points-calc: unknown exception" << std::endl;
    }
    return 1;
}