Beispiel #1
0
def thread_geod(mask_p, index, pos, results):
    shortWeights = binary.ChamferWeights.CHESSKNIGHT.getShortWeights()
    gt = binary.geodesic.GeodesicDistanceTransformShort5x5(shortWeights, False)
    marker = ByteProcessor(dimentions[0], dimentions[1])
    marker.putPixel(pos[0][index], pos[1][index], 255)
    proc = gt.geodesicDistanceMap(marker, mask_p)
    points = []
    for w in range(len(X)):
        points.append(proc.getPixel(pos[0][w], pos[1][w]))
    results[index] = points
Beispiel #2
0
def localContrast(im, block = 127, histobins = 256, maxslope = 3):
	ipMaskCLAHE = ByteProcessor(im.getWidth(),im.getHeight())
	ipMaskCLAHE.threshold(-1)
	bitDepth = im.getBitDepth()
	if bitDepth == 8:
		maxDisp = Math.pow(2,8) - 1
	else:
		maxDisp = Math.pow(2,12) - 1

	ip = im.getProcessor()
	ip.setMinAndMax(0,maxDisp)
	if bitDepth == 8:
		ip.applyLut()
	Flat.getFastInstance().run(im, block, histobins, maxslope, ipMaskCLAHE, False)
	del ipMaskCLAHE
	return im
def mask2D(ip, sigmaPx, k, method, minimum, doFillHoles, doWatershed):
    mask = ip.duplicate()
    sub = mask.duplicate()
    mask.blurGaussian(sigmaPx)
    if k > 0:
        sub.blurGaussian(k * sigmaPx)
        mask.copyBits(sub, 0, 0, Blitter.SUBTRACT)

    stats = mask.getStatistics()
    hist = mask.getStatistics().histogram
    thresh = AutoThresholder().getThreshold(method, hist)
    thresh = (thresh / float(255)) * (stats.max - stats.min) + stats.min

    mask.threshold(int(thresh))
    mask = mask.convertToByte(False)

    if doFillHoles:
        fillHoles(mask)

    if doWatershed:
        floatEdm = EDM().makeFloatEDM(mask, 0, False)
        maxIp = MaximumFinder().findMaxima(floatEdm, 0.5,
                                           ImageProcessor.NO_THRESHOLD,
                                           MaximumFinder.SEGMENTED, False,
                                           True)
        if (maxIp != None):
            mask.copyBits(maxIp, 0, 0, Blitter.AND)

    mask.dilate()
    mask.erode()

    mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE)
    roi = ThresholdToSelection().convert(mask)
    ip.setRoi(roi)
    mean = ip.getStatistics().mean

    if mean < minimum:  #if the mask area intensity mean in the original image is less than the minimum required
        mask = ByteProcessor(ip.getWidth(), ip.getHeight())  #return empty mask

    return mask
Beispiel #4
0
def getMask(ip, method):
    W = ip.getWidth()
    H = ip.getHeight()

    hist = ip.getHistogram(256)
    stats = ip.getStatistics()

    thresh = AutoThresholder().getThreshold(method, hist)
    thresh = (thresh / float(255)) * stats.max

    mask = ByteProcessor(W, H)
    for i in range(W * H):
        value = ip.getf(i)
        bite = 255 if value >= thresh else 0
        mask.set(i, bite)

    fillHoles(mask)

    mask.erode()
    mask.dilate()

    return mask
