int DoSuperpixelSegmentation_ForGivenK(
            int[] ubuff,
            int width,
            int height,
            int[] klabels,
            int numlabels,
            int K,//required number of superpixels
            double m,//weight given to spatial distance
            boolean LAB_space) {

        //--------------------------------------------------
        m_width = width;
        m_height = height;
        int sz = m_width * m_height;
        //--------------------------------------------------
        //if(0 == klabels) klabels = new int[sz];
        for (int s = 0; s < sz; s++) {
            klabels[s] = -1;
         }
        //--------------------------------------------------
        
        if (LAB_space)//LAB
        {
            m_lvec = new double[sz];
            m_avec = new double[sz];
            m_bvec = new double[sz];
            DoRGBtoLABConversion(ubuff, m_lvec, m_avec, m_bvec);
        } else//RGB
        {
            m_lvec = new double[sz];
            m_avec = new double[sz];
            m_bvec = new double[sz];
            for (int i = 0; i < sz; i++) {
                m_lvec[i] = ubuff[i] >> 16 & 0xff;
                m_avec[i] = ubuff[i] >>  8 & 0xff;
                m_bvec[i] = ubuff[i]       & 0xff;
            }
        }
        //--------------------------------------------------

        boolean perturbseeds = true;
        double[] edgemag = new double[sz];
        for (int i = 0; i < sz; i++) {
            edgemag[i] = 0;
        }
        if (perturbseeds) {
            DetectLabEdges(m_lvec, m_avec, m_bvec, m_width, m_height, edgemag);
        }

        int css = countSeedSize(K);
        double[] kseedsl = new double[css];
        double[] kseedsa = new double[css];
        double[] kseedsb = new double[css];
        double[] kseedsx = new double[css];
        double[] kseedsy = new double[css];

       GetLABXYSeeds_ForGivenStepSize(kseedsl, kseedsa, kseedsb, kseedsx, kseedsy, K, perturbseeds, edgemag);

       int STEP = (int) (Math.sqrt((double) (sz) / (double) (K)) + 2.0);//adding a small value in the even the STEP size is too small.
       PerformSuperpixelSLIC(kseedsl, kseedsa, kseedsb, kseedsx, kseedsy, klabels, STEP, edgemag, m);
            
       numlabels = kseedsl.length;

       int[] nlabels = new int[sz];
       for (int s = 0; s < sz; s++) {
           nlabels[s] = -1;
        }
      
       EnforceLabelConnectivity(klabels, m_width, m_height, nlabels, numlabels, K);
       System.arraycopy(nlabels, 0, klabels, 0, sz);
        
       return (numlabels);
    }