Example #1
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
Example #2
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)
Example #3
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
Example #4
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]))
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()
Example #6
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)
Example #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)
Example #8
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
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")
Example #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))
Example #11
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
Example #12
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())
Example #13
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)
Example #14
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
Example #15
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
Example #16
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(
Example #17
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")
Example #18
0
 def turn(self, angle):
     t = AffineTransform()
     t.rotate(angle)
     self.tri1.transform(t)
     self.tri2.transform(t)
Example #19
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)
Example #20
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