Beispiel #5
0
def generate_intensity_weighted_curvature(curvature_overlay,
                                          curvature_profiles,
                                          intensity_channel_imp,
                                          colormap_string):
    """Generate intensity-weighted curvature image"""
    w = intensity_channel_imp.getWidth()
    h = intensity_channel_imp.getHeight()

    curv_impRGB = curvature_overlay.clone()
    IJ.run(curv_impRGB, colormap_string, "")
    IJ.run(curv_impRGB, "RGB Color", "")

    int_imp16 = intensity_channel_imp.clone()

    base_impRGB = intensity_channel_imp.clone()
    IJ.run(base_impRGB, "Grays", "")
    IJ.run(base_impRGB, "RGB Color", "")

    maxes = []
    for fridx in range(0, int_imp16.getNFrames()):
        int_imp16.setPositionWithoutUpdate(1, 1, fridx + 1)
        maxes.append(int_imp16.getStatistics(Measurements.MIN_MAX).max)
    mx = float(max(maxes))

    for idx, profile in enumerate(curvature_profiles):
        print("Frame = " + str(idx))
        curv_impRGB.setPosition(idx + 1)
        curvCP = curv_impRGB.getProcessor()
        base_impRGB.setPosition(idx + 1)
        baseCP = base_impRGB.getProcessor()
        int_imp16.setPosition(idx + 1)

        for chidx in range(0, 3):
            c = ['r', 'g', 'b']
            print("Image channel = " + c[chidx])
            baseBP = ByteProcessor(base_impRGB.getWidth(),
                                   base_impRGB.getHeight())
            curvBP = ByteProcessor(base_impRGB.getWidth(),
                                   base_impRGB.getHeight())
            baseBP = baseCP.getChannel(chidx, baseBP)
            curvBP = curvCP.getChannel(chidx, curvBP)

            for ((x, y), c) in profile:
                # ensure that no rounding issues cause pixels to fall outside image...
                if x > (w - 1):
                    x = w - 1
                if y > (h - 1):
                    y = h - 1
                if x < 0:
                    x = 0
                if y < 0:
                    y = 0
                x = int(round(x))
                y = int(round(y))
                baseBP.putPixelValue(
                    x, y,
                    int(
                        curvBP.getPixel(x, y) *
                        float(int_imp16.getPixel(x, y)[0]) / mx))
                #baseBP.putPixelValue(x, y, int(curvBP.getPixel(x,y)));
            baseCP.setChannel(chidx, baseBP)
        base_impRGB.setProcessor(baseCP)
    base_impRGB.setTitle("Merged")
    base_impRGB.show()
    curv_impRGB.show()
    pause_for_debug()
