예제 #1
0
  private void spawnRandomers() {
    for (int i = 0; i < randomN; i++) {
      float x = (float) Math.random() * width;
      float y = (float) Math.random() * height;
      float r =
          (float)
              Math.sqrt(
                  Math.pow(((Player) players.get(0)).getX() - x, 2)
                      + Math.pow(((Player) players.get(0)).getY() - x, 2));

      while (r < distanceLimit) {
        x = (float) Math.random() * width;
        y = (float) Math.random() * height;
        r =
            (float)
                Math.sqrt(
                    Math.pow(((Player) players.get(0)).getX() - x, 2)
                        + Math.pow(((Player) players.get(0)).getY() - y, 2));
      }

      enemies.add(new EnemyTypes.Random(x, y, 0.5f, borders));
    }

    spawnRandomersB = false;
  }
예제 #2
0
 /* Creates a spline fitted polygon with one pixel segment lengths
 that can be retrieved using the getFloatPolygon() method. */
 public void fitSplineForStraightening() {
   fitSpline((int) getUncalibratedLength() * 2);
   if (splinePoints == 0) return;
   float[] xpoints = new float[splinePoints * 2];
   float[] ypoints = new float[splinePoints * 2];
   xpoints[0] = xSpline[0];
   ypoints[0] = ySpline[0];
   int n = 1, n2;
   double inc = 0.01;
   double distance = 0.0, distance2 = 0.0, dx = 0.0, dy = 0.0, xinc, yinc;
   double x, y, lastx, lasty, x1, y1, x2 = xSpline[0], y2 = ySpline[0];
   for (int i = 1; i < splinePoints; i++) {
     x1 = x2;
     y1 = y2;
     x = x1;
     y = y1;
     x2 = xSpline[i];
     y2 = ySpline[i];
     dx = x2 - x1;
     dy = y2 - y1;
     distance = Math.sqrt(dx * dx + dy * dy);
     xinc = dx * inc / distance;
     yinc = dy * inc / distance;
     lastx = xpoints[n - 1];
     lasty = ypoints[n - 1];
     // n2 = (int)(dx/xinc);
     n2 = (int) (distance / inc);
     if (splinePoints == 2) n2++;
     do {
       dx = x - lastx;
       dy = y - lasty;
       distance2 = Math.sqrt(dx * dx + dy * dy);
       // IJ.log(i+"   "+IJ.d2s(xinc,5)+"   "+IJ.d2s(yinc,5)+"   "+IJ.d2s(distance,2)+"
       // "+IJ.d2s(distance2,2)+"   "+IJ.d2s(x,2)+"   "+IJ.d2s(y,2)+"   "+IJ.d2s(lastx,2)+"
       // "+IJ.d2s(lasty,2)+"   "+n+"   "+n2);
       if (distance2 >= 1.0 - inc / 2.0 && n < xpoints.length - 1) {
         xpoints[n] = (float) x;
         ypoints[n] = (float) y;
         // IJ.log("--- "+IJ.d2s(x,2)+"   "+IJ.d2s(y,2)+"  "+n);
         n++;
         lastx = x;
         lasty = y;
       }
       x += xinc;
       y += yinc;
     } while (--n2 > 0);
   }
   xSpline = xpoints;
   ySpline = ypoints;
   splinePoints = n;
 }
예제 #3
0
파일: LJ3MDApp.java 프로젝트: eskilj/mvp
 static { // data[] is a bitmap image of the ball of radius R
   data = new byte[R * 2 * R * 2];
   for (int Y = -R; Y < R; Y++) {
     int x0 = (int) (Math.sqrt(R * R - Y * Y) + 0.5);
     for (int X = -x0; X < x0; X++) {
       // sqrt(x^2 + y^2) gives distance from the spot light
       int x = X + hx, y = Y + hy;
       int r = (int) (Math.sqrt(x * x + y * y) + 0.5);
       // set the maximal intensity to the maximal distance
       // (in pixels) from the spot light
       if (r > maxr) maxr = r;
       data[(Y + R) * (R * 2) + (X + R)] = (r <= 0) ? 1 : (byte) r;
     }
   }
 }
예제 #4
0
  // For now the final output is unusable.  The associated quantization step
  // needs some tweaking.  If you get this part working, please let me know.
  public double[][] forwardDCTExtreme(float[][] input) {
    double[][] output = new double[N][N];
    double tmp0;
    double tmp1;
    double tmp2;
    double tmp3;
    double tmp4;
    double tmp5;
    double tmp6;
    double tmp7;
    double tmp10;
    double tmp11;
    double tmp12;
    double tmp13;
    double z1;
    double z2;
    double z3;
    double z4;
    double z5;
    double z11;
    double z13;
    int i;
    int j;
    int v;
    int u;
    int x;
    int y;

    for (v = 0; v < 8; v++) {
      for (u = 0; u < 8; u++) {
        for (x = 0; x < 8; x++) {
          for (y = 0; y < 8; y++) {
            output[v][u] +=
                (((double) input[x][y])
                    * Math.cos(((double) ((2 * x) + 1) * (double) u * Math.PI) / (double) 16)
                    * Math.cos(((double) ((2 * y) + 1) * (double) v * Math.PI) / (double) 16));
          }
        }

        output[v][u] *=
            ((double) (0.25)
                * ((u == 0) ? ((double) 1.0 / Math.sqrt(2)) : (double) 1.0)
                * ((v == 0) ? ((double) 1.0 / Math.sqrt(2)) : (double) 1.0));
      }
    }

    return output;
  }
예제 #5
0
  public void calcDimsAndStartPts(LinkedList llist, draw d) {
    /*  Determines the following variables Lenx, Leny, Startx, Starty,
    TitleStarty   */
    // Task: Calculate the length and height of a node and its starting point.
    //   It also computes the y-coordinate of the title

    double TitleToSSGap, MinGt, MaxGt, Diam, MinTitlex, MaxTitlex;
    int NumNodes, NumLines;
    super.calcDimsAndStartPts(llist, d);
    // With circular nodes, not adding Textheight works better to finetune the circle size
    Lenx = Maxstringlength - .02;
    Leny = ((linespernode + 1) * Textheight) + ((linespernode - 1) * (0.5 * Textheight));
    TDx = (Lenx + Leny) / 5.0; // Height is a third of their average *)
    TDy = TDx / Math.sqrt(3);
    TitleToSSGap = 2 * Titleheight;
    NumLines = title.size();
    Startx = 0.0;
    Starty =
        Topy
            - IconHeight
            - IconToTitleGap
            - (NumLines * Titleheight)
            - ((NumLines - 1) * (0.5 * Titleheight))
            - TitleToSSGap
            - (Lenx / 2.0)
            - .15;
    TitleStarty = (Topy - IconHeight - IconToTitleGap - Titleheight) + .05;
  }
예제 #6
0
 public static WritableRaster glowmask(Raster img) {
   Coord sz = imgsz(img);
   int nb = img.getNumBands();
   WritableRaster ret = alpharaster(sz);
   float[] hsv = new float[3];
   float max = 0;
   for (int y = 0; y < sz.y; y++) {
     for (int x = 0; x < sz.x; x++) {
       Color.RGBtoHSB(img.getSample(x, y, 0), img.getSample(x, y, 1), img.getSample(x, y, 2), hsv);
       float a = (nb > 3) ? (img.getSample(x, y, 3) / 255f) : 1f;
       float val = ((1f - hsv[1]) * hsv[2]) * a;
       max = Math.max(max, val);
     }
   }
   float imax = 1f / max;
   for (int y = 0; y < sz.y; y++) {
     for (int x = 0; x < sz.x; x++) {
       Color.RGBtoHSB(img.getSample(x, y, 0), img.getSample(x, y, 1), img.getSample(x, y, 2), hsv);
       float a = (nb > 3) ? (img.getSample(x, y, 3) / 255f) : 1f;
       float val = ((1f - hsv[1]) * hsv[2]) * a;
       ret.setSample(x, y, 0, Math.min(Math.max((int) (Math.sqrt(val * imax) * 255), 0), 255));
     }
   }
   return (ret);
 }
