Exemplo n.º 1
0
def classify(img, classifier, class_names, ops=None, distribution_class_index=-1):
  """ img: a 2D RandomAccessibleInterval.
      classifier: a WEKA Classifier instance, like SMO or FastRandomForest, etc. Any.
                  If it's a string, interprets it as a file path and attempts to deserialize
                  a previously saved trained classifier.
      class_names: the list of names of each class to learn.
      ops: the filter bank of ImgMath ops for the img.
      distribution_class_index: defaults to -1, meaning return the class index for each pixel.
                                When larger than -1, it's interpreted as a class index, and
                                returns instead the floating-point value of each pixel in
                                the distribution of that particular class index. """
  if type(classifier) == str:
    classifier = SerializationHelper.read(classifier)

  ops = ops if ops else filterBank(img)
  
  attributes = ArrayList()
  for i in xrange(len(ops)):
    attributes.add(Attribute("attr-%i" % i))
  #for name in classifier.attributeNames()[0][1]:
  #  attributes.add(Attribute(name))
  attributes.add(Attribute("class", class_names))
  
  info = Instances("structure", attributes, 1)
  info.setClassIndex(len(attributes) -1)

  opImgs = [compute(op).into(ArrayImgs.floats([img.dimension(0), img.dimension(1)])) for op in ops]
  cs_opImgs = Views.collapse(Views.stack(opImgs))

  result = ArrayImgs.floats([img.dimension(0), img.dimension(1)])
  cr = result.cursor()
  cop = Views.iterable(cs_opImgs).cursor()

  while cr.hasNext():
    tc = cop.next()
    vector = array((tc.get(i).getRealDouble() for i in xrange(len(opImgs))), 'd')
    vector += array([0], 'd')
    di = DenseInstance(1.0, vector)
    di.setDataset(info) # the list of attributes
    if distribution_class_index > -1:
      cr.next().setReal(classifier.distributionForInstance(di)[distribution_class_index])
    else:
      cr.next().setReal(classifier.classifyInstance(di))

  return result
Exemplo n.º 2
0
	def getManders(self, imp, cell):
	
		### Crop channels according to cell mask
		channels = self.getCroppedChannels(imp, cell)
		if channels is None:
			return None
			
		### Calculate channel thresholds
		thrs = []
		thrimps = []
		for c, method in enumerate(self.methods):
			if method != "None":
				thr, thrimp = self.getThreshold(channels[c], method)
			else:
				thr, thrimp = None, None
			thrs.append(thr)
			thrimps.append(thrimp)
		
		### Calculate manders colocalization
		manders = MandersColocalization()
		raws = []
		thrds = []
		for chA, chB in self.pairs:
			container = self.getContainer(channels[chA - 1], channels[chB - 1])
			img1 = container.getSourceImage1()
			img2 = container.getSourceImage2()
			mask = container.getMask()
			cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor())
			rtype = img1.randomAccess().get().createVariable()
			raw = manders.calculateMandersCorrelation(cursor, rtype)
			rthr1 = rtype.copy()
			rthr2 = rtype.copy()
			rthr1.set(thrs[chA - 1])
			rthr2.set(thrs[chB - 1])
			cursor.reset()
			thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above)
			raws.append(raw)
			thrds.append(thrd)
		
		return (channels, thrimps, thrs, raws, thrds)
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))
Exemplo n.º 4
0
	title = title[:title.rfind('.')]
	image.close()
	preview.close()
	ch1 = ImagePlusAdapter.wrap(imp1)
	ch2 = ImagePlusAdapter.wrap(imp2)

	for roi in rm.getRoisAsArray():
		container = createContainer(roi, ch1, ch2)
		img1 = container.getSourceImage1()
		img2 = container.getSourceImage2()
		mask = container.getMask()
		
		thr1, thrimp1 = calculateThreshold(imp1, roi, methods[0])
		thr2, thrimp2 = calculateThreshold(imp2, roi, methods[1])
		
		cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor())
		rtype = img1.randomAccess().get().createVariable()
		raw = manders.calculateMandersCorrelation(cursor, rtype)
		rthr1 = rtype.copy()
		rthr2 = rtype.copy()
		rthr1.set(thr1)
		rthr2.set(thr2)
		cursor.reset()
		thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above)
		print "Results are: %f %f %f %f" % (raw.m1, raw.m2, thrd.m1, thrd.m2)

		results.incrementCounter()
		rowno = results.getCounter() - 1
		results.setValue("Cell", rowno, int(rowno))
		results.setValue("Threshold 1", rowno, int(thr1))
		results.setValue("Threshold 2", rowno, int(thr2))
Exemplo n.º 5
0
fi.height = 128
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))
def iterableChannel(imgARGB, i):
  return Views.iterable(Converters.argbChannel(imgARGB, i))
Exemplo n.º 7
0
  # Get each step, waiting until all are built
  steps = [f.get() for f in futures] # list: eager, for concatenation below in Views.stack
finally:
  # This 'finally' block executes even in the event of an error
  # guaranteeing that the executing threads will be shut down no matter what.
  exe.shutdown()


# ISSUE: Does not work with IntervalView from View.rotate,
# so img1 and img2 were copied into ArrayImg
# (The error would occur when iterating vol4d pixels beyond the first element in the 4th dimension.)
vol4d = Views.stack([img1] + steps + [img2])

# Convert 1 -> 255 for easier volume rendering in 3D Viewer
#compute(mul(vol4d, 255)).into(vol4d)
for t in Views.iterable(vol4d):
  if 0 != t.getByte():
    t.setReal(255)

# Construct an ij.VirtualStack from vol4d
virtualstack = IL.wrap(vol4d, "interpolations").getStack()
imp = ImagePlus("interpolations", virtualstack)
imp.setDimensions(1, vol4d.dimension(2), vol4d.dimension(3))
imp.setDisplayRange(0, 255)
# Show as a hyperstack with 4 dimensions, 1 channel
com = CompositeImage(imp, CompositeImage.GRAYSCALE)
com.show()

# Show rendered volumes in 4D viewer: 3D + time axis
univ = Image3DUniverse()
univ.show()