def thresholdStackW(imp, low, high): i = 1 stack = imp.getStack() depth = imp.getNSlices() print "thresholdStackW: depth", depth width = stack.getProcessor(i).getWidth() height = stack.getProcessor(i).getHeight() winput = [None] w = Weaver.inline( """ byte[] input = (byte[]) winput.get(0); byte[] output = new byte[input.length]; for (int i=0; i<input.length; i++) { if (input[i] < low || input[i] > high){ output[i] = (byte)0; } else { output[i] = (byte)255; } } return output; """, {"winput":winput, "low":low, "high":high}) stackout = ImageStack(width, height) for k in range(1, depth+1): ip = stack.getProcessor(k) winput[0] = ip.getPixels() pixels = w.call() ipout = ByteProcessor(width, height) ipout.setPixels(pixels) stackout.addSlice(ipout) imp.setStack(stackout)
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
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 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
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
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
def __midline(self): debug=False #print "line 251", self.__boolML if self.__boolML : ordpoints=self.__midLine[:] npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) return polyOrd #if self.getMaxF()<15 : return None #self.__FeretAxis() #return self.__line self.__boolML=True self.__image.killRoi() self.__image.setRoi(self.__contour) boundRect=self.__contour.getBounds() boundRoi=Roi(boundRect) xori=boundRect.x yori=boundRect.y wori=boundRect.width hori=boundRect.height ip2 = ByteProcessor(self.__image.getWidth(), self.__image.getHeight()) ip2.setColor(255) ip2.setRoi(self.__contour) ip2.fill(self.__contour) skmp=ImagePlus("ip2", ip2) skmp.setRoi(xori-1,yori-1,wori+1,hori+1) ip3=ip2.crop() skmp3=ImagePlus("ip3", ip3) skmp3.killRoi() #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l287") #------------------------------------------------------------- IJ.run(skmp3, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l294") #------------------------------------------------------------- IJ.run(skmp3, "BinaryConnectivity ", "white") ip3.setThreshold(3,4, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(skmp3, "Convert to Mask", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l302") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.updateAndDraw() skmp3.show() IJ.showMessage("imp3 l308") #------------------------------------------------------------- rawPoints=[] w=ip3.getWidth() h=ip3.getHeight() rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] tempbouts=[val for val in rawPoints if val[2]==2] if len(tempbouts)!=2 : return None # test #if len(tempbouts)!=2 : # # IJ.run(skmp3, "BinaryConnectivity ", "white") # ip3.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) # IJ.run(skmp3, "Convert to Mask", "") # #------------------------------------------------------------- # if debug==debug : # skmp3.updateAndDraw() # skmp3.show() # IJ.showMessage("if test l 328") ##------------------------------------------------------------- # rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] # tempbouts=[val for val in rawPoints if val[2]==2] ip3.setRoi(boundRect) if rawPoints==[]: return None npoints=len(rawPoints) xpoints=[point[0] for point in rawPoints] ypoints=[point[1] for point in rawPoints] valpoints=[point[2] for point in rawPoints] bouts={} if tempbouts==[]: return None if tempbouts[0][1]>tempbouts[1][1]: bouts["A"]=tempbouts[0] bouts["B"]=tempbouts[1] else: bouts["A"]=tempbouts[1] bouts["B"]=tempbouts[0] rawPoints.remove(bouts["A"]) rawPoints.remove(bouts["B"]) rawPoints.append(bouts["B"]) tempList=[val for val in rawPoints] p=bouts["A"] Dist={} ordPoints=[] for j in range(len(rawPoints)): Dist.clear() for i in range(len(tempList)): dx=p[0]-tempList[i][0] dy=p[1]-tempList[i][1] d=math.sqrt(dx*dx+dy*dy) Dist[d]=tempList[i] distList=Dist.keys() mind=min(distList) nextpoint=Dist[mind] ordPoints.append(nextpoint) tempList.remove(nextpoint) p=nextpoint ordPoints.insert(0, bouts["A"]) npoints=len(ordPoints) if npoints < 4 : return None xpoints=[point[0] for point in ordPoints] ypoints=[point[1] for point in ordPoints] polyOrd1=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) f=min(self.__midParams[0], len(xpoints)//2) angleA1=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[1],ypoints[1]) angleA2=polyOrd1.getAngle(xpoints[1],ypoints[1], xpoints[2],ypoints[3]) angleA = (angleA1+angleA2)/2.00 angleA=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[f],ypoints[f]) angleA=angleA*(math.pi/180) angleB1=polyOrd1.getAngle(xpoints[-2],ypoints[-2], xpoints[-1],ypoints[-1]) angleB2=polyOrd1.getAngle(xpoints[-3],ypoints[-3], xpoints[-2],ypoints[-2]) angleB = (angleB1+angleB2)/2.00 angleB=polyOrd1.getAngle(xpoints[-f],ypoints[-f], xpoints[-1],ypoints[-1]) angleB=angleB*(math.pi/180) coef=self.__midParams[1] xa = xpoints[0]-coef*f*math.cos(angleA) ya = ypoints[0]+coef*f*math.sin(angleA) xb = xpoints[-1]+coef*f*math.cos(angleB) yb = ypoints[-1]-coef*f*math.sin(angleB) lineA=Line(xpoints[0],ypoints[0], xa, ya) lineB=Line(xpoints[-1],ypoints[-1], xb, yb) lineA.setWidth(0) lineB.setWidth(0) lineA.setStrokeWidth(0) lineB.setStrokeWidth(0) ip2.setColor(0) ip2.fill() ip2.setColor(255) ip2.setRoi(lineA) lineA.drawPixels(ip2) ip2.setRoi(lineB) lineB.drawPixels(ip2) ip2.setRoi(self.__contour) ip2.setColor(0) ip2.fillOutside(self.__contour) ip2=ip2.crop() imb=ImagePlus("new-ip2", ip2) #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l416") #------------------------------------------------------------- w2=ip2.getWidth() h2=ip2.getHeight() ip4 = ByteProcessor(w2+2, h2+2) im4=ImagePlus("im4", ip4) for i in range(w2): for j in range(h2): ip4.set(i+1,j+1,max([ip2.getPixel(i,j),ip3.getPixel(i,j)])) #im4.show() #------------------------------------------------------------- if debug : im4.show() IJ.showMessage("im4 l430") #------------------------------------------------------------- im4.killRoi() #IJ.run(im4, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l300") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") ip4=im4.getProcessor() rawPoints2=[] w4=ip4.getWidth() h4=ip4.getHeight() rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] # test if len(self.__MidBouts)!=2 : IJ.run(im4, "BinaryConnectivity ", "white") ip4.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(im4, "Convert to Mask", "") rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] ordpoints=[] p0=self.__MidBouts[0] rawPoints2.remove(p0) c=0 while p0!=self.__MidBouts[1]: if c<len(rawPoints2): point=rawPoints2[c] else: break if abs(point[0]-p0[0])<2 and abs(point[1]-p0[1])<2: p0=point ordpoints.append(point) rawPoints2.remove(point) c=0 else: c=c+1 ordpoints.insert(0, self.__MidBouts[0]) self.__midLine=ordpoints[:] self.__midCenters = self.__Centers(self.__midLine) npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) #print self.__midLine #print self.__MidBouts #print xpoints #print ypoints return polyOrd
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
# 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:
def __fmaxfinder(self) : #stack = self.__impRes.getStack() self.__impD.killRoi() self.__impF.killRoi() stack = self.__impF.getStack() n_slices = stack.getSize() #newstack=ImageStack(self.__impRes.getWidth(), self.__impRes.getHeight()) newstack=ImageStack(self.__impF.getWidth(), self.__impF.getHeight()) noise = self.__display3.text for index in range(1,n_slices+1): IJ.selectWindow(self.__impF.getTitle()) self.__impF.setSlice(index) ip = self.__impF.getProcessor() mf=MaximumFinder() ipmax = mf.findMaxima(ip, int(noise), 0, 0, False, False) newstack.addSlice("", ipmax) newimage=ImagePlus("max points"+self.__name, newstack) newimage.show() newimage.updateAndDraw() listip = [] maxh=self.__impRes.getHeight() for roi in self.__cellsrois : straightener = Straightener() newimage.setSlice(roi[1]) newimage.setRoi(roi[0]) #listip.append(straightener.straighten(newimage, roi[0], int(self.__widthl))) listip.append(straightener.straighten(newimage, roi[0], maxh)) listip.sort(key = lambda ip : ip.width) ipw=[ ip.getWidth() for ip in listip ] iph=[ ip.getHeight() for ip in listip ] maxw=max(ipw) maxh=max(iph) if self.__enlarge : resizelist = [ ip.resize(maxw, maxh, True) for ip in listip ] else : resizelist = [] for ip in listip : tempip = ByteProcessor(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.__impMax = ImagePlus(self.__name+"-max", ims) self.__impMax.show() stack = self.__impMax.getStack() # get the stack within the ImagePlus n_slices = stack.getSize() for index in range(1, n_slices+1): self.__impMax.killRoi() self.__impMax.setSlice(index) roi = self.__listrois[index-1] if self.__sens[index-1]<0 : self.__impMax.setRoi(roi) ip1 = self.__impMax.getProcessor() ip1.flipHorizontal() self.__impMax.killRoi() self.__impMax.updateAndDraw() ip = self.__impMax.getProcessor() for i in range(ip.getWidth()*ip.getHeight()) : if ip.getf(i) > 0 : ip.setf(i, 255) #else : ip.setf(i, 0) IJ.run(self.__impMax, "8-bit", "") IJ.run(self.__impMax, "Options...", "iterations=2 count=1 black edm=Overwrite do=Close stack") IJ.run(self.__impMax, "Ultimate Points", "stack") self.__impMax.updateAndDraw()
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
gd.addNumericField("Slice end:",theImage.getNSlices(),0) gd.showDialog() if (gd.wasOKed()): startSlice = gd.getNextNumber() endSlice = gd.getNextNumber() width = theImage.getWidth() height = theImage.getHeight() newStack = ImageStack(width,height) for i in range(startSlice,endSlice+1): theImage.setSlice(i) theImage.killRoi() pixels = zeros('b',width*height) bp = ByteProcessor(width,height,pixels) bp.setColor(127) doStaySlice = True while doStaySlice: waiter = NonBlockingGenericDialog("Set cast") waiter.addMessage("Pick 2D ROI") waiter.setOKLabel("Save and advance") waiter.setCancelLabel("Save") waiter.showDialog() if (waiter.wasOKed()): roi = theImage.getRoi() if (roi is None): doStaySlice = True else:
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