コード例 #1
0
ファイル: appdirectories-clu.py プロジェクト: fish2000/homage
def _get_win_folder_with_jna(csidl):
    """ Use the Python Java wrappers to invoke – circuitously,
        I might add – a win32 filesystem API call
    """
    import array
    from com.sun import jna
    from com.sun.jna.platform import win32
    
    buf_size = win32.WinDef.MAX_PATH * 2
    buf = array.zeros('c', buf_size)
    shell = win32.Shell32.INSTANCE
    shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl.fullname),
                          None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)
    
    directory = jna.Native.toString(buf.tostring()).rstrip("\0")
    
    # Downgrade to short path name if have highbit chars. See
    # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
    has_high_char = False
    for char in directory:
        if ord(char) > 255:
            has_high_char = True
            break
    if has_high_char:
        buf = array.zeros('c', buf_size)
        kernel = win32.Kernel32.INSTANCE
        if kernel.GetShortPathName(directory, buf, buf_size):
            directory = jna.Native.toString(buf.tostring()).rstrip("\0")
    
    return directory
コード例 #2
0
ファイル: appdirs.py プロジェクト: OverlordQ/bitcoin-feemodel
def _get_win_folder_with_jna(csidl_name):
    import array
    from com.sun import jna
    from com.sun.jna.platform import win32

    buf_size = win32.WinDef.MAX_PATH * 2
    buf = array.zeros('c', buf_size)
    shell = win32.Shell32.INSTANCE
    shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)
    dir = jna.Native.toString(buf.tostring()).rstrip("\0")

    # Downgrade to short path name if have highbit chars. See
    # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
    has_high_char = False
    for c in dir:
        if ord(c) > 255:
            has_high_char = True
            break
    if has_high_char:
        buf = array.zeros('c', buf_size)
        kernel = win32.Kernel32.INSTANCE
        if kernal.GetShortPathName(dir, buf, buf_size):
            dir = jna.Native.toString(buf.tostring()).rstrip("\0")

    return dir
コード例 #3
0
def _get_win_folder_with_jna(csidl_name):
    import array
    from com.sun import jna
    from com.sun.jna.platform import win32

    buf_size = win32.WinDef.MAX_PATH * 2
    buf = array.zeros('c', buf_size)
    shell = win32.Shell32.INSTANCE
    shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None,
                          win32.ShlObj.SHGFP_TYPE_CURRENT, buf)
    dir = jna.Native.toString(buf.tostring()).rstrip("\0")

    # Downgrade to short path name if have highbit chars. See
    # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
    has_high_char = False
    for c in dir:
        if ord(c) > 255:
            has_high_char = True
            break
    if has_high_char:
        buf = array.zeros('c', buf_size)
        kernel = win32.Kernel32.INSTANCE
        if kernel.GetShortPathName(dir, buf, buf_size):
            dir = jna.Native.toString(buf.tostring()).rstrip("\0")

    return dir
コード例 #4
0
 def test_array_coercion(self):
     self.assertEquals("double", Coercions.takeArray(array.zeros('d', 2)))
     self.assertEquals("float", Coercions.takeArray(array.zeros('f', 2)))
     self.assertEquals("4", Coercions.takePyObj(1, 2, 3, 4))
     c = Coercions()
     self.assertEquals("5", c.takePyObjInst(1, 2, 3, 4, 5))
     self.assertEquals("OtherSubVisible[]", c.takeArray([OtherSubVisible()]))
     self.assertEquals("SubVisible[]", c.takeArray([SubVisible()]))
コード例 #5
0
 def test_array_coercion(self):
     self.assertEquals("double", Coercions.takeArray(array.zeros('d', 2)))
     self.assertEquals("float", Coercions.takeArray(array.zeros('f', 2)))
     self.assertEquals("4", Coercions.takePyObj(1, 2, 3, 4))
     c = Coercions()
     self.assertEquals("5", c.takePyObjInst(1, 2, 3, 4, 5))
     self.assertEquals("OtherSubVisible[]", c.takeArray([OtherSubVisible()]))
     self.assertEquals("SubVisible[]", c.takeArray([SubVisible()]))
