Ejemplo n.º 1
0
 def rotate(self, surface, angle):
     """
     Return Surface rotated by the given angle.
     """
     if not angle:
         return surface.copy()
     theta = angle*self.deg_rad
     width_i = surface.getWidth()
     height_i = surface.getHeight()
     cos_theta = _fabs( _cos(theta) )
     sin_theta = _fabs( _sin(theta) )
     width_f = int( (width_i*cos_theta)+(height_i*sin_theta) )
     height_f = int( (width_i*sin_theta)+(height_i*cos_theta) )
     surf = Surface((width_f,height_f), BufferedImage.TYPE_INT_ARGB)
     at = AffineTransform()
     at.translate(width_f/2, height_f/2)
     at.rotate(-theta)
     g2d = surf.createGraphics()
     ot = g2d.getTransform()
     g2d.setTransform(at)
     g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
     g2d.drawImage(surface, -width_i//2, -height_i//2, None)
     g2d.setTransform(ot)
     g2d.dispose()
     return surf
Ejemplo n.º 2
0
 def rotozoom(self, surface, angle, size):
     """
     Return Surface rotated and resized by the given angle and size.
     """
     if not angle:
         width = int(surface.getWidth()*size)
         height = int(surface.getHeight()*size)
         return self.scale(surface, (width, height))
     theta = angle*self.deg_rad
     width_i = int(surface.getWidth()*size)
     height_i = int(surface.getHeight()*size)
     cos_theta = _fabs( _cos(theta) )
     sin_theta = _fabs( _sin(theta) )
     width_f = int( _ceil((width_i*cos_theta)+(height_i*sin_theta)) )
     if width_f % 2:
         width_f += 1
     height_f = int( _ceil((width_i*sin_theta)+(height_i*cos_theta)) )
     if height_f % 2:
         height_f += 1
     surf = Surface((width_f,height_f), BufferedImage.TYPE_INT_ARGB)
     at = AffineTransform()
     at.translate(width_f/2, height_f/2)
     at.rotate(-theta)
     g2d = surf.createGraphics()
     ot = g2d.getTransform()
     g2d.setTransform(at)
     g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
     g2d.drawImage(surface, -width_i//2, -height_i//2, width_i, height_i, None)
     g2d.setTransform(ot)
     g2d.dispose()
     return surf
Ejemplo n.º 3
0
  def initialiseGraphics(self):
    self.polygonalTilePath = GeneralPath() 
    self.polygonalTilePath.append(self.wiggle, 1)

    t = AffineTransform.getTranslateInstance(1, 0)
    t.rotate(math.pi / 2)
    wiggle2 = GeneralPath(self.wiggle)
    wiggle2.transform(t)
    self.polygonalTilePath.append(wiggle2, 1)

    t = AffineTransform.getTranslateInstance(1, 1)
    t.rotate(3 * math.pi / 4)
    t.scale(1 / math.sqrt(2), 1 / math.sqrt(2))
    wiggle3 = GeneralPath(self.wiggle)
    wiggle3.transform(t)
    self.polygonalTilePath.append(wiggle3, 1)

    t = AffineTransform.getTranslateInstance(0.5, 1.5)
    t.rotate(5 * math.pi / 4)
    t.scale(1 / math.sqrt(2), 1 / math.sqrt(2))
    wiggle4 = GeneralPath(self.wiggle)
    wiggle4.transform(t)
    self.polygonalTilePath.append(wiggle4, 1)

    t = AffineTransform.getTranslateInstance(0, 1)
    t.rotate(3 * math.pi / 2)
    wiggle5 = GeneralPath(self.wiggle)
    wiggle5.transform(t)
    self.polygonalTilePath.append(wiggle5, 1)

    self.polygonalTilePath.closePath()
    self.polygonalTilePath.transform(self.preTransform)
Ejemplo n.º 4
0
def generate_image(width, height):
	renderer = StaticRenderer()
	renderer.setTree(GVTBuilder().build(context, document))
	transform = AffineTransform()
	transform.translate(-svg_x, -svg_y)
	transform.scale(width / svg_width, height / svg_height)
	renderer.setTransform(transform)
	renderer.updateOffScreen(width, height)
	renderer.repaint(Rectangle(0, 0, width, height))
	return renderer.getOffScreen()
Ejemplo n.º 5
0
 def showAt(self, mx, my):
     bg.setPaintColor(self.color)
     t = AffineTransform()
     t.translate(mx, -50 + my % 650)  # Restrict to playground
     # Cloning to avoid side effects
     gp1 = self.tri1.clone()
     gp2 = self.tri2.clone()
     gp1.transform(t)
     gp2.transform(t)
     bg.fillGeneralPath(gp1)
     bg.fillGeneralPath(gp2)
def add_text_to_image(editable_image, text, font, color, x, y, size=10.0, text_width=None, text_height=None):

    assert isinstance(editable_image, BufferedImage), "No *editable* image (instance of ImageIO) given!"
    assert len(text) > 0, "No or empty text given..."
    assert isinstance(font, Font), "No valid font given! Should be instance of java.awt.Font!"
    assert isinstance(color, Color), "No valid color given! Should be instance of java.awt.Color!"
    assert isinstance(x, float), "No valid number given! Should be a float value"
    assert isinstance(y, float), "No valid number given! Should be a float value"

    assert width is None or isinstance(width, float)
    assert height is None or isinstance(height, float)

    text = text.replace("\r", "\n")
    print text

    g = editable_image.getGraphics()
    g.setFont(font)
    g.setColor(color)
    # in case no stretchin
    if (text_width and text_height) is None:
        g.drawString(text, x, y)
        g.dispose()
        return editable_image

    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
    stretch = AffineTransform()
    color_tmp = Color(0, 0, 1, 0.0)
    g.setColor(color_tmp)
    g.drawString(text, x, y)
    g.setColor(color)
    # note first string is only made to get text width of g
    # TODO if possible remove first text string

    original_text_width = g.getFontMetrics(font).stringWidth(text)
    original_text_height = g.getFontMetrics(font).getHeight()
    assert isinstance(original_text_height, int)
    assert isinstance(original_text_width, int)
    # print(original_text_width)
    # print(original_text_height)

    if text_width is None:
        text_width = original_text_width
    if text_height is None:
        text_height = original_text_height

    factor_x = float(text_width) / original_text_width
    factor_y = float(text_height) / original_text_height
    stretch.scale(factor_x, factor_y)
    g.setTransform(stretch)
    g.drawString(text, x, y)
    g.dispose()

    return editable_image
Ejemplo n.º 7
0
    def setSize(self, size):
        # First triangle, size is radius of circumcircle, center at (0,0)
        self.tri1 = GeneralPath()
        self.tri1.moveTo(size, 0)
        self.tri1.lineTo(int(-0.5 * size), int(0.866 * size))
        self.tri1.lineTo(int(-0.5 * size), int(-0.866 * size))
        self.tri1.closePath()

        # Second triangle like first, but rotated 180 degrees
        self.tri2 = self.tri1.clone()
        t = AffineTransform()
        t.rotate(math.pi)
        self.tri2.transform(t)
Ejemplo n.º 8
0
    def run(self):
        try:
            filepath = self.makeFilePath()
            if os.path.exists(filepath):
                return

            x, y, k = self.coords
            width, height, n_layers = self.dimensions

            # Cube's field of view in XY
            fov = Rectangle(x, y, width, height)

            # Join the bounds of the layers
            r = None
            for b in self.bounds[k:min(k + n_layers, len(bounds))]:
                if r is None:
                    r = Rectangle(b.x, b.y, b.width, b.height)
                else:
                    r.add(b)

            if not fov.intersects(r):
                # Would be empty
                return

            drawImage = Graphics2D.getDeclaredMethod(
                "drawImage", [Image, AffineTransform, ImageObserver])
            drawImage.setAccessible(True)
            dispose = Graphics.getDeclaredMethod("dispose", [])
            dispose.setAccessible(True)

            # Populate and write cube
            stack = ImageStack(width, height)
            for layer in self.layers[k:min(k + n_layers, len(self.layers))]:
                img = layer.getProject().getLoader().getFlatAWTImage(
                    layer, fov, 1.0, -1, ImagePlus.GRAY8, Patch, None, False,
                    Color.black)
                bi = BufferedImage(img.getWidth(None), img.getHeight(None),
                                   BufferedImage.TYPE_BYTE_GRAY)
                g = bi.createGraphics()
                aff = AffineTransform(1, 0, 0, 1, 0, 0)
                #g.drawImage(img, aff, None) # Necessary to bypass issues that result in only using 7-bits and with the ByteProcessor constructor
                drawImage.invoke(g, [img, aff, None])
                #g.dispose()
                dispose.invoke(g, [])
                g = None
                img = None
                stack.addSlice("", ByteProcessor(bi))
                bi.flush()
                bi = None

            imp = ImagePlus("x=%s y=%s k=%s" % (x, y, k), stack)
            Utils.ensure(filepath)
            FileSaver(imp).saveAsZip(filepath)
            imp.flush()
            imp = None
        except:
            e = sys.exc_info()
            System.out.println("Error:" + str(e[0]) + "\n" + str(e[1]) + "\n" +
                               str(e[2]))
            System.out.println(traceback.format_exception(e[0], e[1], e[2]))
Ejemplo n.º 9
0
    def write(self, bbox, size):
        scx, scy = bbox.width / size[0], -1 * bbox.height / size[1]
        at = AffineTransform(scx, 0, 0, scy, bbox.west + scx / 2.0,
                             bbox.north + scy / 2.0)

        f = util.toFile(self.file)
        WorldFileWriter(f, at)
Ejemplo n.º 10
0
def transform(g, dx=0, dy=0, sx=1, sy=1, shx=0, shy=0, r=0):
    """
  Tranforms a geometry with an affine transformation.

  *g* is the :class:`Geometry <geoscript.geom.Geometry>` to transform. 

  *dx*, *dy* specify the x,y translation.

  *sx*, *sy* specify the x,y scale factors.

  *shx, shy* specify the x,y shear factors.

  *r* specifies the rotation angle in radians.
  """
    tx = AffineTransform(sx, shy, shx, sy, dx, dy)
    tx.rotate(r)
    return JTS.transform(g, AffineTransform2D(tx))
Ejemplo n.º 11
0
def measureCustom(layerset):
  # Obtain a list of all AreaLists:
  alis = layerset.getZDisplayables(AreaList)
  # The loader
  loader = layerset.getProject().getLoader()
  # The ResultsTable
  table = Utils.createResultsTable("AreaLists", ["id", "layer", "Z", "area", "mean"])
  # The LayerSet's Calibration (units in microns, etc)
  calibration = layerset.getCalibrationCopy()
  # The measurement options as a bit mask:
  moptions = Measurements.AREA | Measurements.MEAN
  
  for ali in alis:
    affine = ali.getAffineTransformCopy()
    box = ali.getBoundingBox()
    index = 0
    for layer in layerset.getLayers():
      index += 1 # layer index starts at 1, so sum before
      # The java.awt.geom.Area object for the AreaList 'ali'
      # at the given Layer 'layer':
      area = ali.getArea(layer)
      if area:
        # Bring the area to world coordinates,
        # and then local to its own data:
        tr = AffineTransform()
        tr.translate(-box.x, -box.y)
        tr.concatenate(affine)
        area = area.createTransformedArea(tr)
        # Create a snapshot of the images under the area:
        imp = loader.getFlatImage(layer, box, 1, 0xffffffff,
              ImagePlus.GRAY8, Patch, False)
        # Set the area as a roi
        imp.setRoi(ShapeRoi(area))
        # Perform measurements (uncalibrated)
	# (To get the calibration, call layerset.getCalibrationCopy())
        stats = ByteStatistics(imp.getProcessor(), moptions, calibration)
	table.incrementCounter()
	table.addLabel("Name", ali.getTitle())
	table.addValue(0, ali.getId())
	table.addValue(1, index) # the layer index
	table.addValue(2, layer.getZ()) 
	table.addValue(3, stats.area)
	table.addValue(4, stats.mean)
    # Update and show the table
    table.show("AreaLists")
def scaleContour(pol, scale):
	# Scale up the polygon relative to its center
	cx = 0
	cy = 0
	for i in range(pol.npoints):
		cx += pol.xpoints[i]
		cy += pol.ypoints[i]

	cx /= pol.npoints
	cy /= pol.npoints

	aff = AffineTransform(1, 0, 0, 1, -cx, -cy)
	aff.preConcatenate(AffineTransform(scale, 0, 0, scale, 0, 0))
	aff.preConcatenate(AffineTransform(1, 0, 0, 1, cx, cy))

	tmp = Area(pol)
	tmp.transform(aff)
	return M.getPolygons(tmp)[0]
Ejemplo n.º 13
0
 def flip(self, surface, xbool=True, ybool=False):
     """
     Return Surface that is flipped horizontally, vertically, or both.
     """
     if xbool and ybool:
         at = AffineTransform.getScaleInstance(-1, -1)
         at.translate(-surface.getHeight(), -surface.getHeight())
     elif xbool:
         at = AffineTransform.getScaleInstance(-1, 1)
         at.translate(-surface.getWidth(), 0)
     elif ybool:
         at = AffineTransform.getScaleInstance(1, -1)
         at.translate(0, -surface.getHeight())
     else:
         return surface
     op = AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR)
     bimage = op.filter(surface, None)
     surf = Surface(bimage)
     return surf
Ejemplo n.º 14
0
 def flip(self, surface, xbool=True, ybool=False):
     """
     Return Surface that is flipped horizontally, vertically, or both.
     """
     if xbool and ybool:
         at = AffineTransform.getScaleInstance(-1, -1)
         at.translate(-surface.getHeight(), -surface.getHeight())
     elif xbool:
         at = AffineTransform.getScaleInstance(-1, 1)
         at.translate(-surface.getWidth(), 0)
     elif ybool:
         at = AffineTransform.getScaleInstance(1, -1)
         at.translate(0, -surface.getHeight())
     else:
         return surface
     op = AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR)
     bimage = op.filter(surface, None)
     surf = Surface(bimage)
     return surf