예제 #7
0
 /**
  * Returns the perimeter length of ROIs created using the wand tool and the particle analyzer. The
  * algorithm counts edge pixels as 1 and corner pixels as sqrt(2). It does this by calculating the
  * total length of the ROI boundary and subtracting 2-sqrt(2) for each non-adjacent corner. For
  * example, a 1x1 pixel ROI has a boundary length of 4 and 2 non-adjacent edges so the perimeter
  * is 4-2*(2-sqrt(2)). A 2x2 pixel ROI has a boundary length of 8 and 4 non-adjacent edges so the
  * perimeter is 8-4*(2-sqrt(2)).
  */
 double getTracedPerimeter() {
   int sumdx = 0;
   int sumdy = 0;
   int nCorners = 0;
   int dx1 = xp[0] - xp[nPoints - 1];
   int dy1 = yp[0] - yp[nPoints - 1];
   int side1 = Math.abs(dx1) + Math.abs(dy1); // one of these is 0
   boolean corner = false;
   int nexti, dx2, dy2, side2;
   for (int i = 0; i < nPoints; i++) {
     nexti = i + 1;
     if (nexti == nPoints) nexti = 0;
     dx2 = xp[nexti] - xp[i];
     dy2 = yp[nexti] - yp[i];
     sumdx += Math.abs(dx1);
     sumdy += Math.abs(dy1);
     side2 = Math.abs(dx2) + Math.abs(dy2);
     if (side1 > 1 || !corner) {
       corner = true;
       nCorners++;
     } else corner = false;
     dx1 = dx2;
     dy1 = dy2;
     side1 = side2;
   }
   double w = 1.0, h = 1.0;
   if (imp != null) {
     Calibration cal = imp.getCalibration();
     w = cal.pixelWidth;
     h = cal.pixelHeight;
   }
   return sumdx * w + sumdy * h - (nCorners * ((w + h) - Math.sqrt(w * w + h * h)));
 }
예제 #8
0
 /**
  * Find the distance between two characters
  *
  * @param Targ Target character
  * @return distance
  */
 public double Dist(GameObject Targ) {
   // find x squared and y squared
   double dx =
       Math.pow(((X + W / 2 * GROWTHFACTOR) - (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR)), 2);
   double dy =
       Math.pow(((Y + H / 2 * GROWTHFACTOR) - (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR)), 2);
   // find distance
   return (Math.sqrt(dx + dy));
 }
예제 #9
0
 void handleMouseMove(int sx, int sy) {
   // Do rubber banding
   int tool = Toolbar.getToolId();
   if (!(tool == Toolbar.POLYGON || tool == Toolbar.POLYLINE || tool == Toolbar.ANGLE)) {
     imp.deleteRoi();
     imp.draw();
     return;
   }
   drawRubberBand(sx, sy);
   degrees = Double.NaN;
   double len = -1;
   if (nPoints > 1) {
     double x1, y1, x2, y2;
     if (xpf != null) {
       x1 = xpf[nPoints - 2];
       y1 = ypf[nPoints - 2];
       x2 = xpf[nPoints - 1];
       y2 = ypf[nPoints - 1];
     } else {
       x1 = xp[nPoints - 2];
       y1 = yp[nPoints - 2];
       x2 = xp[nPoints - 1];
       y2 = yp[nPoints - 1];
     }
     degrees =
         getAngle(
             (int) Math.round(x1),
             (int) Math.round(y1),
             (int) Math.round(x2),
             (int) Math.round(y2));
     if (tool != Toolbar.ANGLE) {
       Calibration cal = imp.getCalibration();
       double pw = cal.pixelWidth, ph = cal.pixelHeight;
       if (IJ.altKeyDown()) {
         pw = 1.0;
         ph = 1.0;
       }
       len = Math.sqrt((x2 - x1) * pw * (x2 - x1) * pw + (y2 - y1) * ph * (y2 - y1) * ph);
     }
   }
   if (tool == Toolbar.ANGLE) {
     if (nPoints == 2) angle1 = degrees;
     else if (nPoints == 3) {
       double angle2 = getAngle(xp[1], yp[1], xp[2], yp[2]);
       degrees = Math.abs(180 - Math.abs(angle1 - angle2));
       if (degrees > 180.0) degrees = 360.0 - degrees;
     }
   }
   String length = len != -1 ? ", length=" + IJ.d2s(len) : "";
   double degrees2 =
       tool == Toolbar.ANGLE && nPoints == 3 && Prefs.reflexAngle ? 360.0 - degrees : degrees;
   String angle = !Double.isNaN(degrees) ? ", angle=" + IJ.d2s(degrees2) : "";
   int ox = ic != null ? ic.offScreenX(sx) : sx;
   int oy = ic != null ? ic.offScreenY(sy) : sy;
   IJ.showStatus(imp.getLocationAsString(ox, oy) + length + angle);
 }
예제 #10
0
파일: Picture.java 프로젝트: rafacb/MasLab
 static BufferedImage addMagnitudes(BufferedImage img1, BufferedImage img2) {
   BufferedImage dst = new BufferedImage(img1.getWidth(), img1.getHeight(), img1.getType());
   for (int y = 0; y < img1.getHeight(); ++y) {
     for (int x = 0; x < img1.getWidth(); ++x) {
       int rgb1 = img1.getRGB(x, y);
       int rgb2 = img2.getRGB(x, y);
       int r1 = (rgb1 & 0x00FF0000) >> 16;
       int r2 = (rgb2 & 0x00FF0000) >> 16;
       int r = (int) (Math.sqrt(r1 * r1 + r2 * r2) / Math.sqrt(2.0));
       if (r > 255) r = 255;
       if (r < 0) r = 0;
       int g1 = (rgb1 & 0x0000FF00) >> 8;
       int g2 = (rgb2 & 0x0000FF00) >> 8;
       int g = (int) (Math.sqrt(g1 * g1 + g2 * g2) / Math.sqrt(2.0));
       if (g > 255) g = 255;
       if (g < 0) g = 0;
       int b1 = rgb1 & 0x000000FF;
       int b2 = rgb2 & 0x000000FF;
       int b = (int) (Math.sqrt(b1 * b1 + b2 * b2) / Math.sqrt(2.0));
       if (b > 255) b = 255;
       if (b < 0) b = 0;
       int rgb = b + (g << 8) + (r << 16);
       dst.setRGB(x, y, rgb);
     }
   }
   return dst;
 }
예제 #11
0
 double getFloatSmoothedPerimeter() {
   double length = getSmoothedLineLength();
   double w2 = 1.0, h2 = 1.0;
   if (imp != null) {
     Calibration cal = imp.getCalibration();
     w2 = cal.pixelWidth * cal.pixelWidth;
     h2 = cal.pixelHeight * cal.pixelHeight;
   }
   double dx = xpf[nPoints - 1] - xpf[0];
   double dy = ypf[nPoints - 1] - ypf[0];
   length += Math.sqrt(dx * dx * w2 + dy * dy * h2);
   return length;
 }
예제 #12
0
 double getFloatSmoothedLineLength() {
   double length = 0.0;
   double w2 = 1.0;
   double h2 = 1.0;
   double dx, dy;
   if (imp != null) {
     Calibration cal = imp.getCalibration();
     w2 = cal.pixelWidth * cal.pixelWidth;
     h2 = cal.pixelHeight * cal.pixelHeight;
   }
   dx = (xpf[0] + xpf[1] + xpf[2]) / 3.0 - xpf[0];
   dy = (ypf[0] + ypf[1] + ypf[2]) / 3.0 - ypf[0];
   length += Math.sqrt(dx * dx * w2 + dy * dy * h2);
   for (int i = 1; i < nPoints - 2; i++) {
     dx = (xpf[i + 2] - xpf[i - 1]) / 3.0;
     dy = (ypf[i + 2] - ypf[i - 1]) / 3.0;
     length += Math.sqrt(dx * dx * w2 + dy * dy * h2);
   }
   dx = xpf[nPoints - 1] - (xpf[nPoints - 3] + xpf[nPoints - 2] + xpf[nPoints - 1]) / 3.0;
   dy = ypf[nPoints - 1] - (ypf[nPoints - 3] + ypf[nPoints - 2] + ypf[nPoints - 1]) / 3.0;
   length += Math.sqrt(dx * dx * w2 + dy * dy * h2);
   return length;
 }