コード例 #6
0
def nearestZProject(imp1):
    relicedImp = Slicer().reslice(imp1)
    relicedStack = relicedImp.getStack()
    width = imp1.getWidth()
    height = imp1.getHeight()
    depth = imp1.getNSlices()

    topPixels = zeros('f', width * height)

    stack2 = ImageStack(width, height)
    for i in range(1, relicedImp.getNSlices()):
        pixels = relicedStack.getPixels(i)
        for x in xrange(width):
            for pixel in xrange(x, x + width * (depth - 1), width):
                #after finding the first pixel above the threshold value, add the value to the list
                if pixels[pixel] != 0:

                    topPixels[i * width + x] = pixels[pixel]
                    #break from looping the y when 1st threshold pixel is found is met -> increases speed drastically! Otherwise need an if statement every loop...
                    break

    ip2 = FloatProcessor(width, height, topPixels, None)
    imp2 = ImagePlus("Nearest point proj", ip2)
    imp3 = imp2.resize(imp2.getWidth() * 2, imp2.getHeight() * 2, 'none')
    return imp3
コード例 #7
0
def pixel_has_color(x,y, raster):
    '''Returns true if pixel has black color'''
    get_pixel_parameter = zeros('i', 1)
    pixel = raster.getPixel(x,y,get_pixel_parameter)
    if pixel[0]==0:
        return True
    else:
        return False
コード例 #8
0
def pixel_has_color(x, y, raster):
    '''Returns true if pixel has black color'''
    get_pixel_parameter = zeros('i', 1)
    pixel = raster.getPixel(x, y, get_pixel_parameter)
    if pixel[0] == 0:
        return True
    else:
        return False
コード例 #9
0
def test_java_object_arrays():
   jStringArr = array(String, [String("a"), String("b"), String("c")])
   verify(Arrays.equals(jStringArr.typecode, str(String)), 
         "String array typecode of wrong type, expected %s, found %s" % 
         (jStringArr.typecode, str(String)))
   verify(zeros(String, 5) == Array.newInstance(String, 5))

   import java # require for eval to work
   if jStringArr != eval(str(jStringArr)):
      raise TestFailed, "eval(str(%s)) <> %s" % (jStringArr,)*2
コード例 #10
0
    def test_java_object_arrays(self):
        jStringArr = array(String, [String("a"), String("b"), String("c")])
        self.assert_(
            Arrays.equals(jStringArr.typecode, 'java.lang.String'),
               "String array typecode of wrong type, expected %s, found %s" % 
               (jStringArr.typecode, str(String)))
        self.assertEqual(zeros(String, 5), Array.newInstance(String, 5))

        import java.lang.String # require for eval to work
        self.assertEqual(jStringArr, eval(str(jStringArr)))
コード例 #11
0
ファイル: test_array_jy.py プロジェクト: maggishaggy/MUFINS
    def test_java_object_arrays(self):
        jStringArr = array(String, [String("a"), String("b"), String("c")])
        self.assert_(
            Arrays.equals(jStringArr.typecode, 'java.lang.String'),
            "String array typecode of wrong type, expected %s, found %s" %
            (jStringArr.typecode, str(String)))
        self.assertEqual(zeros(String, 5), Array.newInstance(String, 5))

        import java.lang.String  # require for eval to work
        self.assertEqual(jStringArr, eval(str(jStringArr)))
コード例 #12
0
    def test_java_compat(self):
        from java import awt

        hsb = awt.Color.RGBtoHSB(0, 255, 255, None)
        self.assertEqual(hsb, array("f", [0.5, 1, 1]), "output hsb float array does not correspond to input rgb values")

        rgb = apply(awt.Color.HSBtoRGB, tuple(hsb))
        self.assertEqual(rgb, -0xFF0001, "output rgb bytes don't match input hsb floats")
        hsb1 = zeros("f", 3)
        awt.Color.RGBtoHSB(0, 255, 255, hsb1)
        self.assertEqual(hsb, hsb1, "hsb float arrays were not equal")
