コード例 #1
0
ファイル: ChestImageViewer.java プロジェクト: kullen/MRI
 /**
  * The method to invoke the application.
  *
  * @param arg a list of DICOM files which may contain chest x-ray images
  */
 public static void main(String arg[]) {
   try {
     new ChestImageViewer(arg);
   } catch (Exception e) {
     e.printStackTrace(System.err);
   }
 }
コード例 #2
0
ファイル: Spaceship.java プロジェクト: LukeJHarvey/SpaceShip
  public void run() {
    try {
      AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
      AudioFormat format = ais.getFormat();
      //    System.out.println("Format: " + format);
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
      SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
      source.open(format);
      source.start();
      int read = 0;
      byte[] audioData = new byte[16384];
      while (read > -1) {
        read = ais.read(audioData, 0, audioData.length);
        if (read >= 0) {
          source.write(audioData, 0, read);
        }
      }
      donePlaying = true;

      source.drain();
      source.close();
    } catch (Exception exc) {
      System.out.println("error: " + exc.getMessage());
      exc.printStackTrace();
    }
  }
コード例 #3
0
ファイル: JopButtonset.java プロジェクト: jordibrus/proview
 public JopButtonset() {
   try {
     jbInit();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #4
0
 public JopFrameroundcorners() {
   try {
     jbInit();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #5
0
ファイル: UBoardGraphPanel.java プロジェクト: sejii/sysmode
 public UBoardGraphPanel() {
   fName = fRb.getString("ORDER_BOOK");
   try {
     jbInit();
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
コード例 #6
0
 public DisplayImage16() {
   super();
   try {
     jbInit();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #7
0
ファイル: CSpace.java プロジェクト: nforrester/6.141_labs
 public static void tests() {
   System.err.println("HEY!");
   Mat p0 = Mat.encodePoint(0, 0);
   Mat p1 = Mat.encodePoint(1, .1);
   Mat p2 = Mat.encodePoint(.1, 1);
   Mat p3 = Mat.encodePoint(-1, -.1);
   Mat p4 = Mat.encodePoint(-.1, -1);
   Mat p5 = Mat.encodePoint(0.0001, 0);
   Mat p6 = Mat.encodePoint(-0.0001, 0);
   if (!lineSegIntersect(p1, p3, p2, p4)) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
   if (lineSegIntersect(p1, p4, p2, p3)) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
   if (lineSegIntersect(p1, p5, p2, p4)) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
   if (!lineSegIntersect(p1, p6, p2, p4)) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
   Mat inter = lineSegIntersection(p1, p3, p2, p4);
   if (inter.data[0][0] != 0 || inter.data[1][0] != 0) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
 }
コード例 #8
0
 /**
  * Method to write the contents of the picture to a file with the passed name without throwing
  * errors
  *
  * @param fileName the name of the file to write the picture to
  * @return true if success else false
  */
 public boolean write(String fileName) {
   try {
     this.writeOrFail(fileName);
     return true;
   } catch (Exception ex) {
     System.out.println("There was an error trying to write " + fileName);
     ex.printStackTrace();
     return false;
   }
 }
コード例 #9
0
ファイル: NimRODUtils.java プロジェクト: ATRM/publicMain
 static ImageIcon loadRes(String fich) {
   try {
     return new ImageIcon(
         Toolkit.getDefaultToolkit()
             .createImage(readStream(NimRODLookAndFeel.class.getResourceAsStream(fich))));
   } catch (Exception ex) {
     ex.printStackTrace();
     System.out.println("No se puede cargar el recurso " + fich);
     return null;
   }
 }
コード例 #10
0
ファイル: RotatePanel.java プロジェクト: freeocs/dlog4j
 public RotatePanel(Image image) {
   this.image = image;
   MediaTracker mt = new MediaTracker(this);
   mt.addImage(image, 0);
   try {
     mt.waitForID(0);
   }
   catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #11
0
ファイル: JCanvas.java プロジェクト: xaleth09/Connect4-AI
 /** print the canvas scaled with factor <code>scale</code> */
 public void print(double scale) {
   printScale = scale;
   PrinterJob printJob = PrinterJob.getPrinterJob();
   printJob.setPrintable(this);
   if (printJob.printDialog()) {
     try {
       printJob.print();
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }
コード例 #12
0
ファイル: Vision.java プロジェクト: dmendelsohn/6.141
  public void handleImage() {
    while (true) {
      Image src = null;
      try {
        src = new Image(visionImage.take(), width, height);
      } catch (InterruptedException e) {
        e.printStackTrace();
        continue;
      }

      // Apply Blob Track to Image
      Image dest = new Image(src);
      blobTrack.apply(src, dest);

      OdometryMsg msg = new OdometryMsg();

      if (LOCALIZE && System.currentTimeMillis() - last_localization > LOCALIZATION_INTERVAL) {
        ResetMsg stop_msg = new ResetMsg();
        stop_msg.reset = false;
        stopPub.publish(stop_msg);

        Point2D.Double curr_point;
        synchronized (localization) {
          curr_point = localization.localize(odo_x, odo_y, blobTrack.fiducials);
        }
        msg.x = curr_point.x;
        msg.y = curr_point.y;

        last_localization = System.currentTimeMillis();
      } else {
        msg.x = odo_x;
        msg.y = odo_y;
      }
      msg.theta = odo_theta;
      localPub.publish(msg);

      // Update newly formed vision message
      gui.setVisionImage(dest.toArray(), width, height);

      try {
        Thread.sleep(1000);
      } catch (Exception exc) {
        exc.printStackTrace();
      }

      ResetMsg stop_msg = new ResetMsg();
      stop_msg.reset = true;
      stopPub.publish(stop_msg);
    }
  }
コード例 #13
0
 public void stateChanged(ChangeEvent e) {
   TimeStampedValue last;
   try {
     last = inspector.getLastValue(fieldname);
   } catch (Exception f) {
     f.printStackTrace();
     return;
   }
   if (last != null) {
     double tmpx, tmpy;
     tmpx = last.getTime() - start;
     tmpy = Double.parseDouble(last.getValue().toString());
     this.view.addPoint(tmpx, tmpy);
   }
 }
コード例 #14
0
ファイル: IAppletGL2.java プロジェクト: JaredHalpern/iGeo
  public void run() {
    try {
      while (running) {

        try {
          Thread.sleep(framerate);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        repaint();
        updateObjects();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #15
0
ファイル: PlanRenderer.java プロジェクト: escalope/IDK
  static {
    try {

      ViewPreferences.ViewType index = ViewPreferences.ViewType.INGENIAS;
      index = ViewPreferences.ViewType.INGENIAS;

      index = ViewPreferences.ViewType.UML;
      RenderComponentManager.loadRenderFile("Plan", index, "/rendererxml/PlanUMLPanel.xml");

      index = ViewPreferences.ViewType.INGENIAS;
      RenderComponentManager.loadRenderFile("Plan", index, "/rendererxml/PlanINGENIASPanel.xml");

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #16
0
  private BufferWrapperRaster readTileRaster(MeshTile tile) {
    File file = new File(this.dataDescriptor.getFileStoreLocation(), tile.getPath());
    if (!file.exists()) return null;

    DataSource source = new BasicDataSource(file);
    source.setValue(AVKey.SECTOR, tile.getSector());

    BILRasterReader reader = new BILRasterReader();
    DataRaster[] rasters;
    try {
      rasters = reader.read(source);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

    return (BufferWrapperRaster) rasters[0];
  }
コード例 #17
0
  /** used for cut and paste. */
  public void addObjectFromClipboard(String a_value) throws CircularIncludeException {
    Reader reader = new StringReader(a_value);
    Document document = null;
    try {
      document = UJAXP.getDocument(reader);
    } catch (Exception e) {
      e.printStackTrace();
      return;
    } // try-catch

    Element root = document.getDocumentElement();
    if (!root.getNodeName().equals("clipboard")) {
      return;
    } // if

    Node child;
    for (child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
      if (!(child instanceof Element)) {
        continue;
      } // if
      Element element = (Element) child;

      IGlyphFactory factory = GlyphFactory.getFactory();

      if (XModule.isMatch(element)) {
        EModuleInvoke module = (EModuleInvoke) factory.createXModule(element);
        addModule(module);
        continue;
      } // if

      if (XContour.isMatch(element)) {
        EContour contour = (EContour) factory.createXContour(element);
        addContour(contour);
        continue;
      } // if

      if (XInclude.isMatch(element)) {
        EIncludeInvoke include = (EIncludeInvoke) factory.createXInclude(element);
        addInclude(include);
        continue;
      } // if
    } // while
  }
コード例 #18
0
ファイル: ClientMediator.java プロジェクト: zTrix/TankMania
 public void toberun() {
   if (_writer == null || _reader == null) {
     Logger.error("@ClientMediator.toberun: _writer or _reader null");
     return;
   }
   String s;
   while (true) {
     s = null;
     try {
       s = _reader.readLine();
     } catch (Exception e) {
       Logger.error("@ClientMediator.toberun: _read error, excep is " + e.toString());
       break;
     }
     if (s != null && s.length() > 0) {
       handleResquest(new String(s));
     }
   }
   Arena.addReq(_id, Const.LOSE_CONNECTION, null);
 }
コード例 #19
0
ファイル: WFConnectsRenderer.java プロジェクト: escalope/IDK
  static {
    try {

      ViewPreferences.ViewType index = ViewPreferences.ViewType.INGENIAS;
      index = ViewPreferences.ViewType.INGENIAS;

      index = ViewPreferences.ViewType.NOICON;
      RenderComponentManager.loadRenderFile(
          "WFConnects", index, "/rendererxml/WFConnectsNOICONPanel.xml");

      index = ViewPreferences.ViewType.INGENIAS;
      RenderComponentManager.loadRenderFile(
          "WFConnects", index, "/rendererxml/WFConnectsINGENIASPanel.xml");

      index = ViewPreferences.ViewType.LABEL;
      RenderComponentManager.loadRenderFile(
          "WFConnects", index, "/rendererxml/WFConnectsLABELPanel.xml");

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #20
0
  /**
   * PS see http://astronomy.swin.edu.au/~pbourke/geomformats/postscript/ Java
   * http://show.docjava.com:8086/book/cgij/doc/ip/graphics/SimpleImageFrame.java.html
   */
  public boolean drawImage(
      Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) {
    try {
      // get data from image
      int[] pixels = new int[width * height];
      PixelGrabber grabber = new PixelGrabber(img, 0, 0, width, height, pixels, 0, width);
      grabber.grabPixels();
      ColorModel model = ColorModel.getRGBdefault();

      // print data to ps
      m_printstream.println("gsave");
      m_printstream.println(
          xTransform(xScale(x)) + " " + (yTransform(yScale(y)) - yScale(height)) + " translate");
      m_printstream.println(xScale(width) + " " + yScale(height) + " scale");
      m_printstream.println(
          width + " " + height + " " + "8" + " [" + width + " 0 0 " + (-height) + " 0 " + height
              + "]");
      m_printstream.println("{<");

      int index;
      for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
          index = i * width + j;
          m_printstream.print(toHex(model.getRed(pixels[index])));
          m_printstream.print(toHex(model.getGreen(pixels[index])));
          m_printstream.print(toHex(model.getBlue(pixels[index])));
        }
        m_printstream.println();
      }

      m_printstream.println(">}");
      m_printstream.println("false 3 colorimage");
      m_printstream.println("grestore");
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
コード例 #21
0
  static {
    try {

      ViewPreferences.ViewType index = ViewPreferences.ViewType.INGENIAS;
      index = ViewPreferences.ViewType.INGENIAS;

      index = ViewPreferences.ViewType.UML;
      RenderComponentManager.loadRenderFile(
          "DeploymentUnitByTypeMSEntity",
          index,
          "/ingenias/editor/rendererxml/DeploymentUnitByTypeMSEntityUMLPanel.xml");

      index = ViewPreferences.ViewType.INGENIAS;
      RenderComponentManager.loadRenderFile(
          "DeploymentUnitByTypeMSEntity",
          index,
          "/ingenias/editor/rendererxml/DeploymentUnitByTypeMSEntityINGENIASPanel.xml");

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #22
0
ファイル: MBColorButton.java プロジェクト: rodijolak/calico
  public MBColorButton(long c, Color col, String iconPath, Rectangle2D bounds) {
    super();
    cuid = c;
    color = col;
    iconString = iconPath;
    try {
      // Color curColor = CalicoOptions.getColor("pen.default_color");
      // setImage(CalicoOptions.getColorImage(color));

      if (CalicoDataStore.PenColor.equals(color)
          && (CalicoDataStore.Mode == CInputMode.EXPERT
              || CalicoDataStore.Mode == CInputMode.ARROW)) {
        setSelected(true);
      }

      setImage(CalicoIconManager.getIconImage(iconPath));
      setBounds(bounds);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #23
0
  static {
    try {

      ViewPreferences.ViewType index = ViewPreferences.ViewType.INGENIAS;
      index = ViewPreferences.ViewType.INGENIAS;

      index = ViewPreferences.ViewType.NOICON;
      RenderComponentManager.loadRenderFile(
          "WFResponsable", index, "/ingenias/editor/rendererxml/WFResponsableNOICONPanel.xml");

      index = ViewPreferences.ViewType.INGENIAS;
      RenderComponentManager.loadRenderFile(
          "WFResponsable", index, "/ingenias/editor/rendererxml/WFResponsableINGENIASPanel.xml");

      index = ViewPreferences.ViewType.LABEL;
      RenderComponentManager.loadRenderFile(
          "WFResponsable", index, "/ingenias/editor/rendererxml/WFResponsableLABELPanel.xml");

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #24
0
ファイル: draw.java プロジェクト: bossiernesto/jvmbytecodes
 private StructureType assignStructureType(Element structure) throws VisualizerLoadException {
   String name = structure.getName().toLowerCase();
   if (name.compareTo("graph") == 0) {
     if (structure.getAttributeValue("weighted").compareTo("true") == 0)
       return new Graph_Network("NETWORK");
     else return new Graph_Network("GRAPH");
   } else if (name.equals("array")) return new MD_Array();
   else if (name.equals("no3darray")) return new No3darray();
   else if (name.equals("linkedlist")) return new VisLinkedList();
   else if (name.equals("no3dlinkedlist")) return new No3dLinkedList();
   else if (name.equals("linkedlistnonull")) return new VisLinkedListNoNull();
   else if (name.equals("bargraph")) return new BarScat("BAR");
   else if (name.equals("scattergraph"))
     return new BarScat(
         "SCAT"); // not implemented in xml dtd, and does not have a load-from-xml method defined
   else if (name.equals("stack")) return new Stack();
   else if (name.equals("queue")) return new Queue();
   else if (name.equals("tree")) {
     if (structure.getChild("binary_node") != null) return new BinaryTree();
     else return new GeneralTree();
   } else if (name.equals("text")) return new TextStructure();
   // if the XML element name is different from your structure's name, you can do something like
   // this:
   // 	else if( name.equalsIgnoreCase("node"))
   // 	    return new Node();
   else if (name.equals("legend")) return new LegendofColors();
   else {
     // try dynamic typing
     try {
       return assignStructureType(name);
     } catch (Exception e) {
       throw new VisualizerLoadException(
           "Unable to instantiate class \"" + name + "\":\n" + e.getMessage());
     }
   }
 }
コード例 #25
0
ファイル: draw.java プロジェクト: bossiernesto/jvmbytecodes
  private /*synchronized*/ void readQuestions(StringTokenizer st) throws VisualizerLoadException {
    String tmpStr =
        "STARTQUESTIONS\n"; // When CG's QuestionFactory parses from a string, it looks for
    // a line with STARTQUESTIONS -- hence we add it artificially here
    try { // Build the string for the QuestionFactory
      while (st.hasMoreTokens()) {
        tmpStr += st.nextToken() + "\n";
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new VisualizerLoadException("Ooof!  bad question format");
    }

    try {
      // System.out.println(tmpStr);
      // Problem -- must make this be line oriented
      GaigsAV.questionCollection = QuestionFactory.parseScript(tmpStr);
    } catch (QuestionParseException e) {
      e.printStackTrace();
      System.out.println("Error parsing questions.");
      throw new VisualizerLoadException("Ooof!  bad question format");
      // throw new IOException();
    }
  } // readQuestions(st)
コード例 #26
0
ファイル: ChestImageViewer.java プロジェクト: kullen/MRI
  /**
   * @param filenames
   * @exception Exception if internal error
   */
  public void loadMultiPanelFromSpecifiedFiles(String filenames[]) throws Exception {

    int nFiles = filenames.length;

    SingleImagePanel imagePanels[] = new SingleImagePanel[nFiles];

    String orientations[][] = new String[nFiles][];
    String views[] = new String[nFiles];
    String lateralityViewAndModifiers[] = new String[nFiles];
    String lateralities[] = new String[nFiles];
    int widths[] = new int[nFiles];
    int heights[] = new int[nFiles];
    PixelSpacing spacing[] = new PixelSpacing[nFiles];

    String rowOrientations[] = new String[nFiles];
    String columnOrientations[] = new String[nFiles];

    HashMap eventContexts = new HashMap();

    double maximumHorizontalExtentInMm = 0;
    double maximumVerticalExtentInMm = 0;

    StructuredReport sr[] = new StructuredReport[nFiles];

    int nImages = 0;
    int nCAD = 0;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    for (int f = 0; f < nFiles; ++f) {
      try {
        String filename = filenames[f];
        DicomInputStream distream = null;
        InputStream in = classLoader.getResourceAsStream(filename);
        if (in != null) {
          distream = new DicomInputStream(in);
        } else {
          distream = new DicomInputStream(new File(filename));
        }
        AttributeList list = new AttributeList();
        list.read(distream);
        if (list.isImage()) {
          int i = nImages++;
          System.err.println("IMAGE [" + i + "] is file " + f + " (" + filenames[f] + ")");

          orientations[i] = getPatientOrientation(list);
          // System.err.println("IMAGE ["+i+"] orientation="+(orientations[i] == null &&
          // orientations[i].length == 2 ? "" : (orientations[i][0] + " " + orientations[i][1])));
          views[i] = getView(list);
          // System.err.println("IMAGE ["+i+"] view="+views[i]);
          lateralityViewAndModifiers[i] = getImageLateralityViewModifierAndViewModifier(list);
          // System.err.println("IMAGE ["+i+"]
          // lateralityViewAndModifiers="+lateralityViewAndModifiers[i]);
          // System.err.println("File "+filenames[f]+": "+lateralityViewAndModifiers[i]);
          lateralities[i] = getLaterality(list);
          // System.err.println("IMAGE ["+i+"] laterality="+lateralities[i]);
          spacing[i] = new PixelSpacing(list);
          // System.err.println("IMAGE ["+i+"] spacing="+spacing[i]);

          SourceImage sImg = new SourceImage(list);
          BufferedImage img = sImg.getBufferedImage();

          widths[i] = sImg.getWidth();
          heights[i] = sImg.getHeight();

          boolean shareVOIEventsInStudy =
              false; // does not seem to work anyway, since adding VOITransform to panel constructor
                     // :(

          EventContext eventContext = new EventContext(Integer.toString(i));

          SingleImagePanel imagePanel = makeNewImagePanel(sImg, eventContext);
          imagePanel.setDemographicAndTechniqueAnnotations(
              new DemographicAndTechniqueAnnotations(list),
              "SansSerif",
              Font.PLAIN,
              10,
              Color.pink);
          imagePanel.setOrientationAnnotations(
              new OrientationAnnotations(rowOrientations[i], columnOrientations[i]),
              "SansSerif",
              Font.PLAIN,
              20,
              Color.pink);
          imagePanel.setPixelSpacingInSourceImage(
              spacing[i].getSpacing(), spacing[i].getDescription());
          if (Attribute.getSingleStringValueOrEmptyString(list, TagFromName.VOILUTFunction)
              .equals("SIGMOID")) {
            imagePanel.setVOIFunctionToLogistic();
          }
          imagePanels[i] = imagePanel;
        } else {
          throw new DicomException("Unsupported SOP Class in file " + filenames[f]);
        }
      } catch (Exception e) { // FileNotFoundException,IOException,DicomException
        e.printStackTrace(System.err);
      }
    }

    // int imagesPerRow = nImages;			// i.e., 1 -> 1, 2 -> 1, 4 -> 4, 5 -> 4, 8 -> 4
    // int imagesPerCol = 1;

    int imagesPerRow = nImages >= 8 ? 8 : nImages; // i.e., 1 -> 1, 2 -> 1, 4 -> 4, 5 -> 4, 8 -> 4
    int imagesPerCol =
        (nImages - 1) / imagesPerRow + 1; // i.e., 1 -> 1, 2 -> 2, 4 -> 1, 5 -> 2, 8 -> 2

    int singleWidth = frameWidth / imagesPerRow;
    int singleHeight = frameHeight / imagesPerCol;

    if (nImages == 1 && singleWidth > singleHeight) {
      singleWidth =
          singleWidth / 2; // use only half the screen for a single view and a landscape monitor
    }

    for (int i = 0; i < nImages; ++i) {
      DisplayedAreaSelection displayedAreaSelection = null;
      displayedAreaSelection =
          new DisplayedAreaSelection(
              widths[i],
              heights[i],
              0,
              0,
              widths[i],
              heights[i],
              true, // in case spacing was not supplied
              0,
              0,
              0,
              0,
              0,
              false /*crop*/);
      imagePanels[i].setDisplayedAreaSelection(displayedAreaSelection);
      imagePanels[i].setPreTransformImageRelativeCoordinates(null);
    }

    SingleImagePanel.deconstructAllSingleImagePanelsInContainer(multiPanel);
    multiPanel.removeAll();
    multiPanel.setLayout(new GridLayout(imagesPerCol, imagesPerRow));
    multiPanel.setBackground(Color.black);

    for (int x = 0; x < imagesPerCol; ++x) {
      for (int y = 0; y < imagesPerRow; ++y) {
        int i = x * imagesPerRow + y;
        if (i < nImages) {
          imagePanels[i].setPreferredSize(new Dimension(singleWidth, singleHeight));
          multiPanel.add(imagePanels[i]);
        }
      }
    }
    frame.getContentPane().validate();
    frame.getContentPane().repaint();
  }
コード例 #27
0
ファイル: Vision.java プロジェクト: dmendelsohn/6.141
  @Override
  public void onStart(Node node) {
    ParameterTree paramTree = node.newParameterTree();
    mapFileName = paramTree.getString(node.resolveName("~/mapFileName"));

    last_localization = System.currentTimeMillis();

    try {
      polymap = new PolygonMap(mapFileName);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Point2D.Double robotStart = polymap.getRobotStart();

    Rectangle2D.Double cSpaceWorld =
        CSpace.CSpaceWorldRect(polymap.getWorldRect(), polymap.getRobotStart(), RADIUS);
    List<PolygonObstacle> cSpaceObstacles =
        CSpace.computeCSpace(polymap, getRobot(), polymap.getRobotStart());

    Map<int[], Point2D.Double> fiducialPairs = new HashMap<int[], Point2D.Double>();

    // Finish adding to fiducial pairs here from map

    localization = new Localization(cSpaceObstacles, cSpaceWorld, robotStart, fiducialPairs);

    blobTrack = new BlobTracking(width, height);
    final boolean reverseRGB = node.newParameterTree().getBoolean("reverse_rgb", false);

    localPub = node.newPublisher("/rss/localization", "rss_msgs/OdometryMsg");
    stopPub = node.newPublisher("/rss/stop", "rss_msgs/ResetMsg");

    vidSub = node.newSubscriber("/rss/video", "sensor_msgs/Image");
    vidSub.addMessageListener(
        new MessageListener<org.ros.message.sensor_msgs.Image>() {
          @Override
          public void onNewMessage(org.ros.message.sensor_msgs.Image message) {
            byte[] rgbData;
            if (reverseRGB) {
              rgbData = Image.RGB2BGR(message.data, (int) message.width, (int) message.height);
            } else {
              rgbData = message.data;
            }
            assert ((int) message.width == width);
            assert ((int) message.height == height);
            handle(rgbData);
          }
        });

    depthSub = node.newSubscriber("/rss/depth", "sensor_msgs/Image");
    depthSub.addMessageListener(
        new MessageListener<org.ros.message.sensor_msgs.Image>() {
          @Override
          public void onNewMessage(org.ros.message.sensor_msgs.Image message) {
            byte[] rgbData;
            if (reverseRGB) {
              rgbData = Image.RGB2BGR(message.data, (int) message.width, (int) message.height);
            } else {
              rgbData = message.data;
            }
            assert ((int) message.width == width);
            assert ((int) message.height == height);
            handle(rgbData);
          }
        });

    odoSub = node.newSubscriber("/rss/odometry", "rss_msgs/OdometryMsg");
    odoSub.addMessageListener(
        new MessageListener<org.ros.message.rss_msgs.OdometryMsg>() {
          @Override
          public void onNewMessage(org.ros.message.rss_msgs.OdometryMsg message) {
            odo_x = message.x;
            odo_y = message.y;
            odo_theta = message.theta;

            Point2D.Double curr_point;
            OdometryMsg msg = new OdometryMsg();
            if (LOCALIZE) {
              synchronized (localization) {
                curr_point = localization.encoderUpdate(odo_x, odo_y);
              }
              msg.x = curr_point.x;
              msg.y = curr_point.y;
            } else {
              msg.x = odo_x;
              msg.y = odo_y;
            }
            msg.theta = odo_theta;
            localPub.publish(msg);
          }
        });

    Thread visionThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                handleImage();
                try {
                  Thread.sleep(10);
                } catch (Exception exc) {
                  exc.printStackTrace();
                }
              }
            });
    visionThread.start();
  }
コード例 #28
0
ファイル: CSpace.java プロジェクト: nforrester/6.141_labs
    /*
     * Take a collection of vertices and edges between them,
     * and return the minimum area polygon containing all of them.
     *
     * ArrayList<Mat> vertices = the list of vertices
     *
     * ArrayList<TreeSet<Integer>> edgesTo = To find the edges connecting to a point indexed i in vertices,
     *                                       look in edgesTo.get(i). There you will find a list of indicies
     *                                       into vertices, which are the endpoints of the edges. This data
     *                                       structure is slow to write, but fast to read.
     */
    public static Polygon perimeter(ArrayList<Mat> vertices, ArrayList<TreeSet<Integer>> edgesTo) {
      // Find a point guaranteed to be on the perimeter of the polygon, so we can start tracing it
      // out
      double dist;
      double maxDist = -1;
      int farPoint = -1;
      for (int i = 0; i < vertices.size(); i++) {
        dist =
            Math.pow(
                Math.pow(vertices.get(i).data[0][0], 2) + Math.pow(vertices.get(i).data[1][0], 2),
                0.5);
        if (dist > maxDist) {
          maxDist = dist;
          farPoint = i;
        }
      }

      // Trace out the perimeter of the polygon
      int vertexStart = farPoint;
      int vertex = vertexStart;
      int prevVertex = -1;
      double prevAngle =
          Math.atan2(vertices.get(vertex).data[0][0], vertices.get(vertex).data[1][0]);
      double edgeAngle;
      double angleDiff;
      double minAngleDiff;
      int nextVertex = -1;
      double nextAngle = -1;
      Mat e0, e1;
      ArrayList<Mat> perimeter = new ArrayList<Mat>();
      while (vertex != vertexStart || prevVertex == -1) {
        minAngleDiff = 3 * Math.PI;
        System.err.println("v:" + vertex);
        e0 = vertices.get(vertex);
        //	System.err.println(edgesTo.get(vertex));
        //	Mat.print(System.err, e0);
        perimeter.add(e0);

        if (perimeter.size() > 100) {
          // F**K!
          try {
            throw new Exception();
          } catch (Exception e) {
            e.printStackTrace();
            System.err.println("hey there");
            System.exit(1);
          }
        }

        for (int edgeVertex : edgesTo.get(vertex)) {
          e1 = vertices.get(edgeVertex);
          edgeAngle = Math.atan2(e1.data[0][0] - e0.data[0][0], e1.data[1][0] - e0.data[1][0]);
          angleDiff = edgeAngle - prevAngle;
          if (angleDiff < 0) {
            angleDiff += 2 * Math.PI;
          }
          if (angleDiff > 2 * Math.PI) {
            angleDiff -= 2 * Math.PI;
          }
          if (angleDiff < minAngleDiff && edgeVertex != prevVertex) {
            minAngleDiff = angleDiff;
            nextVertex = edgeVertex;
            nextAngle = edgeAngle;
          }
        }

        System.err.println("PERIMETER ITERATION:");
        System.err.println("vertexStart = " + vertexStart);
        System.err.println("prevVertex = " + prevVertex);
        System.err.println("vertex = " + vertex);
        System.err.println("nextVertex = " + nextVertex);
        System.err.println("");

        if (nextAngle > 0) {
          prevAngle = nextAngle - Math.PI;
        } else {
          prevAngle = nextAngle + Math.PI;
        }
        prevVertex = vertex;
        vertex = nextVertex;
      }

      return new Polygon(perimeter);
    }
コード例 #29
0
ファイル: CSpace.java プロジェクト: nforrester/6.141_labs
    // take the union of two polygons, assuming no enclosed empty spaces, and that the result will
    // be contiguous.
    public static Polygon combine(Polygon poly1, Polygon poly2) {
      ArrayList<Mat> vertices = new ArrayList<Mat>();
      ArrayList<TreeSet<Integer>> edgesTo = new ArrayList<TreeSet<Integer>>();
      int sizePoly1 = poly1.vertices.size();
      int sizePoly2 = poly2.vertices.size();
      int size = sizePoly1 + sizePoly2;
      boolean done;

      Publisher<GUISegmentMsg> segmentPub =
          node.newPublisher("/gui/Segment", "lab5_msgs/GUISegmentMsg");
      Publisher<GUIEraseMsg> erasePub = node.newPublisher("/gui/Erase", "lab5_msgs/GUIEraseMsg");
      // erasePub.publish(new GUIEraseMsg());
      GUISegmentMsg segmentPlot = new GUISegmentMsg();
      ColorMsg segmentPlotColor = new ColorMsg();

      // add all the vertices in both polygons
      vertices.addAll(poly1.vertices);
      vertices.addAll(poly2.vertices);

      for (int i = 0; i < size; i++) {
        edgesTo.add(new TreeSet<Integer>());
      }

      // add all the edges in both polygons
      for (int i = 0; i < sizePoly1; i++) {
        edgesTo.get(i).add(new Integer((i + 1) % sizePoly1));
        edgesTo.get((i + 1) % sizePoly1).add(new Integer(i));
      }
      for (int i = 0; i < sizePoly2; i++) {
        edgesTo.get(i + sizePoly1).add(new Integer(((i + 1) % sizePoly2) + sizePoly1));
        edgesTo.get(((i + 1) % sizePoly2) + sizePoly1).add(new Integer(i + sizePoly1));
      }

      System.err.println(vertices);
      System.err.println(edgesTo);

      segmentPlotColor.r = 255;
      segmentPlotColor.g = 0;
      segmentPlotColor.b = 0;
      segmentPlot.color = segmentPlotColor;
      for (int e0 = 0; e0 < size; e0++) {
        for (int e1 : edgesTo.get(e0)) {
          double[] xyStart = Mat.decodePoint(vertices.get(e0));
          double[] xyEnd = Mat.decodePoint(vertices.get(e1));
          segmentPlot.startX = xyStart[0];
          segmentPlot.startY = xyStart[1];
          segmentPlot.endX = xyEnd[0];
          segmentPlot.endY = xyEnd[1];
          segmentPub.publish(segmentPlot);
        }
      }

      // find and merge colocated points
      done = false;
      while (!done) {
        done = true;
        checkFMCP:
        {
          for (int p0 = 0; p0 < size; p0++) {
            for (int p1 = 0; p1 < size; p1++) {
              if (p0 != p1) {
                if (ptsEqual(vertices.get(p0), vertices.get(p1))) {
                  //						System.err.println("found two colocated: " + p0 + " " + p1);
                  // System.err.println(edgesTo);
                  edgesTo.get(p0).addAll(edgesTo.get(p1));
                  edgesTo.get(p0).remove(p0);
                  vertices.remove(p1);
                  edgesTo.remove(p1);
                  size--;

                  for (int e0 = 0; e0 < size; e0++) {
                    if (edgesTo.get(e0).contains(new Integer(p1))) {
                      edgesTo.get(e0).remove(new Integer(p1));
                      edgesTo.get(e0).add(new Integer(p0));
                    }
                    // System.err.println("e0: " + e0);
                    // System.err.println(edgesTo.get(e0));
                    TreeSet<Integer> head = new TreeSet(edgesTo.get(e0).headSet(new Integer(p1)));
                    // System.err.println(head);
                    for (Integer e1 : edgesTo.get(e0).tailSet(new Integer(p1))) {
                      head.add(e1 - 1);
                    }
                    head.remove(e0);
                    // System.err.println(head);
                    edgesTo.set(e0, head);
                    // System.err.println(edgesTo.get(e0));
                  }

                  done = false;
                  // System.err.println(edgesTo);
                  break checkFMCP;
                }
              }
            }
          }
        }
      }
      System.err.println("merged points");
      System.err.println(edgesTo);

      /*segmentPlotColor.r = 0;
      segmentPlotColor.g = 0;
      segmentPlotColor.b = 255;
      segmentPlot.color = segmentPlotColor;
      for (int e0 = 0; e0 < size; e0++){
      	for (int e1 : edgesTo.get(e0)) {
      		double[] xyStart = Mat.decodePoint(vertices.get(e0));
      		double[] xyEnd   = Mat.decodePoint(vertices.get(e1));
      		segmentPlot.startX = xyStart[0];
      		segmentPlot.startY = xyStart[1];
      		segmentPlot.endX = xyEnd[0];
      		segmentPlot.endY = xyEnd[1];
      		segmentPub.publish(segmentPlot);
      	}
      }*/

      // find and split edges bisected by points
      done = false;
      while (!done) {
        done = true;
        checkFSEBP:
        {
          for (int e0 = 0; e0 < size; e0++) {
            for (int e1 : edgesTo.get(e0)) {
              for (int p = 0; p < size; p++) {
                if (e0 != p && e1 != p) {
                  if (ptSegIntersect(vertices.get(e0), vertices.get(e1), vertices.get(p))) {
                    edgesTo.get(p).add(new Integer(e0));
                    edgesTo.get(p).add(new Integer(e1));

                    edgesTo.get(e0).remove(new Integer(e1));
                    edgesTo.get(e0).add(new Integer(p));

                    edgesTo.get(e1).remove(new Integer(e0));
                    edgesTo.get(e1).add(new Integer(p));

                    done = false;
                    break checkFSEBP;
                  }
                }
              }
            }
          }
        }
      }
      System.err.println("split edges on points");
      System.err.println(edgesTo);

      System.err.println("GOT HERE!");

      int iters = 0;
      done = false;
      while (!done) {
        // find and split intersecting edges
        System.err.println("size: " + size);
        done = true;
        checkFSIE:
        {
          for (int e00 = 0; e00 < size; e00++) {
            for (int e10 = 0; e10 < size; e10++) {
              if (e00 != e10) {
                for (int e01 : new TreeSet<Integer>(edgesTo.get(e00))) {
                  if (e01 != e10 && e01 != e00) {
                    for (int e11 : new TreeSet<Integer>(edgesTo.get(e10))) {
                      if (e11 != e00 && e11 != e01 && e11 != e10) {
                        if (lineSegIntersect(
                            vertices.get(e00),
                            vertices.get(e01),
                            vertices.get(e10),
                            vertices.get(e11))) {
                          // System.err.println("intersectors for iter " + iters);
                          // System.err.println(e00);
                          // System.err.println(edgesTo.get(e00));
                          // Mat.print(System.err, vertices.get(e00));
                          // System.err.println(e01);
                          // System.err.println(edgesTo.get(e01));
                          // Mat.print(System.err, vertices.get(e01));
                          // System.err.println(e10);
                          // System.err.println(edgesTo.get(e10));
                          // Mat.print(System.err, vertices.get(e10));
                          // System.err.println(e11);
                          // System.err.println(edgesTo.get(e11));
                          // Mat.print(System.err, vertices.get(e11));
                          if (iters > 10000) {
                            // F**K!
                            try {
                              throw new Exception();
                            } catch (Exception e) {
                              e.printStackTrace();
                              System.err.println("hey there");
                              System.exit(1);
                            }
                          }
                          iters++;

                          Mat newVertex =
                              lineSegIntersection(
                                  vertices.get(e00),
                                  vertices.get(e01),
                                  vertices.get(e10),
                                  vertices.get(e11));

                          if (ptsEqual(newVertex, vertices.get(e00))) {
                            edgesTo.get(e10).remove(new Integer(e11));
                            edgesTo.get(e10).add(new Integer(e00));
                            edgesTo.get(e00).add(new Integer(e10));

                            edgesTo.get(e11).remove(new Integer(e10));
                            edgesTo.get(e11).add(new Integer(e00));
                            edgesTo.get(e00).add(new Integer(e11));
                          } else if (ptsEqual(newVertex, vertices.get(e01))) {
                            edgesTo.get(e10).remove(new Integer(e11));
                            edgesTo.get(e10).add(new Integer(e01));
                            edgesTo.get(e01).add(new Integer(e10));

                            edgesTo.get(e11).remove(new Integer(e10));
                            edgesTo.get(e11).add(new Integer(e01));
                            edgesTo.get(e01).add(new Integer(e11));
                          } else if (ptsEqual(newVertex, vertices.get(e10))) {
                            edgesTo.get(e00).remove(new Integer(e01));
                            edgesTo.get(e00).add(new Integer(e10));
                            edgesTo.get(e10).add(new Integer(e00));

                            edgesTo.get(e01).remove(new Integer(e00));
                            edgesTo.get(e01).add(new Integer(e10));
                            edgesTo.get(e10).add(new Integer(e01));
                          } else if (ptsEqual(newVertex, vertices.get(e11))) {
                            edgesTo.get(e00).remove(new Integer(e01));
                            edgesTo.get(e00).add(new Integer(e11));
                            edgesTo.get(e11).add(new Integer(e00));

                            edgesTo.get(e01).remove(new Integer(e00));
                            edgesTo.get(e01).add(new Integer(e11));
                            edgesTo.get(e11).add(new Integer(e01));
                          } else {
                            vertices.add(newVertex);

                            edgesTo.add(new TreeSet<Integer>());

                            edgesTo.get(size).add(new Integer(e00));
                            edgesTo.get(size).add(new Integer(e01));
                            edgesTo.get(size).add(new Integer(e10));
                            edgesTo.get(size).add(new Integer(e11));

                            edgesTo.get(e00).remove(new Integer(e01));
                            edgesTo.get(e00).add(new Integer(size));

                            edgesTo.get(e01).remove(new Integer(e00));
                            edgesTo.get(e01).add(new Integer(size));

                            edgesTo.get(e10).remove(new Integer(e11));
                            edgesTo.get(e10).add(new Integer(size));

                            edgesTo.get(e11).remove(new Integer(e10));
                            edgesTo.get(e11).add(new Integer(size));

                            size++;
                          }
                          done = false;
                          break checkFSIE;
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
        System.err.println("split edges on edges");
        System.err.println(edgesTo);
      }

      System.err.println("GOT HERE TOO!");

      System.err.println("begin vertices");
      for (Mat vertex : vertices) {
        Mat.print(System.err, vertex);
      }
      System.err.println("end vertices");
      System.err.println(edgesTo);

      return perimeter(vertices, edgesTo);
    }
コード例 #30
0
ファイル: Init.java プロジェクト: cszongyang/Panthera
  private void RegionChange(Shape s) {
    try {

      GeneralPath g = (GeneralPath) s;

      PathIterator iterator = g.getPathIterator(null);
      float[] floats = new float[6];
      int i = 0;
      int x[] = new int[5];
      int y[] = new int[5];

      while (!iterator.isDone()) {

        iterator.currentSegment(floats);

        x[i] = (int) floats[0];
        y[i] = (int) floats[1];
        i++;
        iterator.next();
      }

      panConnection con = new panConnection();

      ArrayList<Shape> shapes = con.getAllRegions();

      p =
          new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {

              // repaint all regions
              ArrayList<Shape> shapes;
              try {
                shapes = con.getAllRegions();

                Graphics2D g2d = (Graphics2D) g;
                for (int i = 0; i < shapes.size(); i++) {
                  g2d.draw(shapes.get(i));
                }

              } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }

              // paint inner shapes
              try {
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor(Color.red);
                // ponds
                shapes = con.getInnerPonds(x, y);
                for (int i = 0; i < shapes.size(); i++) {
                  Rectangle2D rect = shapes.get(i).getBounds2D();
                  g2d.setPaint(Color.RED);
                  g2d.fillOval(
                      (int) rect.getCenterX() - ((int) rect.getWidth() / 2),
                      (int) rect.getCenterY() - ((int) rect.getHeight() / 2),
                      (int) rect.getWidth(),
                      (int) rect.getHeight());

                  g2d.draw(shapes.get(i));
                }
                // lions
                ArrayList<Point2D> lions;
                lions = con.getInnerLions(x, y);
                for (int i = 0; i < lions.size(); i++) {
                  g2d.setColor(Color.RED);
                  g2d.fillOval((int) lions.get(i).getX(), (int) lions.get(i).getY(), 5, 5);

                  g2d.drawOval((int) lions.get(i).getX(), (int) lions.get(i).getY(), 5, 5);
                }

              } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }

              // paint outside shapes
              try {
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor(Color.BLACK);
                // ponds
                shapes = con.getOuterPonds(x, y);
                for (int i = 0; i < shapes.size(); i++) {
                  Rectangle2D rect = shapes.get(i).getBounds2D();

                  //    g2d.fill(circle);
                  g2d.setPaint(Color.BLUE);
                  g2d.fillOval(
                      (int) rect.getCenterX() - ((int) rect.getWidth() / 2),
                      (int) rect.getCenterY() - ((int) rect.getHeight() / 2),
                      (int) rect.getWidth(),
                      (int) rect.getHeight());

                  g2d.setColor(Color.BLACK);
                  g2d.draw(shapes.get(i));
                }
                // lions
                ArrayList<Point2D> lions;
                lions = con.getOuterLions(x, y);
                for (int i = 0; i < lions.size(); i++) {
                  g2d.setColor(Color.GREEN);
                  g2d.fillOval((int) lions.get(i).getX(), (int) lions.get(i).getY(), 5, 5);

                  g2d.drawOval((int) lions.get(i).getX(), (int) lions.get(i).getY(), 5, 5);
                }

              } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
            }

            @Override
            public Dimension getPreferredSize() {
              return new Dimension(505, 505);
            }
          };

      p.repaint();
      p.setBackground(Color.white);

      mainMap.add(p);

      mainMap.pack();
      mainMap.setVisible(true);

      // g2.draw(shapes.get(0));

    } catch (Exception e) {
      System.out.println("kao");
      e.printStackTrace();
    }
  }