Ejemplo n.º 15
0
 def _getArea(self):
     h = int((self._get("scale") * self._get("height")))
     w = int((self._get("scale") * self._get("width")))
     p = self._get("position")
     center = self._get("center")
     theta = self._get("rotation")
     #ar = Area(Rectangle2D.Double(-center.x, -center.y, 1, 1))
     ar = self._area(self, center)
     g = AffineTransform()
     g.translate(p.x, p.y)
     g.rotate(theta)
     g.scale(w, h)
     ar.transform(g)
     return ar
Ejemplo n.º 16
0
def rotate(surface, angle):
    """
    Return Surface rotated by the given angle.
    """
    if not angle:
        return surface.copy()
    theta = angle * _deg_rad
    width_i = surface.getWidth()
    height_i = surface.getHeight()
    cos_theta = _fabs(_cos(theta))
    sin_theta = _fabs(_sin(theta))
    width_f = int((width_i * cos_theta) + (height_i * sin_theta))
    height_f = int((width_i * sin_theta) + (height_i * cos_theta))
    surf = Surface((width_f, height_f), BufferedImage.TYPE_INT_ARGB)
    at = AffineTransform()
    at.translate(width_f / 2.0, height_f / 2.0)
    at.rotate(-theta)
    g2d = surf.createGraphics()
    ot = g2d.getTransform()
    g2d.setTransform(at)
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                         RenderingHints.VALUE_INTERPOLATION_BILINEAR)
    g2d.drawImage(surface, -width_i // 2, -height_i // 2, None)
    g2d.setTransform(ot)
    g2d.dispose()
    return surf
Ejemplo n.º 17
0
def rotozoom(surface, angle, size):
    """
    Return Surface rotated and resized by the given angle and size.
    """
    if not angle:
        width = int(surface.getWidth() * size)
        height = int(surface.getHeight() * size)
        return scale(surface, (width, height))
    theta = angle * _deg_rad
    width_i = int(surface.getWidth() * size)
    height_i = int(surface.getHeight() * size)
    cos_theta = _fabs(_cos(theta))
    sin_theta = _fabs(_sin(theta))
    width_f = int(_ceil((width_i * cos_theta) + (height_i * sin_theta)))
    if width_f % 2:
        width_f += 1
    height_f = int(_ceil((width_i * sin_theta) + (height_i * cos_theta)))
    if height_f % 2:
        height_f += 1
    surf = Surface((width_f, height_f), BufferedImage.TYPE_INT_ARGB)
    at = AffineTransform()
    at.translate(width_f / 2.0, height_f / 2.0)
    at.rotate(-theta)
    g2d = surf.createGraphics()
    ot = g2d.getTransform()
    g2d.setTransform(at)
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                         RenderingHints.VALUE_INTERPOLATION_BILINEAR)
    g2d.drawImage(surface, -width_i // 2, -height_i // 2, width_i, height_i,
                  None)
    g2d.setTransform(ot)
    g2d.dispose()
    return surf
