def maxProject(image, chan):
    proj = ShortProcessor(image.getWidth(), image.getHeight())
    stack = image.getStack()
    for z in range(1, imp.getNSlices() + 1):
        ip = stack.getProcessor(image.getStackIndex(chan, z, 1))
        proj.copyBits(ip, 0, 0, Blitter.MAX)
    return proj
Example #2
0
def extract_stack_under_arealist():
    # Check that a Display is open
    display = Display.getFront()
    if display is None:
        IJ.log("Open a TrakEM2 Display first!")
        return
    # Check that an AreaList is selected and active:
    ali = display.getActive()
    if ali is None or not isinstance(ali, AreaList):
        IJ.log("Please select an AreaList first!")
        return

    # Get the range of layers to which ali paints:
    ls = display.getLayerSet()
    ifirst = ls.indexOf(ali.getFirstLayer())
    ilast = ls.indexOf(ali.getLastLayer())
    layers = display.getLayerSet().getLayers().subList(ifirst, ilast + 1)

    # Create a stack with the dimensions of ali
    bounds = ali.getBoundingBox()
    stack = ImageStack(bounds.width, bounds.height)

    # Using 16-bit. To change to 8-bit, use GRAY8 and ByteProcessor in the two lines below:
    type = ImagePlus.GRAY16
    ref_ip = ShortProcessor(bounds.width, bounds.height)

    for layer in layers:
        area = ali.getArea(layer)
        z = layer.getZ()
        ip = ref_ip.createProcessor(bounds.width, bounds.height)
        if area is None:
            stack.addSlice(str(z), bp)
            continue

        # Create a ROI from the area of ali at layer:
        aff = ali.getAffineTransformCopy()
        aff.translate(-bounds.x, -bounds.y)
        roi = ShapeRoi(area.createTransformedArea(aff))

        # Create a cropped snapshot of the images at layer under ali:
        flat = Patch.makeFlatImage(type, layer, bounds, 1.0,
                                   layer.getDisplayables(Patch), Color.black)
        b = roi.getBounds()
        flat.setRoi(roi)
        ip.insert(flat.crop(), b.x, b.y)

        # Clear the outside of ROI (ShapeRoi is a non-rectangular ROI type)
        bimp = ImagePlus("", ip)
        bimp.setRoi(roi)
        ip.setValue(0)
        ip.setBackgroundValue(0)
        IJ.run(bimp, "Clear Outside", "")

        # Accumulate slices
        stack.addSlice(str(z), ip)

    imp = ImagePlus("AreaList stack", stack)
    imp.setCalibration(ls.getCalibrationCopy())
    imp.show()
def extract_stack_under_arealist():
	# Check that a Display is open
	display = Display.getFront()
	if display is None:
		IJ.log("Open a TrakEM2 Display first!")
		return
	# Check that an AreaList is selected and active:
	ali = display.getActive()
	if ali is None or not isinstance(ali, AreaList):
		IJ.log("Please select an AreaList first!")
		return

	# Get the range of layers to which ali paints:
	ls = display.getLayerSet()
	ifirst = ls.indexOf(ali.getFirstLayer())
	ilast = ls.indexOf(ali.getLastLayer())
	layers = display.getLayerSet().getLayers().subList(ifirst, ilast +1)

	# Create a stack with the dimensions of ali
	bounds = ali.getBoundingBox()
	stack = ImageStack(bounds.width, bounds.height)

	# Using 16-bit. To change to 8-bit, use GRAY8 and ByteProcessor in the two lines below:
	type = ImagePlus.GRAY16
	ref_ip = ShortProcessor(bounds.width, bounds.height)

	for layer in layers:
		area = ali.getArea(layer)
		z = layer.getZ()
		ip = ref_ip.createProcessor(bounds.width, bounds.height)
		if area is None:
			stack.addSlice(str(z), bp)
			continue

		# Create a ROI from the area of ali at layer:
		aff = ali.getAffineTransformCopy()
		aff.translate(-bounds.x, -bounds.y)
		roi = ShapeRoi(area.createTransformedArea(aff))

		# Create a cropped snapshot of the images at layer under ali:
		flat = Patch.makeFlatImage(type, layer, bounds, 1.0, layer.getDisplayables(Patch), Color.black)
		b = roi.getBounds()
		flat.setRoi(roi)
		ip.insert(flat.crop(), b.x, b.y)

		# Clear the outside of ROI (ShapeRoi is a non-rectangular ROI type)
		bimp = ImagePlus("", ip)
		bimp.setRoi(roi)
		ip.setValue(0)
		ip.setBackgroundValue(0)
		IJ.run(bimp, "Clear Outside", "")

		# Accumulate slices
		stack.addSlice(str(z), ip)

	imp = ImagePlus("AreaList stack", stack)
	imp.setCalibration(ls.getCalibrationCopy())
	imp.show()
