Exemple #1
0
def makeInterpolatedImage(img1, img2, weight):
    """ weight: float between 0 and 1 """
    edge_pix1 = findEdgePixels(img1)
    kdtree1 = KDTree(edge_pix1, edge_pix1)
    search1 = NearestNeighborSearchOnKDTree(kdtree1)
    edge_pix2 = findEdgePixels(img2)
    kdtree2 = KDTree(edge_pix2, edge_pix2)
    search2 = NearestNeighborSearchOnKDTree(kdtree2)
    img3 = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img1))
    c1 = img1.cursor()
    c2 = img2.cursor()
    c3 = img3.cursor()
    pos = zeros(img1.numDimensions(), 'l')
    while c3.hasNext():
        t1 = c1.next()
        t2 = c2.next()
        t3 = c3.next()
        sign1 = -1 if 0 == t1.get() else 1
        sign2 = -1 if 0 == t2.get() else 1
        search1.search(c1)
        search2.search(c2)
        value1 = sign1 * search1.getDistance() * weight
        value2 = sign2 * search2.getDistance() * (1 - weight)
        if value1 + value2 > 0:
            t3.setOne()
    return img3
    def asNormalizedUnsignedByteArrayImg(interval, invert, blockRadius, n_bins,
                                         slope, matrices, copy_threads, index,
                                         imp):
        sp = imp.getProcessor()  # ShortProcessor
        sp.setRoi(interval.min(0), interval.min(1),
                  interval.max(0) - interval.min(0) + 1,
                  interval.max(1) - interval.min(1) + 1)
        sp = sp.crop()
        if invert:
            sp.invert()
        CLAHE.run(
            ImagePlus("", sp), blockRadius, n_bins, slope, None
        )  # far less memory requirements than NormalizeLocalContrast, and faster.
        minimum, maximum = autoAdjust(sp)

        # Transform and convert image to 8-bit, mapping to display range
        img = ArrayImgs.unsignedShorts(
            sp.getPixels(), [sp.getWidth(), sp.getHeight()])
        sp = None
        affine = AffineTransform2D()
        affine.set(matrices[index])
        imgI = Views.interpolate(Views.extendZero(img),
                                 NLinearInterpolatorFactory())
        imgA = RealViews.transform(imgI, affine)
        imgT = Views.zeroMin(Views.interval(imgA, img))
        imgMinMax = convert(imgT, RealUnsignedByteConverter(minimum, maximum),
                            UnsignedByteType)
        aimg = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img))
        ImgUtil.copy(ImgView.wrap(imgMinMax, aimg.factory()), aimg,
                     copy_threads)
        img = imgI = imgA = imgT = imgMinMax = None
        return aimg
Exemple #3
0
def asNormalizedUnsignedByteArrayImg(blockRadius, stds, center, stretch, imp):
    sp = imp.getProcessor()  # ShortProcessor
    NormalizeLocalContrast().run(sp, blockRadius, blockRadius, stds, center,
                                 stretch)
    return ArrayImgs.unsignedBytes(
        sp.convertToByte(True).getPixels(),
        [sp.getWidth(), sp.getHeight()])
Exemple #4
0
def readBinaryMaskImg(filepath, width, height, depth, header_size):
  ra = RandomAccessFile(filepath, 'r')
  try:
    ra.skipBytes(header_size)
    bytes = zeros(width * height * depth, 'b')
    ra.read(bytes)
    return ArrayImgs.unsignedBytes(bytes, [width, height, depth])
  finally:
    ra.close()