예제 #13
0
        public void mousePressed(MouseEvent e) {
          requestFocus();
          Point p = e.getPoint();
          int size =
              Math.min(
                  MAX_SIZE,
                  Math.min(
                      getWidth() - imagePadding.left - imagePadding.right,
                      getHeight() - imagePadding.top - imagePadding.bottom));
          p.translate(-(getWidth() / 2 - size / 2), -(getHeight() / 2 - size / 2));
          if (mode == ColorPicker.BRI || mode == ColorPicker.SAT) {
            // the two circular views:
            double radius = ((double) size) / 2.0;
            double x = p.getX() - size / 2.0;
            double y = p.getY() - size / 2.0;
            double r = Math.sqrt(x * x + y * y) / radius;
            double theta = Math.atan2(y, x) / (Math.PI * 2.0);

            if (r > 1) r = 1;

            if (mode == ColorPicker.BRI) {
              setHSB((float) (theta + .25f), (float) (r), bri);
            } else {
              setHSB((float) (theta + .25f), sat, (float) (r));
            }
          } else if (mode == ColorPicker.HUE) {
            float s = ((float) p.x) / ((float) size);
            float b = ((float) p.y) / ((float) size);
            if (s < 0) s = 0;
            if (s > 1) s = 1;
            if (b < 0) b = 0;
            if (b > 1) b = 1;
            setHSB(hue, s, b);
          } else {
            int x2 = p.x * 255 / size;
            int y2 = p.y * 255 / size;
            if (x2 < 0) x2 = 0;
            if (x2 > 255) x2 = 255;
            if (y2 < 0) y2 = 0;
            if (y2 > 255) y2 = 255;

            if (mode == ColorPicker.RED) {
              setRGB(red, x2, y2);
            } else if (mode == ColorPicker.GREEN) {
              setRGB(x2, green, y2);
            } else {
              setRGB(x2, y2, blue);
            }
          }
        }
예제 #14
0
 protected void transformInverse(int x, int y, float[] out) {
   float dx = x - icentreX;
   float dy = y - icentreY;
   float distance = dx * dx + dy * dy;
   if (distance > radius2) {
     out[0] = x;
     out[1] = y;
   } else {
     distance = (float) Math.sqrt(distance);
     float a = (float) Math.atan2(dy, dx) + angle * (radius - distance) / radius;
     out[0] = icentreX + distance * (float) Math.cos(a);
     out[1] = icentreY + distance * (float) Math.sin(a);
   }
 }
예제 #15
0
  /** Returns the perimeter (for ROIs) or length (for lines). */
  public double getLength() {
    if (type == TRACED_ROI) return getTracedPerimeter();

    if (nPoints > 2) {
      if (type == FREEROI) return getSmoothedPerimeter();
      else if (type == FREELINE && !(width == 0 || height == 0)) return getSmoothedLineLength();
    }

    double length = 0.0;
    int dx, dy;
    double w2 = 1.0, h2 = 1.0;
    if (imp != null) {
      Calibration cal = imp.getCalibration();
      w2 = cal.pixelWidth * cal.pixelWidth;
      h2 = cal.pixelHeight * cal.pixelHeight;
    }
    if (xSpline != null) {
      double fdx, fdy;
      for (int i = 0; i < (splinePoints - 1); i++) {
        fdx = xSpline[i + 1] - xSpline[i];
        fdy = ySpline[i + 1] - ySpline[i];
        length += Math.sqrt(fdx * fdx * w2 + fdy * fdy * h2);
      }
      if (type == POLYGON) {
        fdx = xSpline[0] - xSpline[splinePoints - 1];
        fdy = ySpline[0] - ySpline[splinePoints - 1];
        length += Math.sqrt(fdx * fdx * w2 + fdy * fdy * h2);
      }
    } else if (xpf != null) {
      double fdx, fdy;
      for (int i = 0; i < (nPoints - 1); i++) {
        fdx = xpf[i + 1] - xpf[i];
        fdy = ypf[i + 1] - ypf[i];
        length += Math.sqrt(fdx * fdx * w2 + fdy * fdy * h2);
      }
      if (type == POLYGON) {
        fdx = xpf[0] - xpf[nPoints - 1];
        fdy = ypf[0] - ypf[nPoints - 1];
        length += Math.sqrt(fdx * fdx * w2 + fdy * fdy * h2);
      }
    } else {
      for (int i = 0; i < (nPoints - 1); i++) {
        dx = xp[i + 1] - xp[i];
        dy = yp[i + 1] - yp[i];
        length += Math.sqrt(dx * dx * w2 + dy * dy * h2);
      }
      if (type == POLYGON) {
        dx = xp[0] - xp[nPoints - 1];
        dy = yp[0] - yp[nPoints - 1];
        length += Math.sqrt(dx * dx * w2 + dy * dy * h2);
      }
    }
    return length;
  }
예제 #16
0
 /**
  * 指定した属性でJDGradientPaintを構築します.
  *
  * @param p1 ユーザー空間で最初に指定されたPoint<br>
  *     p2 ユーザー空間で2番目に指定されたPoint<br>
  *     ; c1 ポイントp1のカラー<br>
  *     c2 ポイントp2のカラー<br>
  *     cp p1からp2間の制御点 cols 制御点のカラー gTyp 塗りのタイプ
  */
 public JDGradientPaint(
     Point2D p1, Point2D p2, Color c1, Color c2, float[] cp, Color[] cols, int gType) {
   this.p1 = p1;
   this.p2 = p2;
   this.c1 = c1;
   this.c2 = c2;
   this.controlPoints = cp;
   this.colors = cols;
   this.gType = gType;
   dx = (float) (p2.getX() - p1.getX());
   dy = (float) (p2.getY() - p1.getY());
   distance = (float) Math.sqrt(dx * dx + dy * dy);
   startC = new float[4];
   endC = new float[4];
   startC = c1.getComponents(startC);
   endC = c2.getComponents(endC);
 }
예제 #17
0
 public void vec2FieldMagnitude(Field field, AffineTransform ftoi) {
   AffineTransform itof = null;
   try {
     itof = ftoi.createInverse();
   } catch (NoninvertibleTransformException niv) {
     TDebug.println(0, "NoninvertibleTransformException: " + niv);
   }
   Vector3d v = new Vector3d();
   Point2D.Double p = new Point2D.Double();
   for (int j = 0, k = 0; j < height; ++j)
     for (int i = 0; i < width; ++i, ++k) {
       p.x = i;
       p.y = j;
       itof.transform(p, p);
       v = field.get(p.x, p.y, 0.0);
       f[k] = (float) Math.sqrt(v.x * v.x + v.y * v.y);
     }
 }
예제 #18
0
  /**
   * Make a Gaussian blur kernel.
   *
   * @param radius the blur radius
   * @return the kernel
   */
  public static Kernel makeKernel(float radius) {
    int r = (int) Math.ceil(radius);
    int rows = r * 2 + 1;
    float[] matrix = new float[rows];
    float sigma = radius / 3;
    float sigma22 = 2 * sigma * sigma;
    float sigmaPi2 = 2 * ImageMath.PI * sigma;
    float sqrtSigmaPi2 = (float) Math.sqrt(sigmaPi2);
    float radius2 = radius * radius;
    float total = 0;
    int index = 0;
    for (int row = -r; row <= r; row++) {
      float distance = row * row;
      if (distance > radius2) matrix[index] = 0;
      else matrix[index] = (float) Math.exp(-(distance) / sigma22) / sqrtSigmaPi2;
      total += matrix[index];
      index++;
    }
    for (int i = 0; i < rows; i++) matrix[i] /= total;

    return new Kernel(rows, 1, matrix);
  }