def getCells(dicStack):
    outStack = ImageStack(W,H)

    cells = [None for t in range(T+1)]

    for t in range(1,T+1):
        mapp = dicStack.getProcessor(t).convertToFloatProcessor()

        mapp.subtract( mapp.getStatistics().mean )
        mapp.abs()

        RankFilters().rank(mapp, 1.0, RankFilters.VARIANCE)
        mapp.sqrt()

        mapp.blurGaussian(5)

        hist = mapp.getHistogram(256)
        stats = mapp.getStatistics()

        thresh = AutoThresholder().getThreshold( AutoThresholder.Method.Otsu, hist )
        thresh = (thresh/float(255)) * (stats.max-stats.min) + stats.min

        mask = ByteProcessor(W,H)
        for i in range(W*H):
            value = mapp.getf(i)
            bite = 255 if value>=thresh else 0
            mask.set(i, bite)

        fillHoles(mask)
        ed = 3
        for e in range(ed): mask.erode(1, 0)
        for d in range(ed): mask.dilate(1, 0)

        watershed(mask)

        minA = 5000 #px²

        mask.setThreshold(255,255, ImageProcessor.NO_LUT_UPDATE)
        composite = ThresholdToSelection().convert(mask)

        rois = ShapeRoi(composite).getRois()
        keep = []
        for roi in rois:
            if roi.getStatistics().area >= minA:
                if not onEdge(roi):
                    keep.append(roi)
                else:
                    edgeRoi = ShapeRoi(roi)
                    edgeRoi.setPosition(0,0,t)
                    edgeRoi.setStrokeColor(Color.YELLOW)
                    ol.add(edgeRoi)
        print("T"+str(t)+" using "+str(len(keep))+"/"+str(len(rois))+" ROIs")
        rois = keep
        #rois = [ roi for roi in rois if roi.getStatistics().area >= minA and not onEdge(roi) ]	#keep big enough and not on edges

        # if there is only one Roi, cut it along the fitted ellipse minor axis
        if len(rois)==1:
            el = EllipseFitter()
            mask.setRoi(rois[0])
            el.fit(mask, None)
            el.makeRoi(mask)
            theta = el.angle * (maths.pi/180.0)

            length = el.major/2.0
            dy = maths.sin(theta)* length
            dx = maths.cos(theta)* length

            #major axis
            lineX0 = el.xCenter - dx
            lineY0 = el.yCenter + dy
            lineX1 = el.xCenter + dx
            lineY1 = el.yCenter - dy
            line = Line(lineX0, lineY0, lineX1, lineY1)
            line.setStrokeColor(Color.BLUE)
            line.setStrokeWidth(1)
            line.setPosition(0,0,t)
            ol.add(line)

            #minor axis scaled length to make sure cut ends are outside Roi
            cutX0 = el.xCenter + dy*100
            cutY0 = el.xCenter + dx*100
            cutX1 = el.yCenter - dy*100
            cutY1 = el.yCenter - dx*100

            cut = Line(cutX0,cutY0, cutX1, cutY1)
            cut.setStrokeWidth(2)
            cut = PolygonRoi( cut.getFloatPolygon(), PolygonRoi.POLYGON )

            mask.setColor(0)
            mask.fill(cut)
            composite = ThresholdToSelection().convert(mask)

            rois = ShapeRoi(composite).getRois()
            rois = [ roi for roi in rois if roi.getStatistics().area >= minA ]
        print(str(t) + ":" + str(len(rois)))

        rois = [ PolygonRoi(roi.getInterpolatedPolygon(20, True), PolygonRoi.POLYGON) for roi in rois ]
        rois = [ PolygonRoi(roi.getConvexHull(), PolygonRoi.POLYGON) for roi in rois ]

        rois = sorted(list(rois), key=lambda roi:roi.getLength() )	#size order
        rois = rois[-2:]											#keep 2 biggest
        rois = sorted(list(rois), key=lambda roi:roi.getStatistics().xCentroid+roi.getStatistics().yCentroid )	#top left to bottom right order

        if len(rois)>0:
            rois[0].setStrokeColor(Color.RED)
            rois[0].setPosition(0, 0, t)
            ol.add(rois[0])
        if len(rois)>1:
            rois[1].setStrokeColor(Color.GREEN)
            rois[1].setPosition(0, 0, t)
            ol.add(rois[1])
            cells[t] = (rois[0], rois[1])


    return cells
Beispiel #7
0
 def getProcessor(self, n):
     return ByteProcessor(self.width, self.height, self.getPixels(n), None)