コード例 #13
0
ファイル: paint_area.py プロジェクト: Jonny-James/HandReco
 def image(self):
     w = self.getWidth();
     h = self.getHeight();
     non_black_withe_image = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB)
     self.paint(non_black_withe_image.getGraphics())
     raster=non_black_withe_image.getRaster()
     bi = BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY)
     write_raster = bi.getRaster()
     c = array.zeros('i', 4)
     on=wc = array.zeros('i', 1)
     off=array.zeros('i', 1)
     off[0]=1
     for x in range(w):
         for y in range(h):
             c = raster.getPixel(x,y,c)
             if sum(c)!=1020:
                 write_raster.setPixel(x,y, on)
             else:
                 write_raster.setPixel(x,y, off)
     return bi;
コード例 #14
0
ファイル: paint_area.py プロジェクト: oussamakhe/HandReco
 def image(self):
     w = self.getWidth()
     h = self.getHeight()
     non_black_withe_image = BufferedImage(w, h,
                                           BufferedImage.TYPE_INT_ARGB)
     self.paint(non_black_withe_image.getGraphics())
     raster = non_black_withe_image.getRaster()
     bi = BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY)
     write_raster = bi.getRaster()
     c = array.zeros('i', 4)
     on = wc = array.zeros('i', 1)
     off = array.zeros('i', 1)
     off[0] = 1
     for x in range(w):
         for y in range(h):
             c = raster.getPixel(x, y, c)
             if sum(c) != 1020:
                 write_raster.setPixel(x, y, on)
             else:
                 write_raster.setPixel(x, y, off)
     return bi
コード例 #15
0
        def read_all(reader):
            arrsize = 8 * 1024
            arr = zeros('c', arrsize)
            buffer = StringBuilder()
            numCharsRead = 0

            while numCharsRead != -1:
                numCharsRead = reader.read(arr, 0, arrsize)
                if numCharsRead != -1:
                    buffer.append(arr, 0, numCharsRead)

            return buffer.toString()
コード例 #16
0
ファイル: test_array_jy.py プロジェクト: Alex-CS/sonify
    def test_java_compat(self):
        from array import zeros
        from java.awt import Color
        hsb = Color.RGBtoHSB(0,255,255, None)
        self.assertEqual(hsb, array('f', [0.5,1,1]),
                         "output hsb float array does not correspond to input rgb values")

        rgb = apply(Color.HSBtoRGB, tuple(hsb))
        self.assertEqual(rgb, -0xff0001,
                         "output rgb bytes don't match input hsb floats")
        hsb1 = zeros('f', 3)
        Color.RGBtoHSB(0, 255, 255, hsb1)
        self.assertEqual(hsb, hsb1, "hsb float arrays were not equal")
コード例 #17
0
ファイル: test_array_jy.py プロジェクト: maggishaggy/MUFINS
    def test_java_compat(self):
        from java.awt import Color
        hsb = Color.RGBtoHSB(0, 255, 255, None)
        self.assertEqual(
            hsb, array('f', [0.5, 1, 1]),
            "output hsb float array does not correspond to input rgb values")

        rgb = apply(Color.HSBtoRGB, tuple(hsb))
        self.assertEqual(rgb, -0xff0001,
                         "output rgb bytes don't match input hsb floats")
        hsb1 = zeros('f', 3)
        Color.RGBtoHSB(0, 255, 255, hsb1)
        self.assertEqual(hsb, hsb1, "hsb float arrays were not equal")