예제 #19
0
  protected void transformInverse(int x, int y, float[] out) {
    float theta, t;
    float m, xmax, ymax;
    float r = 0;

    switch (type) {
      case RECT_TO_POLAR:
        theta = 0;
        if (x >= centreX) {
          if (y > centreY) {
            theta =
                ImageMath.PI - (float) Math.atan(((float) (x - centreX)) / ((float) (y - centreY)));
            r = (float) Math.sqrt(sqr(x - centreX) + sqr(y - centreY));
          } else if (y < centreY) {
            theta = (float) Math.atan(((float) (x - centreX)) / ((float) (centreY - y)));
            r = (float) Math.sqrt(sqr(x - centreX) + sqr(centreY - y));
          } else {
            theta = ImageMath.HALF_PI;
            r = x - centreX;
          }
        } else if (x < centreX) {
          if (y < centreY) {
            theta =
                ImageMath.TWO_PI
                    - (float) Math.atan(((float) (centreX - x)) / ((float) (centreY - y)));
            r = (float) Math.sqrt(sqr(centreX - x) + sqr(centreY - y));
          } else if (y > centreY) {
            theta =
                ImageMath.PI + (float) Math.atan(((float) (centreX - x)) / ((float) (y - centreY)));
            r = (float) Math.sqrt(sqr(centreX - x) + sqr(y - centreY));
          } else {
            theta = 1.5f * ImageMath.PI;
            r = centreX - x;
          }
        }
        if (x != centreX) m = Math.abs(((float) (y - centreY)) / ((float) (x - centreX)));
        else m = 0;

        if (m <= ((float) height / (float) width)) {
          if (x == centreX) {
            xmax = 0;
            ymax = centreY;
          } else {
            xmax = centreX;
            ymax = m * xmax;
          }
        } else {
          ymax = centreY;
          xmax = ymax / m;
        }

        out[0] = (width - 1) - (width - 1) / ImageMath.TWO_PI * theta;
        out[1] = height * r / radius;
        break;
      case POLAR_TO_RECT:
        theta = x / width * ImageMath.TWO_PI;
        float theta2;

        if (theta >= 1.5f * ImageMath.PI) theta2 = ImageMath.TWO_PI - theta;
        else if (theta >= ImageMath.PI) theta2 = theta - ImageMath.PI;
        else if (theta >= 0.5f * ImageMath.PI) theta2 = ImageMath.PI - theta;
        else theta2 = theta;

        t = (float) Math.tan(theta2);
        if (t != 0) m = 1.0f / t;
        else m = 0;

        if (m <= ((float) (height) / (float) (width))) {
          if (theta2 == 0) {
            xmax = 0;
            ymax = centreY;
          } else {
            xmax = centreX;
            ymax = m * xmax;
          }
        } else {
          ymax = centreY;
          xmax = ymax / m;
        }

        r = radius * (float) (y / (float) (height));

        float nx = -r * (float) Math.sin(theta2);
        float ny = r * (float) Math.cos(theta2);

        if (theta >= 1.5f * ImageMath.PI) {
          out[0] = (float) centreX - nx;
          out[1] = (float) centreY - ny;
        } else if (theta >= Math.PI) {
          out[0] = (float) centreX - nx;
          out[1] = (float) centreY + ny;
        } else if (theta >= 0.5 * Math.PI) {
          out[0] = (float) centreX + nx;
          out[1] = (float) centreY + ny;
        } else {
          out[0] = (float) centreX + nx;
          out[1] = (float) centreY - ny;
        }
        break;
      case INVERT_IN_CIRCLE:
        float dx = x - centreX;
        float dy = y - centreY;
        float distance2 = dx * dx + dy * dy;
        out[0] = centreX + centreX * centreX * dx / distance2;
        out[1] = centreY + centreY * centreY * dy / distance2;
        break;
    }
  }
예제 #20
0
  public void actionPerformed(ActionEvent evt) {
    Graphics g = getGraphics();
    if (evt.getSource() == openItem) {
      JFileChooser chooser = new JFileChooser();
      common.chooseFile(chooser, "./images", 0); // 设置默认目录,过滤文件
      int r = chooser.showOpenDialog(null);

      if (r == JFileChooser.APPROVE_OPTION) {
        String name = chooser.getSelectedFile().getAbsolutePath();

        // 装载图像
        iImage = common.openImage(name, new MediaTracker(this));

        // 取载入图像的宽和高
        iw = iImage.getWidth(null);
        ih = iImage.getHeight(null);
        bImage = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bImage.createGraphics();
        g2.drawImage(iImage, 0, 0, null);
        loadflag = true;
        repaint();
      }
    } else if (evt.getSource() == rotateItem) // 内置旋转
    {
      setTitle("第4章 图像几何变换 内置旋转 作者 孙燮华");
      common.draw(g, iImage, bImage, common.getParam("旋转角(度):", "30"), 0, 0);
    } else if (evt.getSource() == scaleItem) // 内置缩放
    {
      setTitle("第4章 图像几何变换 内置缩放 作者 孙燮华");
      // 参数选择面板
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "1.5", "1.5");
      setPanel(pp, "内置缩放");
      float x = pp.getPadx();
      float y = pp.getPady();
      common.draw(g, iImage, bImage, x, y, 1);
    } else if (evt.getSource() == shearItem) // 内置错切
    {
      setTitle("第4章 图像几何变换 内置错切 作者 孙燮华");
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "0.5", "0.5");
      setPanel(pp, "内置错切");
      float x = pp.getPadx();
      float y = pp.getPady();
      common.draw(g, iImage, bImage, x, y, 2);
    } else if (evt.getSource() == transItem) // 内置平移
    {
      setTitle("第4章 图像几何变换 内置平移 作者 孙燮华");
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "100", "50");
      setPanel(pp, "内置平移");
      float x = pp.getPadx();
      float y = pp.getPady();
      common.draw(g, iImage, bImage, x, y, 3);
    } else if (evt.getSource() == rotItem) // 旋转算法
    {
      setTitle("第4章 图像几何变换 旋转算法 作者 孙燮华");
      pix = common.grabber(iImage, iw, ih);

      // 旋转,输出图像宽高
      int owh = (int) (Math.sqrt(iw * iw + ih * ih + 0.5));
      opix = geom.imRotate(pix, common.getParam("旋转角(度):", "30"), iw, ih, owh);

      // 将数组中的象素产生一个图像
      MemoryImageSource memoryImage =
          new MemoryImageSource(owh, owh, ColorModel.getRGBdefault(), opix, 0, owh);
      oImage = createImage(memoryImage);
      common.draw(g, iImage, oImage, iw, ih, owh, 4);
    } else if (evt.getSource() == mirItem) // 镜象算法(type:5)
    {
      setTitle("第4章 图像几何变换 镜象算法 作者 孙燮华");
      Parameters pp = new Parameters("选择镜象类型", "水平", "垂直");
      setPanel(pp, "镜象算法");

      pix = common.grabber(iImage, iw, ih);
      opix = geom.imMirror(pix, iw, ih, pp.getRadioState());
      ImageProducer ip = new MemoryImageSource(iw, ih, opix, 0, iw);
      oImage = createImage(ip);
      common.draw(g, iImage, oImage, iw, ih, 0, 5);
    } else if (evt.getSource() == shrItem) // 错切算法(type:6)
    {
      setTitle("第4章 图像几何变换 错切算法 作者 孙燮华");
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "0.5", "0.5");
      setPanel(pp, "错切算法");

      pix = common.grabber(iImage, iw, ih);

      float shx = pp.getPadx();
      float shy = pp.getPady();

      // 计算包围盒的宽和高
      int ow = (int) (iw + (ih - 1) * shx);
      int oh = (int) ((iw - 1) * shy + ih);

      if (shx > 0 && shy > 0) {
        opix = geom.imShear(pix, shx, shy, iw, ih, ow, oh);
        ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
        oImage = createImage(ip);
        common.draw(g, iImage, oImage, iw, ih, 0, 6);
      } else JOptionPane.showMessageDialog(null, "参数必须为正数!");
    } else if (evt.getSource() == trnItem) {
      setTitle("第4章 图像几何变换 平移算法 作者 孙燮华");
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "100", "50");
      setPanel(pp, "平移算法");
      pix = common.grabber(iImage, iw, ih);
      int tx = (int) pp.getPadx();
      int ty = (int) pp.getPady();

      if (tx > 0 && ty > 0) {
        int ow = iw + tx;
        int oh = ih + ty;
        opix = geom.imTrans(pix, tx, ty, iw, ih, ow, oh);
        ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
        oImage = createImage(ip);
        common.draw(g, iImage, oImage, iw, ih, 0, 7);
      } else JOptionPane.showMessageDialog(null, "参数必须为正数!");
    } else if (evt.getSource() == nearItem) {
      setTitle("第4章 图像几何变换 最邻近插值算法 作者 孙燮华");
      pix = common.grabber(iImage, iw, ih);

      float p =
          (Float.valueOf(JOptionPane.showInputDialog(null, "输入缩放参数(0.1-3.0)", "1.50")))
              .floatValue();
      int ow = (int) (p * iw); // 计算目标图宽高
      int oh = (int) (p * ih);
      opix = geom.nearNeighbor(pix, iw, ih, ow, oh, p);
      ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
      oImage = createImage(ip);
      common.draw(g, oImage, "最邻近插值", p);
    } else if (evt.getSource() == linrItem) {
      setTitle("第4章 图像几何变换 双线性插值算法 作者 孙燮华");
      pix = common.grabber(iImage, iw, ih);

      float p =
          (Float.valueOf(JOptionPane.showInputDialog(null, "输入缩放参数(0.1-3.0)", "1.50")))
              .floatValue();
      int ow = (int) (p * iw); // 计算目标图宽高
      int oh = (int) (p * ih);
      opix = geom.bilinear(pix, iw, ih, ow, oh, p);
      ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
      oImage = createImage(ip);
      common.draw(g, oImage, "双线性插值", p);
    } else if (evt.getSource() == cubicItem) {
      setTitle("第4章 图像几何变换 三次卷积插值算法 作者 孙燮华");
      pix = common.grabber(iImage, iw, ih);

      float p =
          (Float.valueOf(JOptionPane.showInputDialog(null, "输入缩放参数(1.1-3.0)", "1.50")))
              .floatValue();
      if (p < 1) {
        JOptionPane.showMessageDialog(null, "参数p必须大于1!");
        return;
      }
      int ow = (int) (p * iw); // 计算目标图宽高
      int oh = (int) (p * ih);
      opix = geom.scale(pix, iw, ih, ow, oh, p, p);
      ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
      oImage = createImage(ip);
      common.draw(g, oImage, "三次卷积插值", p);
    } else if (evt.getSource() == okButton) dialog.dispose();
    else if (evt.getSource() == exitItem) System.exit(0);
  }