def getGrayScaleImage(currIP, c, chanName, cfg):
    if (cfg.hasValue(ELMConfig.upperLeftExclusionX)):
        ulExclusionX = cfg.getValue(ELMConfig.upperLeftExclusionX)
    else:
        ulExclusionX = 0

    if (cfg.hasValue(ELMConfig.upperLeftExclusionY)):
        ulExclusionY = cfg.getValue(ELMConfig.upperLeftExclusionY)
    else:
        ulExclusionY = 0

    if (cfg.hasValue(ELMConfig.lowerRightExclusionX)):
        lrExclusionX = cfg.getValue(ELMConfig.lowerRightExclusionX)
    else:
        lrExclusionX = currIP.getWidth()

    if (cfg.hasValue(ELMConfig.lowerRightExclusionY)):
        lrExclusionY = cfg.getValue(ELMConfig.lowerRightExclusionY)
    else:
        lrExclusionY = currIP.getHeight()

    imgType = currIP.getType()
    if (chanName in cfg.getValue(
            ELMConfig.chansToSkip)):  # Don't process skip channels
        currIP.close()
        return None
    elif imgType == ImagePlus.COLOR_RGB or imgType == ImagePlus.COLOR_256:
        if (chanName == ELMConfig.BRIGHTFIELD):
            toGray = ImageConverter(currIP)
            toGray.convertToGray8()
        elif (chanName == ELMConfig.BLUE) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): #
            chanIdx = 2
            if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED):
                chanIdx = 0
            elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN):
                chanIdx = 1
            imgChanns = ChannelSplitter.split(currIP)
            currIP.close()
            currIP = imgChanns[chanIdx]

            # Clear the Exclusion zone, so it doesn't mess with  thresholding
            imgProc = currIP.getProcessor()
            imgProc.setColor(Color(0, 0, 0))
            imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                             currIP.getHeight())
            imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)
        elif (chanName == ELMConfig.YELLOW):
            # Clear the Exclusion zone, so it doesn't mess with  thresholding
            imgProc = currIP.getProcessor()
            imgProc.setColor(Color(0, 0, 0))
            imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                             currIP.getHeight())
            imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)

            # Create a new image that consists of the average of the red & green channels
            title = currIP.getTitle()
            width = currIP.getWidth()
            height = currIP.getHeight()
            newPix = ByteProcessor(width, height)
            for x in range(0, width):
                for y in range(0, height):
                    currPix = currIP.getPixel(x, y)
                    newPix.putPixel(x, y, (currPix[0] + currPix[1]) / 2)
            currIP.close()
            currIP = ImagePlus(title, newPix)
        else:
            print "ERROR: Unrecognized channel name! Name: " + chanName
            currIP.close()
            return None
    elif imgType == ImagePlus.GRAY16 or imgType == ImagePlus.GRAY32 or imgType == ImagePlus.GRAY8:
        if not imgType == ImagePlus.GRAY8:
            toGray = ImageConverter(currIP)
            toGray.convertToGray8()
    else:
        print "ERROR: Unrecognized channel name & image type! Channel: " + chanName + ", imgType: " + str(
            imgType)
        currIP.close()
        return None

    return currIP