コード例 #18
0
def learn(imp):

    IJ.run(imp, "Line Width...", "line=10")
    IJ.run("Colors...", "foreground=black background=black selection=red")

    # Clear ROI manager
    roiMan = RoiManager.getInstance()
    if roiMan is not None:
        roiMan.reset()

    # set results table
    rt = ResultsTable.getResultsTable()
    # set up analyzer
    analyzer = Analyzer(imp, 1, rt)

    impBrightness = ProcessHSB.getBrightness(imp)
    IJ.run(impBrightness, "8-bit", "")
    IJ.run(impBrightness, "Auto Threshold", "method=Shanbhag white")
    IJ.run(impBrightness, "Analyze Particles...",
           "size=50000-Infinity circularity=0.00-1.00 show=Masks add in_situ")

    # Pixel running total
    pixelTotal = zeros('f', 4)

    roiTotal = roiMan.getCount()

    if roiMan is not None:

        # Iterate throught the ROIs
        for roi in xrange(roiTotal):
            roiMan.select(roi)
            selectRoi = roiMan.getRoi(roi)

            option = getOptions()

            # measure
            analyzer.measure()
            meas = rt.getRowAsString(0)
            newLine = meas.split("	", 1)
            pixels = float(newLine[1])
            # Tag the ROI
            IJ.run(imp, "Fill", "slice")

            pixelTotal[0] = pixelTotal[0] + (option[0] * pixels)
            pixelTotal[1] = pixelTotal[1] + (option[1] * pixels)
            pixelTotal[2] = pixelTotal[2] + (option[2] * pixels)
            pixelTotal[3] = pixelTotal[3] + (option[3] * pixels)

        return pixelTotal
    else:
        return pixelTotal
コード例 #19
0
def getOptions():

    pixels = zeros('f', 4)  # 4 elements

    # First Dialog Box
    item = [
        "coralline", "tunicate", "red", "macro", "background", "more than one"
    ]
    gd = GenericDialog("Options")
    gd.addRadioButtonGroup("options", item, 3, 2, "coralline")
    gd.showDialog()
    button = gd.getNextRadioButton()

    # Second Dialog Box
    gd2 = GenericDialog("Multiple Options")
    items = ["coralline", "tunicate", "red", "macro", "garbage"]
    defaultVal = [False] * 5
    gd2.addCheckboxGroup(2, 3, items, defaultVal)
    gd2.addNumericField("coralline %", 0, 0)
    gd2.addNumericField("tunicate %", 0, 0)
    gd2.addNumericField("red %", 0, 0)
    gd2.addNumericField("macro %", 0, 0)
    gd2.addNumericField("background %", 0, 0)

    if gd.wasCanceled():
        return 0

    if button == "coralline":
        pixels[0] = 1
    elif button == "tunicate":
        pixels[1] = 1
    elif button == "red":
        pixels[2] = 1
    elif button == "macro":
        pixels[3] = 1
    elif button == "more than one":
        gd2.showDialog()
        checklist = gd2.getCheckboxes()
        pixels[0] = int(
            checklist[0].state) * (float(gd2.getNextNumber()) / 100)
        pixels[1] = int(
            checklist[1].state) * (float(gd2.getNextNumber()) / 100)
        pixels[2] = int(
            checklist[2].state) * (float(gd2.getNextNumber()) / 100)
        pixels[3] = int(
            checklist[3].state) * (float(gd2.getNextNumber()) / 100)

    return pixels
コード例 #20
0
def test_java_compat():
   print_test('array', 2)
   from java import awt
   hsb = awt.Color.RGBtoHSB(0,255,255, None)
   #print hsb
   verify(hsb == array('f', [0.5,1,1]), 
         "output hsb float array does not correspond to input rgb values")
   
   rgb = apply(awt.Color.HSBtoRGB, tuple(hsb))
   #print hex(rgb)
   verify(rgb == 0xff00ffff, "output rgb bytes don't match input hsb floats")
   
   print_test('zeros', 2)
   hsb1 = zeros('f', 3)
   awt.Color.RGBtoHSB(0,255,255, hsb1)
   #print hsb, hsb1
   verify(hsb == hsb1, "hsb float arrays were not equal")