Ejemplo n.º 18
0
 def rotate(self, surface, angle):
     """
     Return Surface rotated by the given angle.
     """
     theta = angle * self.deg_rad
     width_i = surface.getWidth()
     height_i = surface.getHeight()
     cos_theta = math.fabs(math.cos(theta))
     sin_theta = math.fabs(math.sin(theta))
     width_f = int((width_i * cos_theta) + (height_i * sin_theta))
     height_f = int((width_i * sin_theta) + (height_i * cos_theta))
     surf = Surface((width_f, height_f), BufferedImage.TYPE_INT_ARGB)
     at = AffineTransform()
     at.rotate(-theta, width_f / 2, height_f / 2)
     g2d = surf.createGraphics()
     ot = g2d.getTransform()
     g2d.setTransform(at)
     g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                          RenderingHints.VALUE_INTERPOLATION_BILINEAR)
     g2d.drawImage(surface, (width_f - width_i) // 2,
                   (height_f - height_i) // 2, None)
     g2d.setTransform(ot)
     g2d.dispose()
     return surf
Ejemplo n.º 19
0
def generate_image(width, height):
    renderer = StaticRenderer()
    renderer.setTree(GVTBuilder().build(context, document))
    transform = AffineTransform()
    transform.translate(-svg_x, -svg_y)
    transform.scale(width / svg_width, height / svg_height)
    renderer.setTransform(transform)
    renderer.updateOffScreen(width, height)
    renderer.repaint(Rectangle(0, 0, width, height))
    return renderer.getOffScreen()
Ejemplo n.º 20
0
 def _getArea(self):
     h = int((self._get("scale") * self._get("height")))
     w = int((self._get("scale") * self._get("width")))
     p = self._get("position")
     center = self._get("center")
     theta = self._get("rotation")
     #ar = Area(Rectangle2D.Double(-center.x, -center.y, 1, 1))
     ar = self._area(self, center)
     g = AffineTransform()
     g.translate(p.x, p.y)
     g.rotate(theta)
     g.scale(w, h)
     ar.transform(g)
     return ar
Ejemplo n.º 21
0
  def initialiseGraphics(self):
    wiggle=CubicCurve2D.Double(0, 0, 0.3, -0.3, 0.7, 0.3, 1, 0)
    reverseWiggle=CubicCurve2D.Double(1, 0, 0.7, 0.3, 0.3, -0.3, 0, 0)

    self.polygonalTilePath = GeneralPath() 
    self.polygonalTilePath.append(wiggle, 1)

    self.polygonalTilePath.lineTo(math.cos(math.pi / self.n), math.sin(math.pi / self.n))

    t = AffineTransform.getRotateInstance(math.pi / self.n)
    wiggle2 = GeneralPath(reverseWiggle)
    wiggle2.transform(t)
    self.polygonalTilePath.append(wiggle2, 1)

    self.polygonalTilePath.closePath()
    self.polygonalTilePath.transform(self.preTransform)
Ejemplo n.º 22
0
def measureCustom(layerset):
    # Obtain a list of all AreaLists:
    alis = layerset.getZDisplayables(AreaList)
    # The loader
    loader = layerset.getProject().getLoader()
    # The ResultsTable
    table = Utils.createResultsTable("AreaLists",
                                     ["id", "layer", "Z", "area", "mean"])
    # The LayerSet's Calibration (units in microns, etc)
    calibration = layerset.getCalibrationCopy()
    # The measurement options as a bit mask:
    moptions = Measurements.AREA | Measurements.MEAN

    for ali in alis:
        affine = ali.getAffineTransformCopy()
        box = ali.getBoundingBox()
        index = 0
        for layer in layerset.getLayers():
            index += 1  # layer index starts at 1, so sum before
            # The java.awt.geom.Area object for the AreaList 'ali'
            # at the given Layer 'layer':
            area = ali.getArea(layer)
            if area:
                # Bring the area to world coordinates,
                # and then local to its own data:
                tr = AffineTransform()
                tr.translate(-box.x, -box.y)
                tr.concatenate(affine)
                area = area.createTransformedArea(tr)
                # Create a snapshot of the images under the area:
                imp = loader.getFlatImage(layer, box, 1, 0xffffffff,
                                          ImagePlus.GRAY8, Patch, False)
                # Set the area as a roi
                imp.setRoi(ShapeRoi(area))
                # Perform measurements (uncalibrated)
                # (To get the calibration, call layerset.getCalibrationCopy())
                stats = ByteStatistics(imp.getProcessor(), moptions,
                                       calibration)
                table.incrementCounter()
                table.addLabel("Name", ali.getTitle())
                table.addValue(0, ali.getId())
                table.addValue(1, index)  # the layer index
                table.addValue(2, layer.getZ())
                table.addValue(3, stats.area)
                table.addValue(4, stats.mean)
        # Update and show the table
        table.show("AreaLists")
Ejemplo n.º 23
0
	av.setEntry(0 ,0 , vx)
	av.setEntry(1, 0, vy)

#	dd = [2.0, 6,0]
#	jdd = array(dd, 'd')	
#	bv = am(jdd) 

	rot = rotation
	mat = am(2, 2)
	mat.setEntry(0, 0, math.cos(rot))
	mat.setEntry(0, 1, -1 * math.sin(rot))
	mat.setEntry(1, 0, math.sin(rot))
	mat.setEntry(1, 1, math.cos(rot))
	#print mat.getData()
	avdash = mat.multiply(av)
	return avdash

#rotvec  = rotateVec(1, 1, math.pi/4)
#print rotvec.getData()

roter = AT.getRotateInstance(math.pi/4, 0, 0)
sp = pnt(1, 1)
dp = pnt()
roter.deltaTransform(sp, dp)
print dp.x
print dp.y
 

 

Ejemplo n.º 24
0
for line in fobj:
    affineline = line.split()
    affines[affineline[0]] = [
        affineline[1], affineline[2], affineline[3], affineline[4],
        affineline[5], affineline[6]
    ]
fobj.close()

# ...
# ...

# Apply the affine to every Patch
from ini.trakem2.display import Display, Patch
from java.awt.geom import AffineTransform

for layer in Display.getFront().getLayerSet().getLayers():
    for patch in layer.getDisplayables(Patch):
        filepath = patch.getImageFilePath()
        print("filepath\n")
        affine = affines.get(filepath,
                             None)  #filepath statt affines eingefuegt
        if affine:
            for index in range(0, 6):
                affine[index] = float(affine[index])
                print("affine[index]", index, affine[index])
            patch.setAffineTransform(
                AffineTransform(affine[0], affine[1], affine[2], affine[3],
                                (affine[4]), affine[5]))
        else:
            print "No affine for filepath:", filepath
        print("done\n")
Ejemplo n.º 25
0
    # insert the tiles according to the transforms computed on the reference brightfield channel
    IJ.log('Inserting all patches')
    for i in range(0, len(transforms), 8):
        alignedPatchPath = transforms[i]
        l = int(transforms[i + 1])
        alignedPatchName = os.path.basename(alignedPatchPath)

        toAlignPatchPath = fc.cleanLinuxPath(
            os.path.join(os.path.dirname(alignedPatchPath),
                         alignedPatchName.replace(channels[-1], channel)))
        toAlignPatchPath = toAlignPatchPath[:
                                            -1]  # remove a mysterious trailing character ...
        IJ.log('In channel ' + str(channel) + ', inserting this image: ' +
               str(toAlignPatchPath))
        aff = AffineTransform(
            [float(transforms[a]) for a in range(i + 2, i + 8)])
        patch = Patch.createPatch(project, toAlignPatchPath)
        layer = layerset.getLayers().get(l)
        layer.add(patch)
        patch.setAffineTransform(aff)
        patch.updateBucket()

    time.sleep(1)
    IJ.log('Readjusting display')
    fc.resizeDisplay(layerset)
    IJ.log('Blending all layers')
    Blending.blendLayerWise(layerset.getLayers(), True, None)

    IJ.log('Exporting')
    for scaleFactor in scaleFactors:
        theBaseName = 'exported_downscaled_' + str(int(
Ejemplo n.º 26
0
from java.awt.geom import AffineTransform
from array import array

# 2D point
x = 10
y = 40

# Affine transformation
# https://docs.oracle.com/javase/1.5.0/docs/api/java/awt/geom/AffineTransform.html
# https://darkpgmr.tistory.com/79
# [ x']   [  m00  m01  m02  ] [ x ]   [ m00x + m01y + m02 ]
# [ y'] = [  m10  m11  m12  ] [ y ] = [ m10x + m11y + m12 ]
# [ 1 ]   [   0    0    1   ] [ 1 ]   [         1         ]
# AffineTransform(float m00, float m10, float m01, float m11, float m02, float m12)
aff = AffineTransform(1, 0, 0, 1, 45, 56)

# Create a point as a list of x, y
p = [x, y]
# transform(float[] srcPts, int srcOff, float[] dstPts, int dstOff, int numPts)
aff.transform(p, 0, p, 0, 1)
print "p=", p # 그대로 [10, 40]. update 안됨.LookupError

# Create a point as a native float array of x, y
q = array('f', [x, y])
aff.transform(q, 0, q, 0, 1)
print "q=", q
Ejemplo n.º 27
0
 def turn(self, angle):
     t = AffineTransform()
     t.rotate(angle)
     self.tri1.transform(t)
     self.tri2.transform(t)
Ejemplo n.º 28
0
viewTransformed(imp, rotate45, title=imp.getTitle() + " rotate45")

# Remembering the formulas for the translation to correct
# for the origin of transformation (e.g. the center) isn't easy,
# and the fidgety of it all makes it error prone.

# For 2D, java offers an AffineTransform class that addresses this issue
# quite trivially, with the method rotate that takes an origin of rotation
# as argument.
# BEWARE that positive angles rotate to the right (rather than to the left)
# in the AffineTransform, so we use radians(45) instead of radians(-45).
# And BEWARE that AffineTransform.getMatrix fills a double[] array in
# an order that you wouldn't expect (see the javadoc), so instead
# we call each value of the matrix, one by one, to fill our matrix.

aff = AffineTransform()  # initialized as the identity transform
cx = imp.getWidth() / 2.0
cy = imp.getHeight() / 2.0
aff.rotate(radians(45), cx, cy)
rotate45easy = AffineTransform2D()
rotate45easy.set(aff.getScaleX(), aff.getShearX(), aff.getTranslateX(),
                 aff.getShearY(), aff.getScaleY(), aff.getTranslateY())

print rotate45easy

viewTransformed(imp, rotate45easy, title=imp.getTitle() + " rotate45easy")

# An alternative that works also for 3D transformations exploits
# a nice property of transformation matrices: that they can be combined.
# That is, instead of applying a transform to an image, an then applying
# a second transform to the resulting image, instead the transformation
Ejemplo n.º 29
0
 def transform(self, t):
   t = AffineTransform(t)
   t.concatenate(self.preTransformation)
   tile = Trimorphic(t)
   tile.getUI().setBackground(self.getUI().getBackground())
   return tile
Ejemplo n.º 30
0
preprocessor_script_path = "/tmp/trakem2-n5.bsh"
with open(preprocessor_script_path, 'w') as f:
    f.write(script)

# Create as many layers as indices in the Z dimension
layers = []
for z in xrange(dimensions[2]):
    layer = layerset.getLayer(z, 1.0, True)  # create if not there
    layerset.addSilently(layer)
    layers.append(layer)
    # Add a single Patch instance per Layer, whose image is a 2D crop of the N5 volume
    if 0 == layer.getDisplayables().size():
        index = layerset.getLayerIndex(layer.getId())
        patch = Patch(project, str(z), dimensions[0], dimensions[1],
                      dimensions[0], dimensions[1], img_type, 1.0, Color.black,
                      True, 0, 255, AffineTransform(), "")
        layer.add(patch, False)  # don't update displays
        project.getLoader().setPreprocessorScriptPathSilently(
            patch, preprocessor_script_path)

layerset.recreateBuckets(layers, True)
Display.updateLayerScroller(layerset)

# Export for CATMAID from raw images (strategy=0)
"""
saver = Saver("jpg")
saver.setQuality(0.75)
ExportMultilevelTiles.makePrescaledTiles(layers, Patch, Rectangle(0, 0, dimensions[0], dimensions[1]),
                                         -1, img_type, tgt_dir, 0, saver, tile_side, 1,
                                         True, True,
                                         Runtime.getRuntime().availableProcessors())
Ejemplo n.º 31
0
def draw(g, size=(500,500)):
  """
  Draws a geometry onto a canvas.

  *size* is a tuple that specifies the dimensions of the canvas the geometry will drawn upon. 
  """
  buf = 50.0

  if not isinstance(g, list):
    g = [g]

  e = _fac.createGeometryCollection(g).getEnvelopeInternal()
  scale = size[0] / e.width if e.width > 0 else sys.maxint
  scale = min(scale, size[1] / e.height) if e.height > 0 else 1 

  tx = -1*e.minX
  ty = -1*e.minY
       
  at = AffineTransform()
  
  # scale to size of canvas (inverting the y axis)
  at.scale(scale,-1*scale)
  
  # translate to the origin
  at.translate(tx,ty)

  # translate to account for invert
  at.translate(0,-1*size[1]/scale)

  # buffer
  at.translate(buf/scale,-1*buf/scale)
        
  class Panel(swing.JPanel):

    def __init__(self, geoms, atx):
      self.geoms = geoms
      self.atx = atx

    def paintComponent(self, gc):
      opaque = gc.getComposite()      
      gc.setRenderingHint(awt.RenderingHints.KEY_ANTIALIASING, 
        awt.RenderingHints.VALUE_ANTIALIAS_ON)
      gc.setStroke(awt.BasicStroke(2))

      i = 0
      for g in self.geoms:
        shp = LiteShape(g, self.atx, False)

        if isinstance(g, (Polygon, MultiPolygon)):
          i = i + 1
          gc.setColor(awt.Color.WHITE)
          gc.setComposite(awt.AlphaComposite.getInstance(awt.AlphaComposite.SRC_OVER, 0.5))
          gc.fill(shp)

        gc.setComposite(opaque)
        gc.setColor(awt.Color.BLACK)
        gc.draw(shp)

  panel = Panel(g, at)
  s = tuple([int(size[x]+2*buf) for x in range(2)])
  panel.preferredSize = s
  frame = swing.JFrame()
  frame.contentPane = panel
  frame.pack()
  frame.visible = True
# Define the interval we want to see: the original image, enlarged by 2X
# E.g. from 0 to 2*width, from 0 to 2*height, etc. for every dimension
# Notice the -1 in maxC: the interval is inclusive of the largest coordinate.
minC = [0 for d in range(img.numDimensions())]
maxC = [int(img.dimension(i) * scale) -1 for i, scale in enumerate(s)]
imgI = Views.interval(bigger, minC, maxC)

# Visualize the bigger view
imp2x = IL.wrap(imgI, imp.getTitle() + " - 2X") # an ImagePlus
imp2x.show()

# Define a rotation by +30º relative to the image center in the XY axes
# (not explicitly XY but the first two dimensions)
angle = radians(30)
rot2d = Affine2D.getRotateInstance(angle, img.dimension(0) / 2, img.dimension(1) / 2)
ndims = img.numDimensions()
matrix = Matrix(ndims, ndims + 1)
matrix.set(0, 0, rot2d.getScaleX())
matrix.set(0, 1, rot2d.getShearX())
matrix.set(0, ndims, rot2d.getTranslateX())
matrix.set(1, 0, rot2d.getShearY())
matrix.set(1, 1, rot2d.getScaleY())
matrix.set(1, ndims, rot2d.getTranslateY())
for i in range(2, img.numDimensions()):
  matrix.set(i, i, 1.0)

from pprint import pprint
pprint([list(row) for row in matrix.getArray()])

# Define a rotated view of the image
Ejemplo n.º 33
0
 def transform(self, t):
   t = AffineTransform(t)
   t.concatenate(self.preTransformation)
   w = SHorn(self.n, t)
   w.getUI().setBackground(self.getUI().getBackground())
   return w
Ejemplo n.º 34
0
        #////////////////////////////
        targetImage = images[0]
        targetProcessor = targetImage.getProcessor()
        targetHeight = float(targetProcessor.getHeight())
        targetWidth = float(targetProcessor.getWidth())

	#////////////////////////////
        # Determine scaling information, scaling target image rois to mass images size.
        #////////////////////////////
        scalingHeight = float(targetHeight/height)
        scalingWidth = float(targetHeight/width)

	#////////////////////////////
        # Loop through rois in IJ roi manager, scale them, then add to OpenMIMS images
        #////////////////////////////
        rois = IJRoiManager.getRoisAsArray()
        for i in range(len(rois)):
          roi = rois[i]
          polygon = roi.getPolygon()
          at = AfTransform.getScaleInstance(scalingHeight, scalingWidth)
          roi = ShapeRoi(at.createTransformedShape(polygon)).shapeToRoi()
          MIMSRoiManager.add(roi)

        #////////////////////////////
        # Update all the images and open the OpenMimsRoi manager
        #////////////////////////////
        ui.updateAllImages()
        MIMSRoiManager.viewManager()

        
Ejemplo n.º 35
0
# insert the tiles in the project
IJ.log('I am going to insert many files at factor ' + str(downsamplingFactor) + ' ...')
task = loader.importImages(layerset.getLayers().get(0), importFilePath, '\t', 1, 1, False, 1, 0)
task.join()

# apply the transforms
for i in range(0, len(transforms), 8):
	alignedPatchPath = transforms[i]
	alignedPatchName = os.path.basename(alignedPatchPath)
	toAlignPatchName = alignedPatchName.replace('_' + factorString, '').replace('_resized', '')
	toAlignPatchPath = os.path.join(MagCFolder, 'EMData', os.path.basename(os.path.dirname(alignedPatchPath)), toAlignPatchName)
	toAlignPatchPath = toAlignPatchPath[:-1]  # why is there a trailing something !?
	if toAlignPatchPath[:2] == os.sep + os.sep:
		toAlignPatchPath = toAlignPatchPath[1:]
	IJ.log('toAlignPatchPath ' + toAlignPatchPath)
	l = int(transforms[i+1])
	aff = AffineTransform([float(transforms[i+2]), float(transforms[i+3]), float(transforms[i+4]), float(transforms[i+5]), float(transforms[i+6])*float(downsamplingFactor), float(transforms[i+7])*float(downsamplingFactor) ])
	layer = layerset.getLayers().get(l)
	patches = layer.getDisplayables(Patch)
	thePatch = filter(lambda x: os.path.normpath(loader.getAbsolutePath(x)) == os.path.normpath(toAlignPatchPath), patches)[0]
	thePatch.setAffineTransform(aff)
	thePatch.updateBucket()

time.sleep(2)
fc.resizeDisplay(layerset)
time.sleep(2)
project.save()
fc.closeProject(project)
fc.terminatePlugin(namePlugin, MagCFolder)
Ejemplo n.º 36
0
def draw(g, size=(500, 500)):
    """
  Draws a geometry onto a canvas.

  *size* is a tuple that specifies the dimensions of the canvas the geometry will drawn upon. 
  """
    buf = 50.0

    if not isinstance(g, list):
        g = [g]

    e = _fac.createGeometryCollection(g).getEnvelopeInternal()
    scale = size[0] / e.width if e.width > 0 else sys.maxint
    scale = min(scale, size[1] / e.height) if e.height > 0 else 1

    tx = -1 * e.minX
    ty = -1 * e.minY

    at = AffineTransform()

    # scale to size of canvas (inverting the y axis)
    at.scale(scale, -1 * scale)

    # translate to the origin
    at.translate(tx, ty)

    # translate to account for invert
    at.translate(0, -1 * size[1] / scale)

    # buffer
    at.translate(buf / scale, -1 * buf / scale)

    class Panel(swing.JPanel):
        def __init__(self, geoms, atx):
            self.geoms = geoms
            self.atx = atx

        def paintComponent(self, gc):
            opaque = gc.getComposite()
            gc.setRenderingHint(awt.RenderingHints.KEY_ANTIALIASING,
                                awt.RenderingHints.VALUE_ANTIALIAS_ON)
            gc.setStroke(awt.BasicStroke(2))

            i = 0
            for g in self.geoms:
                shp = LiteShape(g, self.atx, False)

                if isinstance(g, (Polygon, MultiPolygon)):
                    i = i + 1
                    gc.setColor(awt.Color.WHITE)
                    gc.setComposite(
                        awt.AlphaComposite.getInstance(
                            awt.AlphaComposite.SRC_OVER, 0.5))
                    gc.fill(shp)

                gc.setComposite(opaque)
                gc.setColor(awt.Color.BLACK)
                gc.draw(shp)

    panel = Panel(g, at)
    s = tuple([int(size[x] + 2 * buf) for x in range(2)])
    panel.preferredSize = s
    frame = swing.JFrame()
    frame.contentPane = panel
    frame.pack()
    frame.visible = True
Ejemplo n.º 37
0
                #////////////////////////////
                targetImage = images[0]
                targetProcessor = targetImage.getProcessor()
                targetHeight = float(targetProcessor.getHeight())
                targetWidth = float(targetProcessor.getWidth())

                #////////////////////////////
                # Determine scaling information, scaling target image rois to mass images size.
                #////////////////////////////
                scalingHeight = float(targetHeight / height)
                scalingWidth = float(targetHeight / width)

                #////////////////////////////
                # Loop through rois in IJ roi manager, scale them, then add to OpenMIMS images
                #////////////////////////////
                rois = IJRoiManager.getRoisAsArray()
                for i in range(len(rois)):
                    roi = rois[i]
                    polygon = roi.getPolygon()
                    at = AfTransform.getScaleInstance(scalingHeight,
                                                      scalingWidth)
                    roi = ShapeRoi(
                        at.createTransformedShape(polygon)).shapeToRoi()
                    MIMSRoiManager.add(roi)

                #////////////////////////////
                # Update all the images and open the OpenMimsRoi manager
                #////////////////////////////
                ui.updateAllImages()
                MIMSRoiManager.viewManager()
Ejemplo n.º 38
0
                 'EMProject.xml'))  # the high res EM project

afterProjectPath = fc.cleanLinuxPath(
    projectPath.replace('EMProject.', 'ToBeElasticAlignedEMProject.'))
IJ.log('afterProjectPath ' + str(afterProjectPath))

project, loader, layerset, nLayers = fc.openTrakemProject(projectPath)

for l, layer in enumerate(layerset.getLayers()):
    transformPath = os.path.join(
        resultRigidAlignmentFolder,
        'stitchedDownsampledEM_' + str(l).zfill(4) + '.xml')
    aff = fc.getAffFromRVSTransformPath(transformPath)
    # aff.scale(float(downsamplingFactor), float(downsamplingFactor)) # cannot be used because it is not a simple scaling
    aff = AffineTransform(aff.getScaleX(), aff.getShearY(), aff.getShearX(),
                          aff.getScaleY(),
                          aff.getTranslateX() * float(downsamplingFactor),
                          aff.getTranslateY() * float(downsamplingFactor))

    for patch in layer.getDisplayables(Patch):
        currentAff = patch.getAffineTransform()
        currentAff.preConcatenate(aff)
        patch.setAffineTransform(currentAff)
IJ.log(
    'The real EM project is now rigidly aligned. Saving and closing the project.'
)
fc.resizeDisplay(layerset)
project.save()
project.saveAs(afterProjectPath, True)
fc.closeProject(project)
time.sleep(2)