Example #4
0
	def __end(self, event): 
		if len(self.__iplist)==0 : 
			IJ.showMessage("", "Stack is empty")
			return

		self.__iplist.sort(key = lambda ip : ip.width)
		
		self.__ipw=[ ip.getWidth() for ip in self.__iplist ]
		self.__iph=[ ip.getHeight() for ip in self.__iplist ]
		maxw=max(self.__ipw)
		maxh=max(self.__iph)
		if self.__enlarge : 
			resizelist = [ ip.resize(maxw, maxh, True) for ip in self.__iplist ]
			
		else : 
			resizelist = []
			for ip in self.__iplist :
				tempip = ShortProcessor(maxw, maxh)
				xloc = int(math.floor((maxw/2.00) - (ip.width/2.00)))
				yloc = int(math.floor((maxh/2.00) - (ip.height/2.00)))
				tempip.copyBits(ip, xloc, yloc, Blitter.COPY)
				resizelist.append(tempip)
		ims = ImageStack(maxw, maxh) 	

		#for ip in resizelist : ims.addSlice("", ip)
		for i in range(len(resizelist)) : 
			ims.addSlice(self.__labels[i], resizelist[i])
		
		
		self.__impRes = ImagePlus(self.__name, ims)
		self.__impRes.show()

		self.__sens = [1 for i in range(len(self.__iplist)) ]
		
		if self.__appmedian : IJ.run(self.__impRes, "Median...", "radius=1 stack")
		if self.__align : self.__falign()
		if self.__avg : self.__favg()
		if self.__mosa : self.__fmosa()
		if self.__maxfinder : self.__fmaxfinder()
		if self.__fire : IJ.run(self.__impRes, "Fire", "")
		if self.__measures : self.__fmeasures()
		
		self.__sens[:] = []
		
		self.__listrois[:] = []
		self.__iplist[:] = []
		self.__cellsrois[:] = []
		self.__ipw[:] = []
		self.__iph[:] = []

		self.__init = False
Example #5
0
def createLabelColorBar():

    imp7 = ImagePlus("labelColorBar", ShortProcessor(180, 20))
    ip7 = imp7.getProcessor()
    pix = ip7.getPixels()
    n_pixels = len(pix)
    # catch width
    w = imp7.getWidth()
    # create a ramp gradient from left to right
    for i in range(len(pix)):
        pix[i] = int((i % w) / 18) + 1

    # adjust min and max
    ip7.setMinAndMax(0, 255)
    font = Font("SansSerif", Font.PLAIN, 12)
    overlay = Overlay()
    for i in range(len(pix)):

        roi = TextRoi(i * 18 + 2, 2, str(i + 1), font)
        roi.setStrokeColor(Color.black)
        overlay.add(roi)
        imp7.setOverlay(overlay)

    imp7.show()
    IJ.run("glasbey_on_dark")
    imp7 = imp7.flatten()

    return imp7