def getThresholdedMask(currIP, c, z, t, chanName, cfg, wellPath, dbgOutDesc):
    if (cfg.hasValue(ELMConfig.upperLeftExclusionX)):
        ulExclusionX = cfg.getValue(ELMConfig.upperLeftExclusionX)
    else:
        ulExclusionX = 0

    if (cfg.hasValue(ELMConfig.upperLeftExclusionY)):
        ulExclusionY = cfg.getValue(ELMConfig.upperLeftExclusionY)
    else:
        ulExclusionY = 0

    if (cfg.hasValue(ELMConfig.lowerRightExclusionX)):
        lrExclusionX = cfg.getValue(ELMConfig.lowerRightExclusionX)
    else:
        lrExclusionX = currIP.getWidth()

    if (cfg.hasValue(ELMConfig.lowerRightExclusionY)):
        lrExclusionY = cfg.getValue(ELMConfig.lowerRightExclusionY)
    else:
        lrExclusionY = currIP.getHeight()

    imgType = currIP.getType()
    if (chanName in cfg.getValue(
            ELMConfig.chansToSkip)):  # Don't process skip channels
        currIP.close()
        return None
    elif imgType == ImagePlus.COLOR_RGB or imgType == ImagePlus.COLOR_256:
        if (chanName == ELMConfig.BRIGHTFIELD):
            toGray = ImageConverter(currIP)
            toGray.convertToGray8()
            if cfg.params[ELMConfig.imgType] == "png":
                darkBackground = True
            else:
                darkBackground = False
        elif (chanName == ELMConfig.BLUE) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): #
            chanIdx = 2
            if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED):
                chanIdx = 0
            elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN):
                chanIdx = 1
            imgChanns = ChannelSplitter.split(currIP)
            currIP.close()
            currIP = imgChanns[chanIdx]

            # Clear the Exclusion zone, so it doesn't mess with  thresholding
            imgProc = currIP.getProcessor()
            imgProc.setColor(Color(0, 0, 0))
            imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                             currIP.getHeight())
            imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)
            darkBackground = True
        elif (chanName == ELMConfig.YELLOW):
            # Clear the Exclusion zone, so it doesn't mess with  thresholding
            imgProc = currIP.getProcessor()
            imgProc.setColor(Color(0, 0, 0))
            imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                             currIP.getHeight())
            imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)

            # Create a new image that consists of the average of the red & green channels
            title = currIP.getTitle()
            width = currIP.getWidth()
            height = currIP.getHeight()
            newPix = ByteProcessor(width, height)
            for x in range(0, width):
                for y in range(0, height):
                    currPix = currIP.getPixel(x, y)
                    newPix.putPixel(x, y, (currPix[0] + currPix[1]) / 2)
            currIP.close()
            currIP = ImagePlus(title, newPix)
            darkBackground = True
        else:
            print "ERROR: Unrecognized channel name! Name: " + chanName
            currIP.close()
            return None
    elif imgType == ImagePlus.GRAY16 or imgType == ImagePlus.GRAY32 or imgType == ImagePlus.GRAY8:
        if (chanName == ELMConfig.BRIGHTFIELD):
            if cfg.params[ELMConfig.imgType] == "png":
                darkBackground = True
            else:
                darkBackground = False
        else:
            darkBackground = True

        if not imgType == ImagePlus.GRAY8:
            toGray = ImageConverter(currIP)
            toGray.convertToGray8()
    else:
        print "ERROR: Unrecognized channel name & image type! Channel: " + chanName + ", imgType: " + str(
            imgType)
        currIP.close()
        return None

    WindowManager.setTempCurrentImage(currIP)

    if cfg.getValue(ELMConfig.debugOutput):
        IJ.saveAs('png',
                  os.path.join(wellPath, "Processing_" + dbgOutDesc + ".png"))

    upperThreshImg = currIP.duplicate()

    # If threshold value is set, use it
    if (cfg.hasValue(ELMConfig.imageThreshold)):
        thresh = cfg.getValue(ELMConfig.imageThreshold)
        if (darkBackground):
            currIP.getProcessor().setThreshold(thresh, 255,
                                               ImageProcessor.NO_LUT_UPDATE)
        else:
            currIP.getProcessor().setThreshold(0, thresh,
                                               ImageProcessor.NO_LUT_UPDATE)
    else:  # Otherise, automatically compute threshold
        threshMethod = "Default"
        if cfg.hasValue(ELMConfig.thresholdMethod):
            threshMethod = cfg.getValue(ELMConfig.thresholdMethod)

        currIP.getProcessor().setAutoThreshold(threshMethod, darkBackground,
                                               ImageProcessor.NO_LUT_UPDATE)
        threshRange = currIP.getProcessor().getMaxThreshold(
        ) - currIP.getProcessor().getMinThreshold()
        #print "\t\tZ = " + str(z) + ", T = " + str(t) +  ", chan " + chanName + ": Using default threshold of minThresh: " + str(currIP.getProcessor().getMinThreshold()) + ", maxThresh: " + str(currIP.getProcessor().getMaxThreshold())
        if currIP.getType() != ImagePlus.GRAY8:
            print "\tChannel " + chanName + " is not GRAY8, instead type is %d" % currIP.getType(
            )
        if threshRange > cfg.getValue(ELMConfig.maxThreshRange):
            if (cfg.hasValue(ELMConfig.defaultThreshold)):
                thresh = cfg.getValue(ELMConfig.defaultThreshold)
                print "\t\tZ = " + str(z) + ", T = " + str(
                    t
                ) + ", chan " + chanName + ": Using default threshold of " + str(
                    thresh) + ", minThresh: " + str(currIP.getProcessor(
                    ).getMinThreshold()) + ", maxThresh: " + str(
                        currIP.getProcessor().getMaxThreshold())
                if (darkBackground):
                    currIP.getProcessor().setThreshold(
                        thresh, 255, ImageProcessor.NO_LUT_UPDATE)
                else:
                    currIP.getProcessor().setThreshold(
                        0, thresh, ImageProcessor.NO_LUT_UPDATE)
            else:
                print "\t\tZ = " + str(z) + ", T = " + str(
                    t
                ) + ", chan " + chanName + ": Ignored Objects due to threshold range! minThresh: " + str(
                    currIP.getProcessor().getMinThreshold(
                    )) + ", maxThresh: " + str(
                        currIP.getProcessor().getMaxThreshold())
                currIP.close()
                return None

    IJ.run(currIP, "Convert to Mask", "")

    # Clear out exclusion zones
    imgProc = currIP.getProcessor()
    imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                     currIP.getHeight())
    imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)

    IJ.run(currIP, "Close-", "")

    # Brightfield has an additional thresholding step
    if cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.BRIGHTFIELD:
        if cfg.getValue(ELMConfig.debugOutput):
            IJ.saveAs(
                'png', os.path.join(wellPath,
                                    "OrigMask_" + dbgOutDesc + ".png"))

        upperThresh = 255 * 0.95
        upperThreshImg.getProcessor().setThreshold(
            upperThresh, 255, ImageProcessor.NO_LUT_UPDATE)
        IJ.run(upperThreshImg, "Convert to Mask", "")
        IJ.run(upperThreshImg, "Close-", "")
        if cfg.getValue(ELMConfig.debugOutput):
            WindowManager.setTempCurrentImage(upperThreshImg)
            IJ.saveAs(
                'png',
                os.path.join(wellPath,
                             "UpperThreshMask_" + dbgOutDesc + ".png"))

        ic = ImageCalculator()
        compositeMask = ic.run("OR create", currIP, upperThreshImg)
        IJ.run(compositeMask, "Close-", "")
        currIP.close()
        currIP = compositeMask
        WindowManager.setTempCurrentImage(currIP)

    if cfg.getValue(ELMConfig.debugOutput):
        WindowManager.setTempCurrentImage(currIP)
        IJ.saveAs('png', os.path.join(wellPath,
                                      "Binary_" + dbgOutDesc + ".png"))

    upperThreshImg.close()
    return currIP