Exemple #5
0
def read2DImageROI(path, dimensions, interval, pixelType=UnsignedShortType, header=0, byte_order=ByteOrder.LITTLE_ENDIAN):
  """ Read a region of interest (the interval) of an image in a file.
      Assumes the image is written with the first dimension moving slowest.

      path: the file path to the image file.
      dimensions: a sequence of integer values e.g. [512, 512, 512]
      interval: two sequences of integer values defining the min and max coordinates, e.g.
                [[20, 0], [400, 550]]
      pixeltype: e.g. UnsignedShortType, FloatType
      header: defaults to zero, the number of bytes between the start of the file and the start of the image data.

      Supports only these types: UnsignedByteType, UnsignedShortType, FloatType.

      Returns an ArrayImg of the given type.
  """
  ra = RandomAccessFile(path, 'r')
  try:
    width, height = dimensions
    minX, minY = interval[0]
    maxX, maxY = interval[1]
    roi_width, roi_height = maxX - minX + 1, maxY - minY + 1
    tailX = width - roi_width - minX

    #print minX, minY
    #print maxX, maxY
    #print roi_width, roi_height

    size = roi_width * roi_height
    n_bytes_per_pixel = pixelType().getBitsPerPixel() / 8

    #print n_bytes_per_pixel

    bytes = zeros(size * n_bytes_per_pixel, 'b')

    # Read only the 2D ROI
    ra.seek(header + (minY * width + minX) * n_bytes_per_pixel)
    for h in xrange(roi_height):
      ra.readFully(bytes, h * roi_width * n_bytes_per_pixel, roi_width * n_bytes_per_pixel)
      ra.skipBytes((tailX + minX) * n_bytes_per_pixel)
    # Make an image
    roiDims = [roi_width, roi_height]
    if UnsignedByteType == pixelType:
      return ArrayImgs.unsignedBytes(bytes, roiDims)
    if UnsignedShortType == pixelType:
      shorts = zeros(size, 'h')
      ByteBuffer.wrap(bytes).order(byte_order).asShortBuffer().get(shorts)
      return ArrayImgs.shorts(shorts, roiDims)
    if FloatType == pixelType:
      floats = zeros(size, 'f')
      ByteBuffer.wrap(bytes).order(byte_order).asFloatBuffer().get(floats)
      return ArrayImgs.floats(floats, roiDims)
  finally:
    ra.close()
Exemple #6
0
def readUnsignedBytes(path, dimensions, header=0):
    """ Read a file as an ArrayImg of UnsignedShortType """
    ra = RandomAccessFile(path, 'r')
    try:
        if header < 0:
            # Interpret from the end: useful for files with variable header lengths
            # such as some types of uncompressed TIFF formats
            header = ra.length() + header
        ra.skipBytes(header)
        bytes = zeros(reduce(operator.mul, dimensions), 'b')
        ra.read(bytes)
        return ArrayImgs.unsignedBytes(bytes, dimensions)
    finally:
        ra.close()
    def asNormalizedUnsignedByteArrayImg(interval, invert, blockRadius, n_bins,
                                         slope, matrices, index, imp):
        sp = imp.getProcessor()  # ShortProcessor
        # Crop to interval if needed
        x = interval.min(0)
        y = interval.min(1)
        width = interval.max(0) - interval.min(0) + 1
        height = interval.max(1) - interval.min(1) + 1
        if 0 != x or 0 != y or sp.getWidth() != width or sp.getHeight(
        ) != height:
            sp.setRoi(x, y, width, height)
            sp = sp.crop()

        if invert:
            sp.invert()

        CLAHE.run(
            ImagePlus("", sp), blockRadius, n_bins, slope, None
        )  # far less memory requirements than NormalizeLocalContrast, and faster.
        minimum, maximum = autoAdjust(sp)

        # Transform and convert image to 8-bit, mapping to display range
        img = ArrayImgs.unsignedShorts(
            sp.getPixels(), [sp.getWidth(), sp.getHeight()])
        sp = None
        imp = None
        # Must use linear interpolation for subpixel precision
        affine = AffineTransform2D()
        affine.set(matrices[index])
        imgI = Views.interpolate(Views.extendZero(img),
                                 NLinearInterpolatorFactory())
        imgA = RealViews.transform(imgI, affine)
        imgT = Views.zeroMin(Views.interval(imgA, img))
        # Convert to 8-bit
        imgMinMax = convert2(imgT,
                             RealUnsignedByteConverter(minimum, maximum),
                             UnsignedByteType,
                             randomAccessible=False)  # use IterableInterval
        aimg = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img))
        # ImgUtil copies multi-threaded, which is not appropriate here as there are many other images being copied too
        #ImgUtil.copy(ImgView.wrap(imgMinMax, aimg.factory()), aimg)

        # Single-threaded copy
        copier = createBiConsumerTypeSet(UnsignedByteType)
        LoopBuilder.setImages(imgMinMax, aimg).forEachPixel(copier)

        img = imgI = imgA = imgMinMax = imgT = None
        return aimg