예제 #21
0
  /** Regenerates the image. */
  private synchronized void regenerateImage() {
    int size =
        Math.min(
            MAX_SIZE,
            Math.min(
                getWidth() - imagePadding.left - imagePadding.right,
                getHeight() - imagePadding.top - imagePadding.bottom));

    if (mode == ColorPicker.BRI || mode == ColorPicker.SAT) {
      float bri2 = this.bri;
      float sat2 = this.sat;
      float radius = ((float) size) / 2f;
      float hue2;
      float k = 1.2f; // the number of pixels to antialias
      for (int y = 0; y < size; y++) {
        float y2 = (y - size / 2f);
        for (int x = 0; x < size; x++) {
          float x2 = (x - size / 2f);
          double theta = Math.atan2(y2, x2) - 3 * Math.PI / 2.0;
          if (theta < 0) theta += 2 * Math.PI;

          double r = Math.sqrt(x2 * x2 + y2 * y2);
          if (r <= radius) {
            if (mode == ColorPicker.BRI) {
              hue2 = (float) (theta / (2 * Math.PI));
              sat2 = (float) (r / radius);
            } else { // SAT
              hue2 = (float) (theta / (2 * Math.PI));
              bri2 = (float) (r / radius);
            }
            row[x] = Color.HSBtoRGB(hue2, sat2, bri2);
            if (r > radius - k) {
              int alpha = (int) (255 - 255 * (r - radius + k) / k);
              if (alpha < 0) alpha = 0;
              if (alpha > 255) alpha = 255;
              row[x] = row[x] & 0xffffff + (alpha << 24);
            }
          } else {
            row[x] = 0x00000000;
          }
        }
        image.getRaster().setDataElements(0, y, size, 1, row);
      }
    } else if (mode == ColorPicker.HUE) {
      float hue2 = this.hue;
      for (int y = 0; y < size; y++) {
        float y2 = ((float) y) / ((float) size);
        for (int x = 0; x < size; x++) {
          float x2 = ((float) x) / ((float) size);
          row[x] = Color.HSBtoRGB(hue2, x2, y2);
        }
        image.getRaster().setDataElements(0, y, image.getWidth(), 1, row);
      }
    } else { // mode is RED, GREEN, or BLUE
      int red2 = red;
      int green2 = green;
      int blue2 = blue;
      for (int y = 0; y < size; y++) {
        float y2 = ((float) y) / ((float) size);
        for (int x = 0; x < size; x++) {
          float x2 = ((float) x) / ((float) size);
          if (mode == ColorPicker.RED) {
            green2 = (int) (x2 * 255 + .49);
            blue2 = (int) (y2 * 255 + .49);
          } else if (mode == ColorPicker.GREEN) {
            red2 = (int) (x2 * 255 + .49);
            blue2 = (int) (y2 * 255 + .49);
          } else {
            red2 = (int) (x2 * 255 + .49);
            green2 = (int) (y2 * 255 + .49);
          }
          row[x] = 0xFF000000 + (red2 << 16) + (green2 << 8) + blue2;
        }
        image.getRaster().setDataElements(0, y, size, 1, row);
      }
    }
    repaint();
  }
예제 #22
0
파일: LJ3MDApp.java 프로젝트: eskilj/mvp
 public double getStd() {
   return Math.sqrt(getVar());
 }