Example #6
0
def readFIBSEMdat(path, channel_index=-1, header=1024, magic_number=3555587570, asImagePlus=False, toUnsigned=True):
  """ Read a file from Shan Xu's FIBSEM software, where two or more channels are interleaved.
      Assumes channels are stored in 16-bit.
      
      path: the file path to the .dat file.
      channel_index: the 0-based index of the channel to parse, or -1 (default) for all.
      header: defaults to a length of 1024 bytes
      magic_number: defaults to that for version 8 of Shan Xu's .dat image file format.
      isSigned: defaults to True, will subtract the min value when negative.
      asImagePlus: return a list of ImagePlus instead of ArrayImg which is the default.
  """
  ra = RandomAccessFile(path, 'r')
  try:
    # Check the magic number
    ra.seek(0)
    magic = ra.readInt() & 0xffffffff
    if magic != magic_number:
      msg = "magic number mismatch: v8 magic " + str(magic_number) + " != " + str(magic) + " for path:\n" + path
      System.out.println(msg)
      print msg
      # Continue: attempt to parse the file anyway
    # Read the number of channels
    ra.seek(32)
    numChannels = ra.readByte() & 0xff # a single byte as unsigned integer
    # Parse width and height
    ra.seek(100)
    width = ra.readInt()
    ra.seek(104)
    height = ra.readInt()
    # Read the whole interleaved pixel array
    ra.seek(header)
    bytes = zeros(width * height * 2 * numChannels, 'b') # 2 for 16-bit
    ra.read(bytes)
    # Parse as 16-bit array
    sb = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asShortBuffer()
    bytes = None
  finally:
    ra.close()
  #
  shorts = zeros(width * height * numChannels, 'h')
  sb.get(shorts)
  sb = None
  # Deinterleave channels and convert to unsigned short
  # Shockingly, these values are signed shorts, not unsigned! (for first popeye2 squid volume, December 2021)
  # With ASM: fast
  channels = DAT_handler.deinterleave(shorts, numChannels, channel_index)
  shorts = None
  #
  if toUnsigned:
    for s in channels:
      DAT_handler.toUnsigned(s)
  # With python array sampling: very slow, and not just from iterating whole array once per channel
  #seq = xrange(numChannels) if -1 == channel_index else [channel_index]
  #channels = [shorts[i::numChannels] for i in seq]
  if asImagePlus:
    return [ImagePlus(str(i), ShortProcessor(width, height, s, None)) for i, s in enumerate(channels)]
  else:
    return [ArrayImgs.unsignedShorts(s, [width, height]) for s in channels]
Example #7
0
    def renderPreview(self, runStats):
        try:
            self.labelPreviewImp.close()
            self.maxZPreviewImp.close()
            self.maxYPreviewImp.close()
        except:
            print "imps already closed"

        fp = ShortProcessor(len(self.labelValues), 1, self.labelValues, None)
        labelerImp = ImagePlus("labeler", fp)
        src2 = clij2.push(labelerImp)
        dst = clij2.create(self.src)
        labelerImp.close()

        clij2.replaceIntensities(self.src, src2, dst)
        self.labelPreviewImp = clij2.pull(dst)
        previewDisplaySettings(self.labelPreviewImp, "label preview", 100,
                               self.cal)

        try:
            self.labelPreviewImp.setSlice(self.current)
        except:
            pass
        if runStats:
            clij2.statisticsOfBackgroundAndLabelledPixels(
                dst, self.src, self.results)
        dst2 = clij2.create(width, height, 1)
        clij2.maximumZProjection(dst, dst2)
        self.maxZPreviewImp = clij2.pull(dst2)
        previewDisplaySettings(self.maxZPreviewImp, "maxZ label preview", 50,
                               self.cal)

        dst3 = clij2.create(width, depth, 1)
        clij2.maximumYProjection(dst, dst3)
        self.maxYPreviewImp = clij2.pull(dst3)
        previewDisplaySettings(self.maxYPreviewImp, "maxY label preview", 50,
                               self.cal)

        dst3.close()
        dst.close()
        dst2.close()
        src2.close()

        labelWindow = self.labelPreviewImp.getWindow()
        x = labelWindow.getLocation().x
        y = labelWindow.getLocation().y

        maxZPreviewWindow = self.maxZPreviewImp.getWindow()
        maxZPreviewWindow.setLocation(x, y + height + 50)
        maxYPreviewWindow = self.maxYPreviewImp.getWindow()
        maxYPreviewWindow.setLocation(x + width / 2, y + height + 50)
        print labelWindow
 def getProcessor(self, n):
     return ShortProcessor(self.dimensions[0], self.dimensions[1],
                           self.getPixels(n), None)
Example #9
0
s = 300

pathh = "C:\\Users\\USER\\Documents\\studia\\zaklad\\EC_rainbow\\"
segmentator = WekaSegmentation()
segmentator.loadClassifier(pathh)