Beispiel #10
0
# adjust min and max, since we know them
imp.getProcessor().setMinAndMax(0, w-1)
imp.show()

# Create a random 8-bit image the hard way...
width = 512
height = 512
  
pix = zeros(width * height, 'b')
Random().nextBytes(pix)

channel = zeros(256, 'b')
for i in range(256):
    channel[i] = (i -128) 
cm = LUT(channel, channel, channel)
imp_rand_hard = ImagePlus("Random", ByteProcessor(width, height, pix, cm))
imp_rand_hard.show()

# random 16 bit the hard way...
imp = IJ.createImage("An Easy Random Image 8 bit image", "8-bit", 512, 512, 1)
Random().nextBytes(imp.getProcessor().getPixels())
imp.show()

print(sys.getsizeof(int))
print(sys.getsizeof(bytes))

# 1 - Obtain an image
blobs = IJ.openImage("http://imagej.net/images/blobs.gif")
blobs.setTitle("blobs")
blobs.show()
# Make a copy with the same properties as blobs image:
Beispiel #11
0
def hyst(ima, T1, T2):
    la = ima.getWidth()
    ha = ima.getHeight()
    res = ByteProcessor(la, ha)
    for x in xrange(la):
        for y in xrange(ha):
            pix = ima.getPixelValue(x, y)
            if pix >= T1:
                res.putPixel(x, y, 255)
            elif pix >= T2:
                res.putPixel(x, y, 128)
    change = True
    while (change):
        change = False
        for x in xrange(1, la - 1):
            for y in xrange(1, ha - 1):
                if (res.getPixelValue(x, y) == 255):
                    if (res.getPixelValue(x + 1, y) == 128):
                        change = True
                        res.putPixelValue(x + 1, y, 255)
                    if (res.getPixelValue(x - 1, y) == 128):
                        change = True
                        res.putPixelValue(x - 1, y, 255)
                    if (res.getPixelValue(x, y + 1) == 128):
                        change = True
                        res.putPixelValue(x, y + 1, 255)
                    if (res.getPixelValue(x, y - 1) == 128):
                        change = True
                        res.putPixelValue(x, y - 1, 255)
                    if (res.getPixelValue(x + 1, y + 1) == 128):
                        change = True
                        res.putPixelValue(x + 1, y + 1, 255)
                    if (res.getPixelValue(x - 1, y - 1) == 128):
                        change = True
                        res.putPixelValue(x - 1, y - 1, 255)
                    if (res.getPixelValue(x - 1, y + 1) == 128):
                        change = True
                        res.putPixelValue(x - 1, y + 1, 255)
                    if (res.getPixelValue(x + 1, y - 1) == 128):
                        change = True
                        res.putPixelValue(x + 1, y - 1, 255)
        if (change):
            for x in xrange(la - 2, 0, -1):
                for y in xrange(ha - 2, 0, -1):
                    if (res.getPixelValue(x, y) == 255):
                        if (res.getPixelValue(x + 1, y) == 128):
                            change = True
                            res.putPixelValue(x + 1, y, 255)
                        if (res.getPixelValue(x - 1, y) == 128):
                            change = True
                            res.putPixelValue(x - 1, y, 255)
                        if (res.getPixelValue(x, y + 1) == 128):
                            change = True
                            res.putPixelValue(x, y + 1, 255)
                        if (res.getPixelValue(x, y - 1) == 128):
                            change = True
                            res.putPixelValue(x, y - 1, 255)
                        if (res.getPixelValue(x + 1, y + 1) == 128):
                            change = True
                            res.putPixelValue(x + 1, y + 1, 255)
                        if (res.getPixelValue(x - 1, y - 1) == 128):
                            change = True
                            res.putPixelValue(x - 1, y - 1, 255)
                        if (res.getPixelValue(x - 1, y + 1) == 128):
                            change = True
                            res.putPixelValue(x - 1, y + 1, 255)
                        if (res.getPixelValue(x + 1, y - 1) == 128):
                            change = True
                            res.putPixelValue(x + 1, y - 1, 255)
    for x in xrange(la):
        for y in xrange(ha):
            if (res.getPixelValue(x, y) == 128):
                res.putPixelValue(x, y, 0)
    return res