예제 #23
0
/*
  @Override
  public void run() {
    amIActive = true;

    String shapefile = null;
    String inputFieldsString = null;
    String[] fieldNames = null;
    double z;
    int numFields;
    int progress = 0;
    int lastProgress = 0;
    int row;
    int a, i, j;
    double[] fieldAverages;
    double[] fieldTotals;
    boolean standardizedPCA = false;
    int numberOfComponentsOutput = 0;

    if (args.length <= 0) {
      showFeedback("Plugin parameters have not been set.");
      return;
    }

    // read the input parameters

    inputFieldsString = args[0];
    standardizedPCA = Boolean.parseBoolean(args[1]);
    if (args[2].toLowerCase().contains("not")) { // not specified
      numberOfComponentsOutput = 0;
    } else {
      numberOfComponentsOutput = Integer.parseInt(args[2]);
    }

    try {
      // deal with the input fields
      String[] inputs = inputFieldsString.split(";");
      shapefile = inputs[0];
      numFields = inputs.length - 1;
      fieldNames = new String[numFields];
      System.arraycopy(inputs, 1, fieldNames, 0, numFields);

      // read the appropriate field from the dbf file into an array
      AttributeTable table = new AttributeTable(shapefile.replace(".shp", ".dbf"));
      int numRecs = table.getNumberOfRecords();
      DBFField[] fields = table.getAllFields();
      ArrayList<Integer> PCAFields = new ArrayList<>();
      for (j = 0; j < fieldNames.length; j++) {
        for (i = 0; i < fields.length; i++) {
          if (fields[i].getName().equals(fieldNames[j])
              && (fields[i].getDataType() == DBFField.DBFDataType.NUMERIC
                  || fields[i].getDataType() == DBFField.DBFDataType.FLOAT)) {
            PCAFields.add(i);
          }
        }
      }

      if (numFields != PCAFields.size()) {
        showFeedback(
            "Not all of the specified database fields were found in the file or "
                + "a field of a non-numerical type was selected.");
        return;
      }

      double[][] fieldArray = new double[numRecs][numFields];
      Object[] rec;
      for (i = 0; i < numRecs; i++) {
        rec = table.getRecord(i);
        for (j = 0; j < numFields; j++) {
          fieldArray[i][j] = (Double) (rec[PCAFields.get(j)]);
        }
        if (cancelOp) {
          cancelOperation();
          return;
        }
        progress = (int) (100f * i / (numRecs - 1));
        if (progress != lastProgress) {
          updateProgress("Reading data:", progress);
        }
        lastProgress = progress;
      }

      fieldAverages = new double[numFields];
      fieldTotals = new double[numFields];

      // Calculate the means
      for (row = 0; row < numRecs; row++) {
        for (i = 0; i < numFields; i++) {
          fieldTotals[i] += fieldArray[row][i];
        }
      }

      for (i = 0; i < numFields; i++) {
        fieldAverages[i] = fieldTotals[i] / numRecs;
      }

      // Calculate the covariance matrix and total deviations
      double[] fieldTotalDeviation = new double[numFields];
      double[][] covariances = new double[numFields][numFields];
      double[][] correlationMatrix = new double[numFields][numFields];

      for (row = 0; row < numRecs; row++) {
        for (i = 0; i < numFields; i++) {
          fieldTotalDeviation[i] +=
              (fieldArray[row][i] - fieldAverages[i]) * (fieldArray[row][i] - fieldAverages[i]);
          for (a = 0; a < numFields; a++) {
            covariances[i][a] +=
                (fieldArray[row][i] - fieldAverages[i]) * (fieldArray[row][a] - fieldAverages[a]);
          }
        }
        if (cancelOp) {
          cancelOperation();
          return;
        }
        progress = (int) (100f * row / (numRecs - 1));
        if (progress != lastProgress) {
          updateProgress("Calculating covariances:", progress);
        }
        lastProgress = progress;
      }

      for (i = 0; i < numFields; i++) {
        for (a = 0; a < numFields; a++) {
          correlationMatrix[i][a] =
              covariances[i][a] / (Math.sqrt(fieldTotalDeviation[i] * fieldTotalDeviation[a]));
        }
      }

      for (i = 0; i < numFields; i++) {
        for (a = 0; a < numFields; a++) {
          covariances[i][a] = covariances[i][a] / (numRecs - 1);
        }
      }

      // Calculate the eigenvalues and eigenvectors
      Matrix cov = null;
      if (!standardizedPCA) {
        cov = new Matrix(covariances);
      } else {
        cov = new Matrix(correlationMatrix);
      }
      EigenvalueDecomposition eigen = cov.eig();
      double[] eigenvalues;
      Matrix eigenvectors;
      SortedSet<PrincipalComponent> principalComponents;
      eigenvalues = eigen.getRealEigenvalues();
      eigenvectors = eigen.getV();

      double[][] vecs = eigenvectors.getArray();
      int numComponents = eigenvectors.getColumnDimension(); // same as num rows.
      principalComponents = new TreeSet<PrincipalComponent>();
      for (i = 0; i < numComponents; i++) {
        double[] eigenvector = new double[numComponents];
        for (j = 0; j < numComponents; j++) {
          eigenvector[j] = vecs[j][i];
        }
        principalComponents.add(new PrincipalComponent(eigenvalues[i], eigenvector));
      }

      double totalEigenvalue = 0;
      for (i = 0; i < numComponents; i++) {
        totalEigenvalue += eigenvalues[i];
      }

      double[][] explainedVarianceArray = new double[numComponents][2]; // percent and cum. percent
      j = 0;
      for (PrincipalComponent pc : principalComponents) {
        explainedVarianceArray[j][0] = pc.eigenValue / totalEigenvalue * 100.0;
        if (j == 0) {
          explainedVarianceArray[j][1] = explainedVarianceArray[j][0];
        } else {
          explainedVarianceArray[j][1] =
              explainedVarianceArray[j][0] + explainedVarianceArray[j - 1][1];
        }
        j++;
      }

      DecimalFormat df1 = new DecimalFormat("0.00");
      DecimalFormat df2 = new DecimalFormat("0.0000");
      DecimalFormat df3 = new DecimalFormat("0.000000");
      DecimalFormat df4 = new DecimalFormat("0.000");
      String ret = "Principal Component Analysis Report:\n\n";
      ret += "Component\tExplained Var.\tCum. %\tEigenvalue\tEigenvector\n";
      j = 0;
      for (PrincipalComponent pc : principalComponents) {

        String explainedVariance = df1.format(explainedVarianceArray[j][0]);
        String explainedCumVariance = df1.format(explainedVarianceArray[j][1]);
        double[] eigenvector = pc.eigenVector.clone();
        ret +=
            (j + 1)
                + "\t"
                + explainedVariance
                + "\t"
                + explainedCumVariance
                + "\t"
                + df2.format(pc.eigenValue)
                + "\t";
        String eigenvec = "[";
        for (i = 0; i < numComponents; i++) {
          if (i < numComponents - 1) {
            eigenvec += df3.format(eigenvector[i]) + ", ";
          } else {
            eigenvec += df3.format(eigenvector[i]);
          }
        }
        eigenvec += "]";
        ret += eigenvec + "\n";

        if (j < numberOfComponentsOutput) {
          DBFField field = new DBFField();
          field = new DBFField();
          field.setName("COMP" + (j + 1));
          field.setDataType(DBFField.DBFDataType.NUMERIC);
          field.setFieldLength(10);
          field.setDecimalCount(4);
          table.addField(field);

          for (row = 0; row < numRecs; row++) {
            z = 0;
            for (i = 0; i < numFields; i++) {
              z += fieldArray[row][i] * eigenvector[i];
            }

            Object[] recData = table.getRecord(row);
            recData[recData.length - 1] = new Double(z);
            table.updateRecord(row, recData);

            if (cancelOp) {
              cancelOperation();
              return;
            }
            progress = (int) (100f * row / (numRecs - 1));
            if (progress != lastProgress) {
              updateProgress("Outputing Component " + (j + 1) + ":", progress);
            }
            lastProgress = progress;
          }
        }
        j++;
      }

      // calculate the factor loadings.
      ret += "\nFactor Loadings:\n";
      ret += "\t\tComponent\n\t";
      for (i = 0; i < numComponents; i++) {
        ret += (i + 1) + "\t";
      }
      ret += "\n";
      double loading = 0;
      if (!standardizedPCA) {
        for (i = 0; i < numFields; i++) {
          ret += "field " + (i + 1) + "\t";
          for (PrincipalComponent pc : principalComponents) {
            double[] eigenvector = pc.eigenVector.clone();
            double ev = pc.eigenValue;
            loading = (eigenvector[i] * Math.sqrt(ev)) / Math.sqrt(covariances[i][i]);
            ret += df4.format(loading) + "\t";
          }
          ret += "\n";
        }
      } else {
        for (i = 0; i < numFields; i++) {
          ret += "field " + (i + 1) + "\t";
          for (PrincipalComponent pc : principalComponents) {
            double[] eigenvector = pc.eigenVector.clone();
            double ev = pc.eigenValue;
            loading = (eigenvector[i] * Math.sqrt(ev));
            ret += df4.format(loading) + "\t";
          }
          ret += "\n";
        }
      }

      ret += "\n";
      for (i = 0; i < numFields; i++) {
        ret += "field " + (i + 1) + "\t" + fieldNames[i] + "\n";
      }

      returnData(ret);

      if (numberOfComponentsOutput > 0) {
        returnData(table.getFileName());
      }

      ScreePlot plot = new ScreePlot(explainedVarianceArray);
      returnData(plot);

    } catch (OutOfMemoryError oe) {
      myHost.showFeedback("An out-of-memory error has occurred during operation.");
    } catch (Exception e) {
      myHost.showFeedback("An error has occurred during operation. See log file for details.");
      myHost.logException("Error in " + getDescriptiveName(), e);
    } finally {
      updateProgress("Progress: ", 0);
      // tells the main application that this process is completed.
      amIActive = false;
      myHost.pluginComplete();
    }
  }
  /*.................................................................................................................*/
  public Object doCommand(String commandName, String arguments, CommandChecker checker) {
    Tree trt = treeDisplay.getTree();
    MesquiteTree t = null;
    if (trt instanceof MesquiteTree) t = (MesquiteTree) trt;
    if (checker.compare(
        this.getClass(),
        "Adjust tool has touched branch",
        "[branch number][x coordinate touched][y coordinate touched][modifiers]",
        commandName,
        "touchedPositionAdjust")) {
      if (t == null) return null;
      MesquiteInteger io = new MesquiteInteger(0);
      int node = MesquiteInteger.fromString(arguments, io);
      int x = MesquiteInteger.fromString(arguments, io);
      int y = MesquiteInteger.fromString(arguments, io);
      String mod = ParseUtil.getRemaining(arguments, io);

      Point newOnLine = treeDisplay.getTreeDrawing().projectionOnLine(node, x, y);
      originalX = newOnLine.x;
      originalY = newOnLine.y;
      // lastX= newOnLine.x;
      // lastY = newOnLine.y;
      Graphics g = null;
      if (GraphicsUtil.useXORMode(null, false)) {
        g = treeDisplay.getGraphics();
        g.setXORMode(Color.white);
        g.setColor(Color.red);
      }
      // double bX = treeDisplay.getTreeDrawing().lineBaseX[node];
      // double bY = treeDisplay.getTreeDrawing().lineBaseY[node];
      // Math.sqrt((originalY-bY)*(originalY-bY) + (originalX-bX)*(originalX-bX));
      lastBL = tree.getBranchLength(node);
      double shortestAbove = MesquiteDouble.unassigned;
      for (int daughter = t.firstDaughterOfNode(node);
          t.nodeExists(daughter);
          daughter = t.nextSisterOfNode(daughter))
        shortestAbove = MesquiteDouble.minimum(shortestAbove, tree.getBranchLength(daughter));
      if (shortestAbove == MesquiteDouble.unassigned) upperLimit = MesquiteDouble.infinite;
      else if (MesquiteDouble.isCombinable(lastBL)) upperLimit = shortestAbove + lastBL;
      else upperLimit = shortestAbove + 1.0;
      int ibX = treeDisplay.getTreeDrawing().lineBaseX[node];
      int ibY = treeDisplay.getTreeDrawing().lineBaseY[node];
      lastX = treeDisplay.getTreeDrawing().lineTipX[node];
      lastY = treeDisplay.getTreeDrawing().lineTipY[node];
      if (GraphicsUtil.useXORMode(null, false)) {
        drawThickLine(g, ibX, ibY, lastX, lastY);
        for (int daughter = t.firstDaughterOfNode(node);
            t.nodeExists(daughter);
            daughter = t.nextSisterOfNode(daughter))
          drawThickLine(
              g,
              treeDisplay.getTreeDrawing().lineTipX[daughter],
              treeDisplay.getTreeDrawing().lineTipY[daughter],
              lastX,
              lastY);
        g.fillOval(
            lastX - ovalRadius,
            lastY - ovalRadius,
            ovalRadius + ovalRadius,
            ovalRadius + ovalRadius);
        try {
          g.drawString(MesquiteDouble.toString(lastBL), lastX + 10, lastY);
        } catch (InternalError e) { // workaround for bug on windows java 1.7.
        } catch (Throwable e) {
        }
        lineOn = true;
        g.dispose();
      }
    } else if (checker.compare(
        this.getClass(),
        "Adjust tool has been dropped",
        "[branch number][x coordinate dropped][y coordinate dropped]",
        commandName,
        "droppedPositionAdjust")) {
      if (t == null) return null;
      if (editorOn) return null;
      MesquiteInteger io = new MesquiteInteger(0);
      int node = MesquiteInteger.fromString(arguments, io);
      int x = MesquiteInteger.fromString(arguments, io);
      int y = MesquiteInteger.fromString(arguments, io);
      if (lineOn) {
        Point newOnLine = treeDisplay.getTreeDrawing().projectionOnLine(node, x, y);
        double bX = treeDisplay.getTreeDrawing().lineBaseX[node];
        double bY = treeDisplay.getTreeDrawing().lineBaseY[node];
        double tX = treeDisplay.getTreeDrawing().lineTipX[node];
        double tY = treeDisplay.getTreeDrawing().lineTipY[node];
        double lengthLine =
            Math.sqrt((originalY - bY) * (originalY - bY) + (originalX - bX) * (originalX - bX));
        double bL;
        if (lengthLine != 0) {
          double extension =
              Math.sqrt(
                      (newOnLine.y - bY) * (newOnLine.y - bY)
                          + (newOnLine.x - bX) * (newOnLine.x - bX))
                  / lengthLine;
          if (t.getBranchLength(node) == 0 || t.branchLengthUnassigned(node)) bL = extension;
          else bL = t.getBranchLength(node) * extension;
        } else bL = 1;

        if (bL > upperLimit) bL = upperLimit;
        else if (bL < lowerLimit) bL = lowerLimit;
        double oldBL = t.getBranchLength(node);
        if (!MesquiteDouble.isCombinable(oldBL)) oldBL = 1.0;
        t.setBranchLength(node, bL, false);
        double difference = oldBL - t.getBranchLength(node);
        for (int daughter = t.firstDaughterOfNode(node);
            t.nodeExists(daughter);
            daughter = t.nextSisterOfNode(daughter))
          if (MesquiteDouble.isCombinable(t.getBranchLength(daughter)))
            t.setBranchLength(daughter, t.getBranchLength(daughter) + difference, false);
        t.notifyListeners(this, new Notification(MesquiteListener.BRANCHLENGTHS_CHANGED));
        Graphics g = treeDisplay.getGraphics();
        g.setPaintMode();
        g.dispose();
        treeDisplay.pleaseUpdate(true);
        lineOn = false;
      }
    } else if (checker.compare(
        this.getClass(),
        "Adjust tool is being dragged",
        "[branch number][x coordinate][y coordinate]",
        commandName,
        "draggedPositionAdjust")) {
      if (t == null) return null;
      if (editorOn) return null;
      MesquiteInteger io = new MesquiteInteger(0);
      int node = MesquiteInteger.fromString(arguments, io);
      int x = MesquiteInteger.fromString(arguments, io);
      int y = MesquiteInteger.fromString(arguments, io);
      if (lineOn) {
        Point newOnLine = treeDisplay.getTreeDrawing().projectionOnLine(node, x, y);
        // WARNING":  This shouldn't result in length increase if simple click and release with no
        // drag; must subtract original X, Y
        Graphics g = null;
        if (GraphicsUtil.useXORMode(null, false)) {
          g = treeDisplay.getGraphics();
          g.setXORMode(Color.white);
          g.setColor(Color.red);
        }
        // g.fillOval(lastX-ovalRadius, lastY-ovalRadius, ovalRadius + ovalRadius, ovalRadius +
        // ovalRadius);
        // g.fillOval(newOnLine.x-ovalRadius, newOnLine.y -ovalRadius, ovalRadius + ovalRadius,
        // ovalRadius + ovalRadius);

        // g.drawLine(originalX, originalY, lastX, lastY);
        // g.drawLine(originalX, originalY, newOnLine.x, newOnLine.y);

        //				if decreasing, & unassigned involved: push unassigned down and assign values to
        // unassigned above; if increasing, push unassigne up
        int ibX = treeDisplay.getTreeDrawing().lineBaseX[node];
        int ibY = treeDisplay.getTreeDrawing().lineBaseY[node];
        int itX = treeDisplay.getTreeDrawing().lineTipX[node];
        int itY = treeDisplay.getTreeDrawing().lineTipY[node];

        double bX = ibX;
        double bY = ibY;
        double tX = itX;
        double tY = itY;
        double lengthLine =
            Math.sqrt((originalY - bY) * (originalY - bY) + (originalX - bX) * (originalX - bX));
        if (lengthLine != 0) {
          if (GraphicsUtil.useXORMode(null, false)) {
            if (MesquiteTrunk.isMacOSX()
                && MesquiteTrunk.getJavaVersionAsDouble() >= 1.5
                && MesquiteTrunk.getJavaVersionAsDouble() < 1.6) // due to a JVM bug
            g.fillRect(lastX, lastY - 20, 100, 20);
            g.drawString(MesquiteDouble.toString(lastBL), lastX + 10, lastY);
            if (MesquiteTrunk.isMacOSX()
                && MesquiteTrunk.getJavaVersionAsDouble() >= 1.5
                && MesquiteTrunk.getJavaVersionAsDouble() < 1.6) // due to a JVM bug
            g.fillRect(lastX, lastY - 20, 100, 20);
          }
          double extension =
              Math.sqrt(
                      (newOnLine.y - bY) * (newOnLine.y - bY)
                          + (newOnLine.x - bX) * (newOnLine.x - bX))
                  / lengthLine;
          double bL;
          if (t.getBranchLength(node) == 0 || t.branchLengthUnassigned(node)) bL = extension;
          else bL = t.getBranchLength(node) * extension;
          if (bL > upperLimit) {
            bL = upperLimit;
            if (t.getBranchLength(node) == 0 || t.branchLengthUnassigned(node))
              extension = upperLimit;
            else extension = upperLimit / t.getBranchLength(node);
          } else if (bL < lowerLimit) {
            bL = lowerLimit;
            if (t.getBranchLength(node) == 0 || t.branchLengthUnassigned(node))
              extension = lowerLimit;
            else extension = lowerLimit / t.getBranchLength(node);
          }
          lastBL = bL;
          if (GraphicsUtil.useXORMode(null, false)) {
            drawThickLine(g, ibX, ibY, lastX, lastY);
            for (int daughter = t.firstDaughterOfNode(node);
                t.nodeExists(daughter);
                daughter = t.nextSisterOfNode(daughter))
              drawThickLine(
                  g,
                  treeDisplay.getTreeDrawing().lineTipX[daughter],
                  treeDisplay.getTreeDrawing().lineTipY[daughter],
                  lastX,
                  lastY);
            g.fillOval(
                lastX - ovalRadius,
                lastY - ovalRadius,
                ovalRadius + ovalRadius,
                ovalRadius + ovalRadius);
          }
          int newX = ibX + (int) (extension * (tX - bX));
          int newY = ibY + (int) (extension * (tY - bY));
          if (GraphicsUtil.useXORMode(null, false)) {
            g.drawString(MesquiteDouble.toString(bL), newX + 10, newY);
            drawThickLine(g, ibX, ibY, newX, newY);
            for (int daughter = t.firstDaughterOfNode(node);
                t.nodeExists(daughter);
                daughter = t.nextSisterOfNode(daughter))
              drawThickLine(
                  g,
                  treeDisplay.getTreeDrawing().lineTipX[daughter],
                  treeDisplay.getTreeDrawing().lineTipY[daughter],
                  newX,
                  newY);
            g.fillOval(
                newX - ovalRadius,
                newY - ovalRadius,
                ovalRadius + ovalRadius,
                ovalRadius + ovalRadius);
          }
          lastX = newX;
          lastY = newY;
        }

        // lastX= newOnLine.x;
        // lastY = newOnLine.y;
      }
    }
    return null;
  }