コード例 #21
0
    def getBytes(self, size):
        parmStr = self.toString()
        if size == Parameter.DATA_SIZE:
            dataSize = len(parmStr)
        elif size == Parameter.UNKNOWN_SIZE:
            dataSize = len(parmStr);
        elif size == Parameter.DEFAULT_SIZE:
            dataSize = 65000;
        elif size == Parameter.OUTPUT_SIZE:
            dataSize = Parameter.DEFAULT_OUTPUT_SIZE
        else: dataSize = size    
            
        nulled = array.zeros( 'b', 3)
        nulled[0] = 0
        nulled[1] = 0
        nulled[2] = 0
        convertor = AS400Text(dataSize + 3, 37);

        return convertor.toBytes( parmStr + nulled.tostring() );
コード例 #22
0
def NeighborChecker(xar, yar, zar, switch):
	""" Check the distance to neighbors, and count the number of neighbors below thdist. """
	global thdist
	neighborA = zeros('d', len(xar))
	if switch:
		for i in range(len(xar)):
			cx = xar[i]
			cy = yar[i]
			cz = zar[i]	 
			for j in range(len(xar)):
				if j != i :
					dist = Math.sqrt( Math.pow((cx - xar[j]), 2) + Math.pow((cy - yar[j]), 2))
					if dist < thdist:
						if Math.abs(cz - zar[j]) < 2:
							logstr = ".... Dot%d - Dot%d too close: dist = %d" % (i, j, dist)
							IJ.log(logstr)
							print logstr
							neighborA[i] += 1
			if neighborA[i] > 0:
				IJ.log("---> Dot%d rejected" % (i))
				print "---> Dot", i, " rejected"
	return neighborA
コード例 #23
0
def measureWidth(numberOfWidthMeasurements):
  impIn = WindowManager.getCurrentImage()
  title = impIn.getTitle()
  IJ.run("Duplicate...", " ")
  impWork =  WindowManager.getCurrentImage()
  workTitle = impWork.getTitle()
  IJ.run("Clear Results")
  IJ.run("Measure")
  rt = ResultsTable.getResultsTable()
  min = rt.getValue("Min", 0)  
  IJ.run("Subtract...", "value=" + str(min))
  IJ.resetMinAndMax()
  imp = WindowManager.getCurrentImage()
  width = imp.getWidth()
  height = imp.getHeight()
  IJ.setAutoThreshold(imp, "Mean dark")
  roiManager = RoiManager.getRoiManager()
  roiManager.reset()
  IJ.run("Analyze Particles...", "size=1000-Infinity add")
  IJ.run("Clear Results")
  roiManager.select(0)
  roiManager.runCommand("Measure")
  angle = rt.getValue("Angle", 0)
  IJ.run("Select None")
  roiManager.runCommand("Delete")
  IJ.run("Rotate... ", "angle="+str(angle)+" grid=1 interpolation=Bilinear enlarge")
  IJ.setAutoThreshold(imp, "Li dark")
  IJ.run("Convert to Mask")
  IJ.run("Fill Holes")
  roiManager.reset()
  IJ.run("Analyze Particles...", "size=1000-Infinity add")
  IJ.run("Clear Results")
  roiManager.select(0)
  IJ.run("Clear Outside")
  IJ.selectWindow(title)
  IJ.run("Rotate... ", "angle="+str(angle)+" grid=1 interpolation=Bilinear enlarge")
  roiManager.select(0) 
  roiManager.runCommand("Measure")
  IJ.run("Select None")
  IJ.run("Rotate... ", "angle="+str(-angle)+" grid=1 interpolation=Bilinear enlarge")
  IJ.run("Canvas Size...", "width="+str(width)+" height="+str(height)+" position=Center zero")
  IJ.selectWindow(workTitle)
  xBox = rt.getValue("BX", 0)
  lengthBox = rt.getValue("Width", 0)
  heightBox = rt.getValue("Height", 0)
  lengthEllipse = rt.getValue("Major", 0)
  heightEllipse = rt.getValue("Minor", 0)
  calibration = imp.getCalibration()
  xMiddle = int(round(((lengthBox - xBox) / 2.0) + xBox, 0))
  xOuter = xBox + lengthBox
  xInner = xBox
  widths = zeros('f', numberOfWidthMeasurements)
  delta = (xOuter - xInner) / (numberOfWidthMeasurements + 1.0)
  for i in range(1,numberOfWidthMeasurements+1):
    deltaLen = delta * i;
    xM = xInner + deltaLen
    widths[i-1] = getWidthAt(xM, imp)
  IJ.run("Flatten");
  IJ.run("Rotate... ", "angle="+str(-angle)+" grid=1 interpolation=Bilinear enlarge")
  IJ.run("Canvas Size...", "width="+str(width)+" height="+str(height)+" position=Center zero")
  impFlat = WindowManager.getCurrentImage()
  imp.changes = False;
  imp.close()
  titleIn = impIn.getTitle()
  titleFlat = impFlat.getTitle()
  IJ.selectWindow(titleIn)
  IJ.run("Add Image...", "image=" + titleFlat + " x=0 y=0 opacity=50 zero")
  impFlat.changes = False
  impFlat.close()
  return widths