Beispiel #12
0
from lib.io import parse_TIFF_IFDs, unpackBits2
from jarray import zeros, array
from java.io import RandomAccessFile
from ij import IJ, ImagePlus
from ij.process import ByteProcessor
from ij.io import ImageReader, FileInfo
from net.sf.ij.jaiio import JAIWriter
from com.sun.media.jai.codec import TIFFEncodeParam
from java.util import Arrays

filepath = os.path.join(tempfile.gettempdir(), "test-packbits.tif")

# Write a test TIFF packbits-compressed image of known pixel values
source_bytes = array([0, 0, 0, 42, 42, 42, 42, 89,
                      20, 20, 20, 20, 20, 20, 20, 20], 'b')
imp = ImagePlus("test-packbits", ByteProcessor(16, 1, source_bytes, None))
writer = JAIWriter()
writer.setFormatName("tiff")
# See doc: https://download.java.net/media/jai/javadoc/1.1.3/jai-apidocs/com/sun/media/jai/codec/TIFFEncodeParam.html
param = TIFFEncodeParam()
param.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS)
writer.setImageEncodeParam(param)
writer.write(filepath, imp)


# Parse the test file
IFDs = list(parse_TIFF_IFDs(filepath)) # the tags of each IFD

firstIFD = IFDs[0]
print firstIFD