Exemple #8
0
def makeInterpolatedImage(img1, search1, img2, search2, weight):
  """ weight: float between 0 and 1 """
  img3 = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img1))
  c1 = img1.cursor()
  c2 = img2.cursor()
  c3 = img3.cursor()
  while c3.hasNext():
    t1 = c1.next()
    t2 = c2.next()
    t3 = c3.next()
    sign1 = -1 if 0 == t1.get() else 1
    sign2 = -1 if 0 == t2.get() else 1
    search1.search(c1)
    search2.search(c2)
    value1 = sign1 * search1.getDistance() * (1 - weight)
    value2 = sign2 * search2.getDistance() * weight
    if value1 + value2 > 0:
      t3.setOne()
  return img3
Exemple #9
0
# Load the facc and cw classes
loader = CustomClassLoader()
accessClass = loader.defineClass("my/UnsignedByteToFloatAccess",
                                 facc.toByteArray())
samplerClass = loader.defineClass("my/UnsignedByteToFloatSamplerConverter",
                                  cw.toByteArray())

# Test SamplerConverter:
from net.imglib2.img.array import ArrayImgs
from net.imglib2.converter import Converters
from net.imglib2.util import ImgUtil
from net.imglib2.img import ImgView

dimensions = [100, 100, 100]
img1 = ArrayImgs.unsignedBytes(dimensions)
c = img1.cursor()
while c.hasNext():
    c.next().setOne()
img2 = ArrayImgs.floats(dimensions)


def testASM():
    ImgUtil.copy(
        ImgView.wrap(
            Converters.convertRandomAccessibleIterableInterval(
                img1, samplerClass.newInstance()), img1.factory()), img2)


timeit(20, testASM)
from net.imglib2.img.array import ArrayImgs
from net.imglib2.view import Views
from net.imglib2.type.numeric.integer import UnsignedByteType

img1 = ArrayImgs.unsignedBytes([10, 10, 10])
img2 = ArrayImgs.unsignedBytes([10, 10, 10])

stack = Views.stack([img1, img2])

for t in Views.iterable(stack):
    t.setReal(1)

assert 1000 + 1000 == sum(t.get() for t in Views.iterable(stack))
Exemple #11
0
        c.fwd()
        c.localize(pos)
        print "Cursor:", pos, "::", c.get()

    # Test RandomAccess
    ra = iraf.randomAccess()
    c = iraf.cursor()
    while c.hasNext():
        c.fwd()
        ra.setPosition(c)
        c.localize(pos)
        print "RandomAccess:", pos, "::", ra.get()

    # Test source img: should be untouched
    c = img.cursor()
    while c.hasNext():
        print "source:", c.next()

    # Test interval view: the middle 2x2 square
    v = Views.interval(iraf, [1, 1], [2, 2])
    IL.wrap(v, "+2 view").show()


# An array from 0 to 15
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
pixels = array(a, 'b')
img = ArrayImgs.unsignedBytes(pixels, [4, 4])