for i in range(len(channels)):
    channel = channels[i]
    pix = channel.getProcessor().getPixels()
    cm = channel.getProcessor().getColorModel()
    pix1 = pix[:((lim1 + s) * d1)]
    pix2 = pix[((lim1 - s) * d1):((lim2 + s) * d1)]
    pix3 = pix[((lim2 - s) * d1):((lim3 + s) * d1)]
    pix4 = pix[((lim3 - s) * d1):]
    imps = [
        ImagePlus("Random", ShortProcessor(d1, (lim1 + s), pix1, cm)),
        ImagePlus("Random", ShortProcessor(d1, (lim2 - lim1 + 2 * s), pix2,
                                           cm)),
        ImagePlus("Random", ShortProcessor(d1, (lim3 - lim2 + 2 * s), pix3,
                                           cm)),
        ImagePlus("Random",
                  ShortProcessor(d1, (dimentions[1] - lim3 + s), pix4, cm))
    ]
    subsub = sub + "\\C" + str(i + 1)
    del pix1
    del pix2
    del pix3
    del pix4
    if not os.path.exists(subsub):
        os.mkdir(subsub)
    pixels = []
	except: 
		print i

rt.show(resultsName+ " with labels")
clij2.clear()
labelColorBarImp.close()
imp1Stats=imp1.getStatistics()
print imp1Stats.max
tracked=[11]*int(65535)
for i,v in enumerate(test.labelValues):
	if value not in test.errors:
		tracked[i]= v
	else:
		tracked[i]= 11
print test.labelValues
fp= ShortProcessor(len(tracked), 1,tracked , None)

labelerImp= ImagePlus("labeler", fp)
src2=clij2.push(labelerImp)
conLabeledStack=ImageStack(imp1.width, imp1.height)


if frames>1:
	for nFrame in range(1,frames+1):

		imp3=extractFrame(imp1, nFrame)
		src=clij2.push(imp3)
		dst=clij2.create(src)
		clij2.replaceIntensities(src, src2, dst)
		LabeledImp=clij2.pull(dst)
		conLabeledStack = concatStacks( conLabeledStack, LabeledImp)
Example #11
0
					fmin.append(65536)
				if f[i] > fmax[i]:
					fmax[i] = f[i]
				if f[i] < fmin[i]:
					fmin[i] = f[i]
			
			sphere = {'cx': cx, 'cy': cy, 'cz': cz, 'r': r, 'f': f}
			spheres.append(sphere)


# Plot spheres
channelImages = []

if flat == True:
    for i in range(0, channels):
	imageProcessor = ShortProcessor(sx*4, sy*4)
	imageStack = ImageStack(sx*4, sy*4)
        for sphere in spheres:
            fnorm = int(round((sphere['f'][i] - fmin[i]) / (fmax[i] - fmin[i]) * 65536.0))
            x = sphere['cx'] * 4 - sphere['r']
            y = sphere['cy'] * 4 - sphere['r']
            d = sphere['r'] * 2
            imageProcessor.setValue(fnorm)
            imageProcessor.fillOval(x, y, d, d)
	imageStack.addSlice(imageProcessor)
	channelImages.append(ImagePlus("Rendering C" + "%i" % (i + 1), imageStack))
		
    imageO = RGBStackMerge.mergeChannels(channelImages, False)
elif pixels == True:
    for i in range(0, channels):
	imageProcessor = ShortProcessor(width, height)
Example #12
0
ranges = [[0, ((lim1 + s) * d1)], [(lim1 - s) * d1, ((lim2 + s) * d1)],
          [(lim2 - s) * d1, (lim3 + s) * d1],
          [(lim3 - s) * d1, dimensions[1] * d1]]
image_frags = []
for i in range(len(channels)):
    channel_frags = []
    channel = channels[i]
    pix = channel.getProcessor().getPixels()
    cm = channel.getProcessor().getColorModel()
    for r in range(len(ranges)):
        frag_pix = pix[ranges[r][0]:ranges[r][1]]
        channel_frags.append(
            ImagePlus(
                "Frag",
                ShortProcessor(d1, (ranges[r][1] - ranges[r][0]) / d1,
                               frag_pix, cm)))
    image_frags.append(channel_frags)
out_frags = []
for r in range(len(ranges)):
    channel_array = [
        image_frags[0][r], image_frags[1][r], image_frags[2][r],
        image_frags[3][r]
    ]
    imp = VesselFinder(channel_array, classifier_path)
    imp = imp.getStack()
    imp = imp.getProcessor(1)
    cm = imp.getColorModel()
    out_frags.append(imp)

cm = out_frags[0].getColorModel()
mranges = [[0, (-s * d1)], [s * d1, (-s * d1)], [s * d1, (-s * d1)],