예제 #26
0
 private float distance(float a, float b) {
   return (float) Math.sqrt(a * a + b * b);
 }
예제 #27
0
  /**
   * Applies a gaussian blur filter to the given image. Apart from the filter radius, you can also
   * specify an alpha factor which will be multiplied with the filter's result. Also, you can
   * specify whether the blurred image should be rendered into a newly created BufferedImage
   * instance or into the original image. If you request a new image instance, the result will be
   * larger than the original one as a (2*filterradius) pixel wide padding will be applied.
   *
   * @param image the image to be blurred.
   * @param filterRadius the radius of the gaussian filter to apply. The corresponding kernel will
   *     be sized 2 * filterRadius + 1;
   * @param alphaFactor a factor which will be multiplied with the filtered image. You can use this
   *     parameter to weaken or strengthen the colors in the blurred image.
   * @param useOriginalImageAsDestination Determines whether the blur result should be rendered into
   *     the original image or into a new image instance. If you choose to create a new image
   *     instance, the result will be larger than the original image to provide the required padding
   *     for the blur effect.
   * @return An image instance containing a blurred version of the given image.
   */
  public static BufferedImage applyGaussianBlur(
      final BufferedImage image,
      final int filterRadius,
      final float alphaFactor,
      final boolean useOriginalImageAsDestination) {
    if (filterRadius < 1) {
      throw new IllegalArgumentException(
          "Illegal filter radius: expected to be >= 1, was " + filterRadius);
    }

    float[] kernel = new float[2 * filterRadius + 1];

    final float sigma = filterRadius / 3f;
    final float alpha = 2f * sigma * sigma;
    final float rootAlphaPI = (float) Math.sqrt(alpha * Math.PI);
    float sum = 0;
    for (int i = -0; i < kernel.length; i++) {
      final int d = -((i - filterRadius) * (i - filterRadius));
      kernel[i] = (float) (Math.exp(d / alpha) / rootAlphaPI);
      sum += kernel[i];
    }

    for (int i = 0; i < kernel.length; i++) {
      kernel[i] /= sum;
      kernel[i] *= alphaFactor;
    }

    final Kernel horizontalKernel = new Kernel(kernel.length, 1, kernel);
    final Kernel verticalKernel = new Kernel(1, kernel.length, kernel);

    synchronized (BlurUtils.class) {
      final int blurredWidth =
          useOriginalImageAsDestination ? image.getWidth() : image.getWidth() + 4 * filterRadius;
      final int blurredHeight =
          useOriginalImageAsDestination ? image.getHeight() : image.getHeight() + 4 * filterRadius;

      final BufferedImage img0 = ensureBuffer0Capacity(blurredWidth, blurredHeight);
      final Graphics2D graphics0 = img0.createGraphics();
      graphics0.drawImage(
          image,
          null,
          useOriginalImageAsDestination ? 0 : 2 * filterRadius,
          useOriginalImageAsDestination ? 0 : 2 * filterRadius);
      graphics0.dispose();

      final BufferedImage img1 = ensureBuffer1Capacity(blurredWidth, blurredHeight);
      final Graphics2D graphics1 = img1.createGraphics();
      graphics1.drawImage(
          img0, new ConvolveOp(horizontalKernel, ConvolveOp.EDGE_NO_OP, null), 0, 0);
      graphics1.dispose();

      BufferedImage destination =
          useOriginalImageAsDestination
              ? image
              : new BufferedImage(blurredWidth, blurredHeight, BufferedImage.TYPE_INT_ARGB);
      final Graphics2D destGraphics = destination.createGraphics();
      destGraphics.drawImage(
          img1, new ConvolveOp(verticalKernel, ConvolveOp.EDGE_NO_OP, null), 0, 0);
      destGraphics.dispose();

      return destination;
    }
  }