test(add(img, 2).view())
test(add(img, 2).view(FloatType()))
Exemple #12
0
IL.wrap(img_sub, "LoopBuilder").show()
"""

# Example 2b: with ImgLib2 LoopBuilder using a clojure-defined TriConsumer
from net.imglib2.img.display.imagej import ImageJFunctions as IL
from net.imglib2.converter import Converters
from net.imglib2.img.array import ArrayImgs
from net.imglib2.util import Intervals
from net.imglib2.loops import LoopBuilder
from org.scijava.plugins.scripting.clojure import ClojureScriptEngine

img = IL.wrap(imp_rgb) # an ARGBType Img
red   = Converters.argbChannel(img, 1) # a view of the ARGB red channel
green = Converters.argbChannel(img, 2) # a view of the ARGB green channel
img_sub = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img))    # the img to store the result

code = """
(deftype Consumer [^long threshold]
  %s
  (accept [self red green result] ; can't type-hint, doesn't find matching method
    (let [^%s r red
          ^%s g green
          ^%s s result]
      (.setInteger s (if (>= (.getInteger r) threshold)
                       (.getInteger g)
                       0)))))
""" % ((LoopBuilder.TriConsumer.getName(),) \
      + tuple(a.randomAccess().get().getClass().getName() for a in [red, green, img_sub]))

clj = ClojureScriptEngine()
# in the VIB's vib.BinaryInterpolator class, for ij.ImagePlus.
#
#
# Note that a java-based implementation would be significantly faster.

from net.imglib2.img.array import ArrayImgs
from org.scijava.vecmath import Point3f
from net.imglib2.img.display.imagej import ImageJFunctions as IL
from net.imglib2.view import Views
from net.imglib2.type.numeric.integer import UnsignedByteType
from jarray import zeros
from net.imglib2.algorithm.morphology.distance import DistanceTransform


# First 3D mask: a sphere
img1 = ArrayImgs.unsignedBytes([100, 100, 100])
p = zeros(3, 'l')
cursor = img1.cursor()
middle = Point3f(49.5,49.5, 49.5)
distance_sq = float(30 * 30)

while cursor.hasNext():
  cursor.fwd()
  cursor.localize(p)
  if middle.distanceSquared(Point3f(p[0], p[1], p[2])) < distance_sq:
    cursor.get().setOne()
  else:
    cursor.get().setZero()

imp1 = IL.wrap(img1, "sphere")
imp1.setDisplayRange(0, 1)
Exemple #14
0
from ij import IJ
from net.imglib2.view import Views
from net.imglib2.realtransform import AffineTransform3D, RealViews
from net.imglib2.interpolation.randomaccess import NLinearInterpolatorFactory
from net.imglib2.img.array import ArrayImgs
from jarray import zeros
from math import sqrt
import sys
sys.path.append("/home/albert/lab/scripts/python/imagej/IsoView-GCaMP")
from lib.ui import showAsStack, makeTranslationUI
from lib.util import affine3D

# Create a [100,100,100] image with a sphere of radius 20 at the center
aimg = ArrayImgs.unsignedBytes([10, 10, 10])
c = aimg.cursor()
pos = zeros(3, 'l')
while c.hasNext():
    t = c.next()
    c.localize(pos)
    v = sqrt(sum(pow(p - 5, 2) for p in pos))
    if v < 2:
        t.setReal(255)


# Use the image to represent a channel
# Transform each channel independently
def identity():
    return affine3D([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0])


aff1 = identity()
Exemple #15
0
# @UIService ui

import net.imglib2.img.array.ArrayImgs as ArrayImgs
import bdv.util.BdvFunctions as BdvFunctions

import random as random

w = 101
h = w
d = w

img = ArrayImgs.unsignedBytes(w, h, d)
img_ra = img.randomAccess()

for x in range(0, w):
    for y in range(0, h):
        for z in range(0, d):
            img_ra.setPosition(x, 0)
            img_ra.setPosition(y, 1)
            img_ra.setPosition(z, 2)

            xo = x - 50
            yo = y - 50
            zo = z - 50

            val = 255 - ( xo**2 + yo**2 + zo**2 ) ** 0.65

            img_ra.get().setReal(int(val))

print('done')
Exemple #16
0
 def __init__(self, width, height, n, scale, offset):
     super(VirtualStack, self).__init__(width, height, n)
     self.scale = scale
     self.offset = offset
     self.img = ArrayImgs.unsignedBytes([width, height])
     self.bytes = self.img.update(None).getCurrentStorageArray()
Exemple #17
0
    ra.read(bytes)
    return ArrayImgs.unsignedBytes(bytes, [width, height, depth])
  finally:
    ra.close()

bird = readBinaryMaskImg(os.path.join(baseDir, "birdsIm/b21.im"), 128, 128, 128, 1024)
airplane = readBinaryMaskImg(os.path.join(baseDir, "airplanesIm/b14.im"), 128, 128, 128, 1024)

# Rotate bird: starts with posterior view, dorsal down
# Rotate 180 degrees around Y axis
birdY90 = Views.rotate(bird, 2, 0) # 90
birdY180 = Views.rotate(birdY90, 2, 0) # 90 again: 180

# Copy rotated bird into ArrayImg
dims = Intervals.dimensionsAsLongArray(birdY90)
img1 = compute(ImgSource(birdY180)).into(ArrayImgs.unsignedBytes(dims))

# Rotate airplane: starts with dorsal view, anterior down
# Set to: coronal view, but dorsal is still down
airplaneC = Views.rotate(airplane, 2, 1)
# Set to dorsal up: rotate 180 degrees
airplaneC90 = Views.rotate(airplaneC, 0, 1) # 90
airplaneC180 = Views.rotate(airplaneC90, 0, 1) # 90 again: 180

# Copy rotated airplace into ArrayImg
img2 = compute(ImgSource(airplaneC180)).into(ArrayImgs.unsignedBytes(dims))


# Find edges
def findEdgePixels(img):
  edge_pix = []
from net.imglib2.img.array import ArrayImgs
from time import time
from itertools import imap
from collections import deque
from net.imglib2.util.Util import getTypeFromInterval
from org.scijava.plugins.scripting.clojure import ClojureScriptEngine
from net.imglib2.type.numeric.integer import UnsignedByteType
from net.imglib2.type.operators import SetOne
from java.util.function import Predicate, Consumer, Function
from java.lang.invoke import MethodHandles, MethodType, LambdaMetafactory
from java.lang import Void
import sys
from org.objectweb.asm import ClassWriter, Opcodes
from java.lang import Object, ClassLoader, String, Class, Integer

img = ArrayImgs.unsignedBytes([512, 512, 5])

n_iterations = 4

# Test 1: for loop
for i in xrange(n_iterations):
    t0 = time()
    for t in img.cursor():
        t.setOne()
    t1 = time()
    print "looping:", t1 - t0  # About 1 seconds

# Test 2: imap + deque with maxlen=0
for i in xrange(n_iterations):
    t0 = time()
    # Performance almost as bad as the for loop
fi.nImages = 128

baseDir = "/home/albert/lab/scripts/data/cim.mcgill.ca-shape-benchmark/"

bird = IL.wrap(Raw.open(baseDir + "/birdsIm/b21.im", fi))
airplane = IL.wrap(Raw.open(baseDir + "/airplanesIm/b14.im", fi))

# Rotate bird
# Starts with posterior view
# Rotate 180 degrees around Y axis
# Set to dorsal up: 180 degrees
birdY90 = Views.rotate(bird, 2, 0)  # 90
birdY180 = Views.rotate(birdY90, 2, 0)  # 90 again: 180

c1 = Views.iterable(birdY180).cursor()
img1 = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(birdY180))
c2 = img1.cursor()
while c2.hasNext():
    c2.next().set(c1.next())

# Rotate airplane
# Starts with dorsal view, anterior down
# Set to: coronal view, but dorsal is down
airplaneC = Views.rotate(airplane, 2, 1)
# Set to dorsal up: 180 degrees
airplaneC90 = Views.rotate(airplaneC, 0, 1)  # 90
airplaneC180 = Views.rotate(airplaneC90, 0, 1)  # 90 again: 180

c1 = Views.iterable(airplaneC180).cursor()
img2 = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(airplaneC180))
c2 = img2.cursor()
Exemple #20
0
from net.imglib2.converter import Converters
from net.imglib2.converter import RealFloatConverter
from net.imglib2.type.numeric.real import FloatType
from net.imglib2.view import Views


imp = IJ.getImage()
dimensions = [imp.getWidth(), imp.getHeight()]
ip = imp.getProcessor()
pixels = ip.getPixels()

# In practice, you never want to do this below,
# and instead you'd use the built-in wrapper: ImageJFunctions.wrap(imp)
# This is merely for illustration of how to use ArrayImgs with an existing pixel array
if isinstance(ip, ByteProcessor):
  img1 = ArrayImgs.unsignedBytes(pixels, dimensions)
elif isinstance(ip, ShortProcessor):
  img1 = ArrayImgs.unsignedShorts(pixels, dimensions)
elif isinstance(ip, FloatProcessor):
  img1 = ArrayImgs.floats(pixels, dimensions)
else:
  print "Can't handle image of type:", type(ip).getName()


# An empty image of float[]
img2 = ArrayImgs.floats(dimensions)

# View it as RandomAccessibleInterval<FloatType> by converting on the fly
# using a generic RealType to FloatType converter
floatView = Converters.convertRAI(img1, RealFloatConverter(), FloatType())
Exemple #21
0
from net.imglib2.algorithm.math.ImgMath import compute, gen
from net.imglib2.img.display.imagej import ImageJFunctions as IL
from net.imglib2.type.numeric.integer import UnsignedByteType
from net.imglib2.img.array import ArrayImgs
from net.imglib2.util import Intervals
from net.imglib2 import KDTree, Point

locations = [(10, 15), (25, 40), (30, 75), (80, 60)]

points = [
    Point.wrap([x, y]) for x, y in [(10, 15), (25, 40), (30, 75), (80, 60)]
]
values = [UnsignedByteType(v) for v in [128, 164, 200, 255]]

kt = KDTree(values, points)
dimensions = [100, 100]

op = gen(kt, 10)
target = ArrayImgs.unsignedBytes(
    Intervals.dimensionsAsLongArray(op.getInterval()))
compute(op).into(target)

IL.wrap(target, "KDTree").show()
Exemple #22
0
def draw(dimensions, scale, offset):
    img = ArrayImgs.unsignedBytes(dimensions)
    M.into(MandelbrotRealRandomAccess(), img.cursor(), scale, offset)
    return img
        b = ArrayImgs.floats(bb, [width, height])
        #print "ArrayImg:", b.iterationOrder()
        ImgUtil.copy(ImgView.wrap(hue.view(FloatType()), None), h)
        ImgUtil.copy(ImgView.wrap(saturation.view(FloatType()), None), s)
        ImgUtil.copy(ImgView.wrap(brightness.view(FloatType()), None), b)
        stack = ImageStack(width, height)
        stack.addSlice(FloatProcessor(width, height, hb, None))
        stack.addSlice(FloatProcessor(width, height, sb, None))
        stack.addSlice(FloatProcessor(width, height, bb, None))
        imp = ImagePlus("hsb", stack)
    return imp


# For the test, transfer converted views into arrays
ared = compute(img(red)).into(
    ArrayImgs.unsignedBytes([rgb.dimension(0),
                             rgb.dimension(1)]))
agreen = compute(img(green)).into(
    ArrayImgs.unsignedBytes([rgb.dimension(0),
                             rgb.dimension(1)]))
ablue = compute(img(blue)).into(
    ArrayImgs.unsignedBytes([rgb.dimension(0),
                             rgb.dimension(1)]))


def timeit(fn, *args, **kwargs):
    n_iterations = 20
    times = []
    for i in xrange(n_iterations):
        t0 = System.nanoTime()
        imp = fn(*args, **kwargs)
        t1 = System.nanoTime()