コード例 #24
0
ファイル: simpledata.py プロジェクト: dailypips/gumtree
def zeros(shape, dtype = float): 
    return new(array.zeros(shape, dtype))
コード例 #25
0
ファイル: fillROI_.py プロジェクト: jrminter/OSImageAnalysis
# fillROI_.py
# from A. Cardona
# http://www.ini.uzh.ch/~acardona/fiji-tutorial/#fill-ROI
#
from ij import IJ, ImagePlus  
from ij.process import FloatProcessor  
from array import zeros  
from random import random  
from ij.gui import Roi, PolygonRoi  
  
# Create a new ImagePlus filled with noise  
width = 1024  
height = 1024  
pixels = zeros('f', width * height)  
  
for i in xrange(len(pixels)):  
  pixels[i] = random()  
  
fp = FloatProcessor(width, height, pixels, None)  
imp = ImagePlus("Random", fp)  
  
# Fill a rectangular region of interest  
# with a value of 2:  
roi = Roi(400, 200, 400, 300)  
fp.setRoi(roi)  
fp.setValue(2.0)  
fp.fill()  
  
# Fill a polygonal region of interest  
# with a value of -3  
xs = [234, 174, 162, 102, 120, 123, 153, 177, 171,  
コード例 #26
0
ファイル: simpledata.py プロジェクト: nxi/gumtree
def zeros(shape, dtype=float):
    return new(array.zeros(shape, dtype))
コード例 #27
0
# 선택 영역 칠하기
from ij import ImagePlus
from ij.process import FloatProcessor
from array import zeros
from random import random
from ij.gui import Roi, PolygonRoi

# noise로 칠해진 이미지 생성
width = 1024
height = 1024
pixels = zeros('f', width * height)

for i in xrange(len(pixels)):
    pixels[i] = random()

fp = FloatProcessor(width, height, pixels, None)
imp = ImagePlus("Random", fp)

imp.show()

# 직사각형 관심영역(ROI: Region of Interest)를 2로 채우기
fp = FloatProcessor(width, height, pixels, None)
roi = Roi(400, 200, 400, 300)  # Roi(int x, int y, int width, int height)
fp.setRoi(roi)
fp.setValue(2.0)
fp.fill()

imp2 = ImagePlus("Rectangle", fp)
imp2.show()

# Polygon ROI를 -3으로 채우기
コード例 #28
0
ファイル: roi.to.mask_.py プロジェクト: rmd13/lab-program
refImp = IJ.openImage(refpath)
width = refImp.width
height = refImp.height

roim = RoiManager()
roim.runCommand("open", roipath)

roiArray = roim.getRoisAsArray()
nRoi = len(roiArray)
roim.close()

bwStack = ImageStack(width, height, nRoi)
for i in xrange(1, nRoi + 1):
    bwStack.setProcessor(
        FloatProcessor(width, height, zeros('f', width * height), None), i)

for i in xrange(1, nRoi + 1):
    roi = roiArray[i - 1]
    fp = bwStack.getProcessor(i)
    fp.setValue(1.0)
    fp.fill(roi)

roiImp = ImagePlus("roi", bwStack)

outfn = "roi_" + os.path.splitext(roifn)[0] + ".tif"
outpath = os.path.join(roidir, outfn)
if os.path.exists(outpath):
    print "Skipped, already exists: ", outfn
else:
    IJ.saveAsTiff(roiImp, outpath)
コード例 #29
0
 	 del a[2]  xóa phần tử thứ 3.
 	 a.remove(1)
 	 print(a.pop(1))

 	Thư viện numpy :
 	import numpy as np
 	mangA=np.array([2,3,4,5,6,8])
 	mangB=np.arange(25) #tạo một mảng có 25 ptử
 	mangB.reshape(5,5) #tạo mảng 5 5, ma trận
 	mang=np.arange(25).reshape(5,5)

 	 ví dụ:
 	 	abc=np.array([[1,2,3,4,5,6],[1,2,4,67,8,8]])
 	 	abc.shape ==>> output is (2,6)
 	Tạo một mảng chứa 5 ptu 0:
 			np.zeros(5)
 			np.ones(10) #tạo 10 phẩn tử có gt 1.
 			np.twos(5)
 			np.zeros(2,1) #tạo mảng 0 hình 2 dòng một ô.
 	+array arithmetic
 		arr + 10 #thêm vào mỗi phần tử 10 đơn vị
 		arr*arr #nhân mỗi phần tử với chính nó
 		arr**2 # mỗi phần tử lũy thừa 2
 		name.T # đổi dòng thành cột, và ngược lại
 	a1=a[:10] # lấy 10 ptu cua a ve a1
 	a1[:100]#chuyển ptu cua a1 thanh 100
 	#khi in a van bao gom ca a1
 	a1[0]=100 đổi ptu
 	b=a.copy()

 	xem thêm bài 61
コード例 #30
0
from array import array, zeros
from ij import ImagePlus, IJ

# An empty native float array of length 5
a = zeros('f', 5)
print a

# A native float array with values 0 to 9
b = array('f', [0, 1, 2, 3, 4])
print b

# An empty native ImagePlus array of length 5
imps = zeros(ImagePlus, 5)
print imps

# Assign the current image to the first element of the array
imps[0] = IJ.getImage()
print imps

# Length of an array
print "length:", len(imps)
コード例 #31
0
ファイル: fuji-merge-frames.py プロジェクト: caomw/fuji-exr
#basename = '141016_155913'
#basename = 'test/DSCF3564'

frame = []

for fn in ['0', '1']:
    filename = os.environ['HOME'] + '/' + basename + '_' + fn + '.pgm'
    imp = IJ.openImage(filename)
    if imp is None:
        print "Could not open image from file:", filename
    frame.append(imp)
print 'loaded frames'

width = frame[0].width
height = frame[0].height
bpix = zeros('h', (width + height)**2)

for fn in [0, 1]:
    pix = frame[fn].getProcessor().getPixels()
    for i in range(len(pix)):
        x = i % width + i / width + fn # the second frame (fn == 1) is shifted 1px to the right
        y = (width - i % width - 1) + (i / width)
        bpix[y * (width + height) + x] = pix[i]
    print 'wrote frame %s' % fn

ip = ShortProcessor(width + height, width + height, bpix, None)  
bayer = ImagePlus("Sensor", ip)

fs = FileSaver(bayer)  
fs.saveAsTiff(os.path.dirname(filename) + '/' + 'raw.tiff')
コード例 #32
0
def processCurrentImage(table):
    imp = WindowManager.getCurrentImage()
    fileName = imp.getTitle()
    middleSlice = int(math.floor(imp.getNFrames() / 2.0) + (imp.getNFrames() % 2))
    imp.setSlice(middleSlice)
    IJ.run("Duplicate...", " ")
    imp.close()
    imp = WindowManager.getCurrentImage()
    
    dir = fiji.analyze.directionality.Directionality_()
    dir.setImagePlus(imp)
    dir.setMethod(fiji.analyze.directionality.Directionality_.AnalysisMethod.FOURIER_COMPONENTS)
    dir.setBinNumber(90)
    dir.setBinStart(-90)
    dir.setBuildOrientationMapFlag(False)
        
    dir.computeHistograms()
    dir.fitHistograms()
    results = dir.getFitAnalysis()
    direction = math.degrees(results[0][0])
    dispersion = math.degrees(results[0 ][1])
    amount = results[0][2]
    goodness = results[0][3]
    IJ.run("Clear Results")
    IJ.run("FFT")
    fftImp = WindowManager.getCurrentImage()
    
    IJ.run("Mean...", "radius=2");
    IJ.run("Find Maxima...", "noise=15 output=[Point Selection]")
    IJ.run("Measure")
    fftImp.changes = False
    fftImp.close()
      
    rt = ResultsTable.getResultsTable()
    size = rt.size()
    numberOfFrequences = size
    if size>=5: 
       numberOfFrequences = 5
    R = zeros('f', numberOfFrequences)
    Theta = zeros('f', numberOfFrequences)
    for i in range(0, numberOfFrequences):
       R[i] = rt.getValue("R", i)
       Theta[i] = rt.getValue("Theta", i)
    table.incrementCounter()
    table.addValue('image', fileName)
    table.addValue('Direction', direction)
    table.addValue('Dispersion', dispersion)
    table.addValue('Amount', amount)
    table.addValue('Goodness', goodness)
    for i in range(0, numberOfFrequences):
       table.addValue('R'+str(i), R[i])
       table.addValue('Theta'+str(i), Theta[i])
    
    widths = measureWidth(numberOfWidthMeasurements)
    i = 1;
    for width in widths:
      table.addValue("width" + str(i), width)        
      i = i + 1
    headings = rt.getHeadings()
    for heading in headings:
      if heading != "Label":
        value = rt.getValue(heading, 0)
        table.addValue(heading, value)
    table.show('Directonality analysis')
コード例 #33
0
# 밑바닥부터 이미지 만들기
from ij import ImagePlus
from ij.process import FloatProcessor
from array import zeros
from random import random

width = 1024
height = 1024
# Jython으로 array 만들기
# http://fiji.sc/wiki/index.php/Jython_Scripting_Examples#Creating_multi-dimensional_native_java_arrays
pixels = zeros('f', width * height)  # f: "float"

for i in xrange(len(pixels)):
    pixels[i] = random()

fp = FloatProcessor(width, height, pixels, None)
imp = ImagePlus("White noise", fp)

imp.show()
コード例 #34
0
    refpath = os.path.join(refdir, reffn)

refImp = IJ.openImage(refpath)
width = refImp.width  
height = refImp.height  

roim = RoiManager()
roim.runCommand("open", roipath)

roiArray = roim.getRoisAsArray()
nRoi = len(roiArray)
roim.close()

bwStack = ImageStack(width, height, nRoi)
for i in xrange(1, nRoi+1):
    bwStack.setProcessor(FloatProcessor(width, height, zeros('f', width * height), None), i)

for i in xrange(1, nRoi+1):
    roi = roiArray[i-1]
    fp = bwStack.getProcessor(i)
    fp.setValue(1.0)
    fp.fill(roi)

roiImp = ImagePlus("roi", bwStack)

outfn = "roi_" + os.path.splitext(roifn)[0] + ".tif"
outpath = os.path.join(roidir, outfn)
if os.path.exists(outpath):
    print "Skipped, already exists: ", outfn
else:
    IJ.saveAsTiff(roiImp, outpath)