Ejemplo n.º 1
0
def acquireZStackContinuous(topZ, bottomZ, mmc, folder=None, flatField = None):
    ## get information we need
    imageWidth = mmc.getImageWidth()
    imageHeight = mmc.getImageHeight()
    configuration = Configuration()
    zStep = configuration.zStep
    nSlices = int(math.ceil((topZ-bottomZ)/zStep))
    ## intialize
    finalStack = np.zeros((nSlices,imageHeight,imageWidth)).astype("uint16")
    ## make list of z values
    zList = np.empty([0])
    ## so that we are in the correct index
    index = nSlices - 1
    ## go from top to bottom, incrementing by amount specified in 
    velocity = mmc.getProperty("ZeissFocusAxis", "Velocity (micron/s)")
    mmc.startSequenceAcquisition(nSlices, 0, True)
    frame = 0
    exposureMs = configuration.exposureBrightField
    
    while (mmc.getRemainingImageCount() > 0 or mmc.isSequenceRunning()):
        mmc.setPosition(mmc.getPosition()-zStep)
        if (mmc.getRemainingImageCount() > 0):
            singleLayer = mmc.popNextImage()
            finalStack[index,:,:] = singleLayer
            frame = frame + 1
            index = index - 1
        else:
            mmc.sleep(min(0.5 * exposureMs, 20))
    mmc.stopSequenceAcquisition()
    mmc.stopSequenceAcquisition(mmc.getCameraDevice())
    print finalStack[:,:,0]
    imsave("oneLayer.tiff", finalStack[:,:,0])
    return finalStack, zList
Ejemplo n.º 2
0
def multiSlides(slideName1,
                mmc,
                slideName2=None,
                slideName3=None,
                slideName4=None,
                slideName5=None,
                slideName6=None,
                slideName7=None,
                slideName8=None):
    ## get configuration
    configuration = Configuration()
    ## get list of slide names
    listOfSlideNames = [
        slideName1, slideName2, slideName3, slideName4, slideName5, slideName6,
        slideName7, slideName8
    ]
    ## get list without nones
    listOfSlideNamesNoNones = filter(None, listOfSlideNames)
    numberOfSlides = len(listOfSlideNamesNoNones)
    ## assumes that the first slide is in an okay position
    originalX = mmc.getXPosition()
    originalY = mmc.getYPosition()
    ## go through each slide
    for i in range(0, numberOfSlides):
        ## run acquisition routine
        oneSlide(listOfSlideNamesNoNones[i], mmc)
        ## move to next slide
        mmc.setXYPosition(originalX + configuration.SpaceBetweenSlides,
                          originalY)
Ejemplo n.º 3
0
def acquireZStack(topZ, bottomZ, mmc, folder=None, flatField = None):
    ## get information we need
    imageWidth = mmc.getImageWidth()
    imageHeight = mmc.getImageHeight()
    configuration = Configuration()
    zStep = configuration.zStep
    nSlices = int(math.ceil((topZ-bottomZ)/zStep))
    ## intialize
    finalStack = np.zeros((nSlices,imageHeight,imageWidth))
    ## make list of z values
    zList = np.empty([0])
    ## so that we are in the correct index
    index = nSlices - 1 
    ## go from top to bottom, incrementing by amount specified in 
    for z in np.arange(topZ, bottomZ, -zStep): 
        mmc.setPosition(z)
        mmc.snapImage()
        singleLayer = mmc.getImage()
        if flatField != None:
            singleLayer = flatFieldCorrection(flatField, singleLayer, mmc)
        finalStack[index,:,:] = singleLayer
        index = index-1
        ## add the z layer to the list of z coordinates
        zList = np.append(z, zList)
        if configuration.saveImages == True:
            filename = folder + "/" + str(z) + ".tiff"
            singleLayer = flatFieldCorrection(flatField, singleLayer, mmc)
            imsave(filename, singleLayer)
    return finalStack, zList
Ejemplo n.º 4
0
def makeMIP(topZ, bottomZ, flatField, mmc, folder=None):
    ## load configuration
    configuration = Configuration()
    if configuration.saveImages == True:
        finalStack, zList = acquireZStack(topZ, bottomZ, mmc, folder, flatField)
    if configuration.saveImages == False:
        finalStack, zList = acquireZStack(topZ, bottomZ, mmc, None, flatField)
    mip = minimumIntensityProjection(finalStack, mmc)
    hvLayer = findFocusLayerVL(finalStack, zList, mmc)
    return mip, hvLayer
def stitchDAPI(imageSoFar, x, y, img, mmc):
    configuration = Configuration()
    notOverlap = configuration.notOverlap
    ## crop the image
    croppedImg = img[0:int(math.floor(img.shape[0] * notOverlap)),
                     0:int(math.floor(img.shape[1] * notOverlap))]

    ## put into the larger image
    imageSoFar[int(math.floor(x)):(int(math.floor(x)) + croppedImg.shape[0]),
               int(math.floor(y)):(int(math.floor(y)) +
                                   croppedImg.shape[1])] = croppedImg
    return imageSoFar
Ejemplo n.º 6
0
def zLimits(mmc):
    ## get relevant values
    configuration = Configuration()
    extremeUpperZ = configuration.extremeUpperZ
    extremeLowerZ = configuration.extremeLowerZ
    downSampleRate = configuration.downSampleRate
    filterBlur = configuration.filterBlur
    ## make a from the very high z value to the very low z faluye
    zStack, zList = acquireZStack(extremeUpperZ, extremeLowerZ, mmc)
    ## downsample images
    binImg = downsampleImage(zStack, downSampleRate)

    varVect = varFilterStack(binImg)

    startEnd, conservativeStartEnd = processVarianceVector(varVect, filterBlur)

    showSelectedPlanes(varVect, startEnd, conservativeStartEnd)

    return startEnd[0], startEnd[1]
def stitchToEnd(imageSoFar, mmc):
    configuration = Configuration()
    notOverlap = configuration.notOverlap
    imageWidthNotOverlap = int(mmc.getImageWidth() * notOverlap)
    ## get the first column
    columnToStitch = imageSoFar[0:imageSoFar.shape[0], 0:imageWidthNotOverlap]
    ## move the image without the first column over by one column
    imageSoFar[0:imageSoFar.shape[0],
               0:(imageSoFar.shape[1] - imageWidthNotOverlap
                  )] = imageSoFar[0:imageSoFar.shape[0],
                                  imageWidthNotOverlap:imageSoFar.shape[1]]

    ## make columnToStitch the last column
    imageSoFar[0:imageSoFar.shape[0],
               (imageSoFar.shape[1] -
                imageWidthNotOverlap):imageSoFar.shape[1]] = columnToStitch
    imageSoFarCropped = imageSoFar[0:imageSoFar.shape[0],
                                   0:imageSoFar.shape[1] -
                                   imageWidthNotOverlap + 1]
    return imageSoFarCropped
Ejemplo n.º 8
0
def getDAPIFlatField(mmc):
    raw_input("Put blue chroma slide on, then press enter")
    ## load configuration
    configuration = Configuration()
    ## get information to set ROI
    imageWidth = mmc.getImageWidth()
    imageHeight = mmc.getImageHeight()
    ## set ROI
    mmc.setROI(configuration.cropX, configuration.cropY,
               (imageWidth - configuration.cropX * 2),
               (imageHeight - configuration.cropY * 2))
    ## turn on correct settings
    DAPIOn(mmc)
    ## need to sleep otherwise it's all grey
    mmc.sleep(100)
    ## snap image
    mmc.snapImage()
    ## save as CSV
    flatField = mmc.getImage()
    np.savetxt("DAPIFlatfield.csv", flatField, delimiter=",")
    DAPIOff(mmc)
Ejemplo n.º 9
0
""" purpose: make a z stack and save each layer as a tiff with the file name as the z coordinate
    inputs: the folder to save the z stack into, the most positive z coordinate, the most negative z coordinate, a mmc object
    returns: a tuple: 3d numpy array where each layer is an image acquired with mmc.getImage(), a list of the z coordinates in the same order
    saves: z tiffs
"""
def zStackTiffs(folder, topZ, bottomZ, flatField,  mmc):
    ## make the file folder, if it doesn't already exist
    if not os.path.exists(folder):
        os.makedirs(folder)
    ## go from top to bottom, incrementing by the z step specified in the configuration file and saving images
    finalStack, zList = acquireZStack(topZ, bottomZ, flatField, mmc, folder)
    return finalStack, zList

if __name__ == '__main__':
    #load microscope
    configuration = Configuration()
    mmc = MMCorePy.CMMCore()
    mmc.loadSystemConfiguration(configuration.cfg)
    mmc.setExposure(configuration.exposureBrightField)
    acquireZStackContinuous(0, -100, mmc)


########################## focus finding ##############################################


""" purpose: uses sobel gradient to return z coordinate of the most focused layer of a Z stack
    input: a 3d numpy array of images, a list of the z coordinates
    returns: the z coordinate of the image with the highest sobel gradient
    saves: nothing
""" 
def findFocusFromSobelGradient(inputArray, zList, mmc):
Ejemplo n.º 10
0
def oneSlide(slideName, mmc):
    ## get configuration
    configuration = Configuration()
    ## set properties to get 16 bit images and avoid tunneling
    mmc.setProperty('IDS uEye', 'Exposure', configuration.exposureBrightField)
    imageHeight = mmc.getImageHeight()
    imageWidth = mmc.getImageWidth()
    mmc.setROI(configuration.cropX, configuration.cropY, (imageWidth - configuration.cropX*2), (imageHeight - configuration.cropY*2))
    ## go to some z limit in the middle in the hopes that things won't be horribly out of focus
    middleZ = extremeUpperZ - (extremeUpperZ - extremeLowerZ)/2
    mmc.setPosition(middleZ)
    ## get 16 points to try to find sample
    sampleFound = findSample(mmc)
    ## if sample was found, find focus (not worth doing if no sample was found because there's nothing to focus on)
    if sampleFound == 'true':
        lowerZ, upperZ = zLimits(mmc)
    ## get flatfield and darkfield
    flatField = moveForFlatField(mmc)
    ## get coordinates needed to take an overview (should find sample if sample was not found before)
    coordinates = edgeDetectedOverview(mmc)
    LeftX = coordinates[0]
    RightX = coordinates[1] 
    TopY = coordinates[2] 
    BottomY = coordinates[3]
    ## can now get focus because the sample has definitely been found
    if sampleFound == 'false':
        ## go to somewhere within the sample
        mmc.setXYPosition((LeftX - RightX), (TopY - BottomY))
        lowerZ, upperZ = zLimits(mmc)
    ## create z stack spline
    folderNameMIP = slideName + "MIPS"
    coordinateList = getOverviewAndSaveMIP(folderNameMIP, RightX, LeftX, BottomY, TopY, upperZ, lowerZ, flatField, mmc)
    ## rename all the folders to be in the FFFFFF -> FFFFFF_SSSSSS -> ZZZZZZ.tiff file required by TeraStitcher
    renameTiffFolders(folderNameMIP)
    ## get the fluorescence image
    folderNameFluorescence = slideName + "Fluorescence"
    ## get DAPI flatfield
    flatFieldfileName = "DAPIFlatfield.csv"
    DAPIflatField = np.genfromtxt(flatFieldfileName, delimiter=",")
    fluorescenceAcquisition(coordinateList, folderNameFluorescence, DAPIflatField, mmc) 
    ## rename all the folders to be in the FFFFFF -> FFFFFF_SSSSSS -> ZZZZZZ.tiff file required by TeraStitcher
    renameTiffFolders(folderNameFluorescence)
    ## stitch in tera stitcher
    pixelSize = mmc.getPixelSizeUm()
    if configuration.saveImages == False:
        os.system('terastitcher --import -volin="{}" --ref1=-Y --ref2=X --ref3=Z --vxl1={} --vxl2={} --vxl3={} --projout=xml_import'.format(os.path.abspath(folderNameMIP), pixelSize, pixelSize, configuration.zStep))
        os.system('terastitcher --displcompute --projin="{}"'.format(os.path.abspath(folderNameMIP + r"\xml_import.xml")))
        os.system('terastitcher --displproj --projin="{}"'.format(os.path.abspath(folderNameMIP + r"\xml_displcomp.xml")))
        os.system('terastitcher --displthres --threshold={} --projin="{}"'.format(configuration.threshhold, os.path.abspath( folderNameMIP + r"\xml_displproj.xml")))
        os.system('terastitcher --placetiles --projin="{}"'.format(os.path.abspath(folderNameMIP + r"\xml_displthres.xml")))
        stitchedFolder = folderNameMIP + r"\stitched"
        if not os.path.exists(stitchedFolder):
            os.makedirs(stitchedFolder)
        os.system('terastitcher --merge -projin="{}" -volout="{}" -volout_plugin="TiledXY|2Dseries"'.format(os.path.abspath(folderNameMIP + r"\xml_merging.xml"), os.path.abspath(stitchedFolder)))
    ## stitch in tera stitcher if all the images of MIPS were saved
    if configuration.saveImages == True:
        folderNameMIPSaved = folderNameMIP + "/savedImages"
        os.system('terastitcher --import --volin="{}" --ref1=-Y --ref2=X --ref3=Z --vxl1={} --vxl2={} --vxl3={} --projout=xml_import'.format(os.path.abspath(folderNameMIPSaved), pixelSize, pixelSize, configuration.zStep))
        os.system('terastitcher --displcompute --projin="{}"'.format(os.path.abspath(folderNameMIPSaved  + r"\xml_import.xml")))
        os.system('terastitcher --displproj --projin="{}"'.format(os.path.abspath(folderNameMIPSaved  + r"\xml_displcomp.xml")))
        os.system('terastitcher --displthres --threshold={} --projin="{}"'.format(configuration.threshhold, os.path.abspath( folderNameMIPSaved  + r"\xml_displproj.xml")))
        os.system('terastitcher --placetiles --projin="{}"'.format(os.path.abspath(folderNameMIPSaved  + r"\xml_displthres.xml")))
        stitchedFolder = folderNameMIPSaved  + r"\stitched"
        if not os.path.exists(stitchedFolder):
            os.makedirs(stitchedFolder)
        os.system('terastitcher --merge --projin="{}" --volout="{}" --volout_plugin="TiledXY|2Dseries"'.format(os.path.abspath(folderNameMIPSaved + r"\xml_merging.xml"), os.path.abspath(stitchedFolder)))
    ## stitch DAPI in tera stitcher
    os.system('terastitcher --import --volin="{}" --ref1=-Y --ref2=X --ref3=Z --vxl1={} --vxl2={} --vxl3={} --projout=xml_import'.format(os.path.abspath(folderNameFluorescence), pixelSize, pixelSize, configuration.zStep))
    os.system('terastitcher --displcompute --projin="{}"'.format(os.path.abspath(folderNameFluorescence + r"\xml_import.xml")))
    os.system('terastitcher --displproj --projin="{}"'.format(os.path.abspath(folderNameFluorescence + r"\xml_displcomp.xml")))
    os.system('terastitcher --displthres --threshold={} --projin="{}"'.format(configuration.threshhold, os.path.abspath(folderNameFluorescence + r"\xml_displproj.xml")))
    os.system('terastitcher --placetiles --projin="{}"'.format(os.path.abspath(folderNameMIP + r"\xml_displthres.xml")))
    stitchedFolder = folderNameFluorescence + r"\stitched"
    if not os.path.exists(stitchedFolder):
        os.makedirs(stitchedFolder)
    os.system('terastitcher --merge --projin="{}" --volout="{}" --volout_plugin="TiledXY|2Dseries"'.format(os.path.abspath(folderNameFluorescence + r"\xml_merging.xml"), os.path.abspath(stitchedFolder)))
Ejemplo n.º 11
0
def getOverviewAndSaveZ(FolderToSaveTo, RightX, LeftX, BottomY, TopY, upperZ,
                        lowerZ, highestFocusZ, flatField, mmc):
    mmc.assignImageSynchro('ZeissXYStage')
    mmc.assignImageSynchro('IDS uEye')
    imageWidth = mmc.getImageWidth()
    imageHeight = mmc.getImageHeight()
    pixelSize = mmc.getPixelSizeUm()  ## for ids uEye at 20x magnification
    imageWidthUM = pixelSize * imageWidth
    imageHeightUM = pixelSize * imageHeight
    configuration = Configuration()
    notOverlap = configuration.notOverlap
    ### intialize iteration, intitalize the row which will be concatenated
    iteration = 0
    ## get the number of images that will be taken and make an array with that many
    numberImagesRow = math.ceil(
        abs((RightX) - (LeftX)) / imageWidthUM / notOverlap) + 1
    numberImagesColumn = math.ceil(
        abs((TopY) - (BottomY)) / imageHeightUM / notOverlap) + 2
    numberImagesArrayRow = np.arange(0, numberImagesRow)
    numberImagesArrayColumn = np.arange(0, numberImagesColumn)
    ## make an array with all the X and Y coordinates (need to start at RightX and BottomY)
    imageHeightArray = np.add(
        numberImagesArrayColumn * imageHeightUM * notOverlap,
        BottomY - imageHeightUM * notOverlap)
    print imageHeightArray
    imageWidthArray = np.add(numberImagesArrayRow * imageWidthUM * notOverlap,
                             RightX)
    print imageWidthArray
    ### intialize iteration and list of coordinates
    iteration = 0
    ### initialize list of coordinates
    middleZ = upperZ - (upperZ - lowerZ) / 2
    ### go into correct folder
    initialDir = os.getcwd()
    if not os.path.exists(FolderToSaveTo):
        os.makedirs(FolderToSaveTo)
    os.chdir(FolderToSaveTo)
    ### Start in upper left corner and go to the bottom left
    for y in range(len(imageHeightArray) - 1, -1,
                   -1):  ## go from top down, 0 indexed
        ## make folder for this Y coordinate
        currentY = imageHeightArray[y]
        folder = str(currentY)  #make the folder name the y index
        if not os.path.exists(folder):
            os.makedirs(folder)
        ## go through x for even iteration
        if (iteration % 2 == 0):
            ## go from Right to left
            for x in range(0, len(imageWidthArray)):
                ## go to correct x,y location
                currentX = imageWidthArray[x]
                mmc.setXYPosition(currentX, currentY)
                ## add this xy coordinate to the list of xy coordinates and put z in the middle
                ## make folder for this X coordinate
                subfolder = folder + "/" + str(currentX)
                if not os.path.exists(subfolder):
                    os.makedirs(subfolder)
                zStackTiffs(subfolder, upperZ, lowerZ, flatField, mmc)
        ## go through x for odd iteration
        else:
            ## go from left to right
            for x in range(len(imageWidthArray) - 1, -1,
                           -1):  ##go from Left to Right
                ## go to correct x,y location
                currentX = imageWidthArray[x]
                mmc.setXYPosition(currentX, currentY)
                ## add this xy coordinate to the list of xy coordinates and put z in the middle
                ## make folder for this X coordinate
                subfolder = folder + "/" + str(currentX)
                if not os.path.exists(subfolder):
                    os.makedirs(subfolder)
                zStackTiffs(subfolder, upperZ, lowerZ, flatField, mmc)
        iteration = iteration + 1
    os.chdir(initialDir)
    return imageHeightArray, imageWidthArray
Ejemplo n.º 12
0
def getOverviewAndSaveMIP(folder, RightX, LeftX, BottomY, TopY, upperZ, lowerZ,
                          flatField, mmc):
    mmc.assignImageSynchro('ZeissXYStage')
    mmc.assignImageSynchro('IDS uEye')
    ## go to correct folder
    initialDir = os.getcwd()
    if not os.path.exists(folder):
        os.makedirs(folder)
    os.chdir(folder)
    ## get necessary information
    imageWidth = mmc.getImageWidth()
    imageHeight = mmc.getImageHeight()
    pixelSize = mmc.getPixelSizeUM()  ## for ids uEye at 20x magnification
    imageWidthUM = pixelSize * imageWidth
    imageHeightUM = pixelSize * imageHeight
    configuration = Configuration()
    notOverlap = configuration.notOverlap
    resolution = configuration.resolution
    ### intialize iteration, intitalize the row which will be concatenated
    iteration = 0
    ## initialze the list of (x,y,z) 3-tuples which will be returned for use in the DAPI method
    XYZCoordList = []
    ## get the number of images that will be taken and make an array with that many
    numberImagesRow = math.ceil(
        abs((RightX) - (LeftX)) / imageWidthUM / notOverlap) + 1
    numberImagesColumn = math.ceil(
        abs((TopY) - (BottomY)) / imageHeightUM / notOverlap) + 2
    numberImagesArrayRow = np.arange(0, numberImagesRow)
    numberImagesArrayColumn = np.arange(0, numberImagesColumn)
    ## initialize the size of one row
    rowWidth = (numberImagesArrayRow[len(numberImagesArrayRow) - 1] + 1) * int(
        imageWidth * notOverlap
    )  ## need to add 1 because we need the total size of the array, if we don't add 1 it's the size of the array up to the last picture
    image = np.empty([0, int(rowWidth)])
    ## make an array with all the X and Y coordinates (need to start at RightX and BottomY)
    imageHeightArray = np.add(
        numberImagesArrayColumn * imageHeightUM * notOverlap,
        BottomY - imageHeightUM * notOverlap)
    imageWidthArray = np.add(numberImagesArrayRow * imageWidthUM * notOverlap,
                             RightX)
    ### Start in upper left corner and go to the bottom left
    for y in range(len(imageHeightArray) - 1, -1,
                   -1):  ## go from top down, 0 indexed
        ## make folder for this Y coordinate
        currentY = imageHeightArray[y]
        if (iteration % 2 == 0):  ## it is an even iteration
            ## initialize the row
            row = np.empty([int(imageHeight * notOverlap), 0])
            ## go from Right to left
            for x in range(0, len(imageWidthArray)):
                ## go to correct x,y location
                currentX = imageWidthArray[x]
                mmc.setXYPosition(currentX, currentY)
                ## go make MIP at current XY location and find most in focus Z
                if configuration.saveImages == True:
                    folderOfSavedImages = folder + "/savedImages"
                    array, hvLayer = makeMIP(upperZ, lowerZ, flatField, mmc,
                                             folderOfSavedImages)
                else:
                    array, hvLayer = makeMIP(upperZ, lowerZ, flatField, mmc)
                ## save the MIP
                foldername = str(currentY) + "/" + str(
                    currentX)  #make the folder name the y index
                if not os.path.exists(foldername):
                    os.makedirs(foldername)
                filename = foldername + "/000000.tiff"
                imsave16(filename, array)
                # stitched the cropped mip
                croppedArray = array[0:int(imageHeight * notOverlap):1,
                                     0:int(imageWidth * notOverlap):1]
                row = np.concatenate((row, croppedArray), axis=1)
                #Add xyz 3-tuple to list
                XYZCoordList = XYZCoordList + [(currentX, currentY, hvLayer)]
            # concatenate rows together
            image = np.concatenate((image, row), axis=0)
        else:
            ## initialize the row
            row = np.empty([int(imageHeight * notOverlap), 0])
            ## go from left to right
            for x in range(len(imageWidthArray) - 1, -1, -1):
                ## go to correct x,y location
                currentX = imageWidthArray[x]
                mmc.setXYPosition(currentX, currentY)
                ## go make MIP at current XY location and find most in focus Z
                if configuration.saveImages == True:
                    folderOfSavedImages = folder + "/savedImages"
                    array, hvLayer = makeMIP(upperZ, lowerZ, flatField, mmc,
                                             folderOfSavedImages)
                else:
                    array, hvLayer = makeMIP(upperZ, lowerZ, flatField, mmc)
                ## Save the MIP
                foldername = str(currentY) + "/" + str(
                    currentX)  #make the folder name the y index
                if not os.path.exists(foldername):
                    os.makedirs(foldername)
                filename = foldername + "/000000.tiff"
                imsave16(filename, array)
                # stitch the cropped mip
                croppedArray = array[0:int(imageHeight * notOverlap):1,
                                     0:int(imageWidth * notOverlap):1]
                row = np.concatenate((croppedArray, row), axis=1)
                #Add xyz 3-tuple to list
                XYZCoordList = XYZCoordList + [(currentX, currentY, hvLayer)]
            # concatenate rows together
            image = np.concatenate((image, row), axis=0)
        iteration = iteration + 1
    ## go back to initial folder
    os.chdir(initialDir)
    MIPName = folder + ".tiff"
    ## make sure to test medium and low resolution!
    if resolution == 'high':
        imsave(MIPName, image)
    if resolution == 'medium':
        imMedium = imresize(image, (image.shape[0] / 2, image.shape[1] / 2))
        imsave(MIPName, imMedium)
    if resolution == 'low':
        imLow = imresize(image, (image.shape[0] / 4, image.shape[1] / 4))
        imsave(MIPName, imLow)
    ## return XYZCoordList
    return XYZCoordList
Ejemplo n.º 13
0
def getOverviewAndSaveXY(FolderToSaveTo, RightX, LeftX, BottomY, TopY,
                         flatField, mmc):
    mmc.assignImageSynchro('ZeissXYStage')
    mmc.assignImageSynchro('IDS uEye')
    imageWidth = mmc.getImageWidth()
    imageHeight = mmc.getImageHeight()
    pixelSize = mmc.getPixelSizeUm()  ## for ids uEye at 20x magnification
    imageWidthUM = pixelSize * imageWidth
    imageHeightUM = pixelSize * imageHeight
    configuration = Configuration()
    notOverlap = configuration.notOverlap
    ### intialize iteration, intitalize the row which will be concatenated
    iteration = 0
    ## get the number of images that will be taken and make an array with that many
    numberImagesRow = math.ceil(
        abs((RightX) - (LeftX)) / imageWidthUM / notOverlap) + 1
    numberImagesColumn = math.ceil(
        abs((TopY) - (BottomY)) / imageHeightUM / notOverlap) + 2
    numberImagesArrayRow = np.arange(0, numberImagesRow)
    numberImagesArrayColumn = np.arange(0, numberImagesColumn)
    ## make an array with all the X and Y coordinates (need to start at RightX and BottomY)
    imageHeightArray = np.add(
        numberImagesArrayColumn * imageHeightUM * notOverlap,
        BottomY - imageHeightUM * notOverlap)
    print imageHeightArray
    imageWidthArray = np.add(numberImagesArrayRow * imageWidthUM * notOverlap,
                             RightX)
    print imageWidthArray
    ### intialize iteration
    iteration = 0
    ## go into correct directory
    initialDir = os.getcwd()
    if not os.path.exists(FolderToSaveTo):
        os.makedirs(FolderToSaveTo)
    os.chdir(FolderToSaveTo)
    ### Start in upper riught corner and go to the bottom left
    for y in range(len(imageHeightArray) - 1, -1,
                   -1):  ## go from top down, 0 indexed
        ## make folder for this Y coordinate
        currentY = imageHeightArray[y]
        ## go through x on an even iteration
        if (iteration % 2 == 0):
            ## go from Right to left
            for x in range(0, len(imageWidthArray)):
                ## go to correct x,y location
                currentX = imageWidthArray[x]
                mmc.setXYPosition(currentX, currentY)
                ## make folder for this X coordinate
                foldername = str(currentY) + "/" + str(
                    currentX)  #make the folder name the y index
                if not os.path.exists(foldername):
                    os.makedirs(foldername)
                filename = foldername + "/000000.tiff"
                ## move and take photo
                mmc.snapImage()
                singleLayer = mmc.getImage()
                singleLayer = flatFieldCorrection(flatField, singleLayer, mmc)
                ## save tiff at the filename
                imsave(filename, singleLayer)
        ## go through x on an odd iteration
        else:
            ## go from left to right
            for x in range(len(imageWidthArray) - 1, -1, -1):
                ## go to correct x,y location
                currentX = imageWidthArray[x]
                mmc.setXYPosition(currentX, currentY)
                ## make folder for this X coordinate
                foldername = str(currentY) + "/" + str(
                    currentX)  #make the folder name the y index
                if not os.path.exists(foldername):
                    os.makedirs(foldername)
                filename = foldername + "/000000.tiff"
                ## move and take photo
                mmc.snapImage()
                singleLayer = mmc.getImage()
                singleLayer = flatFieldCorrection(flatField, singleLayer, mmc)
                ## save tiff at the filename
                imsave(filename, singleLayer)
        iteration = iteration + 1
    ## go back to initial working directory for the next step
    os.chdir(initialDir)
Ejemplo n.º 14
0
def findSample(mmc):
    ## go to each position
    mmc.assignImageSynchro('ZeissXYStage')
    mmc.assignImageSynchro('IDS uEye')
    ## relevant info
    imageWidth = mmc.getImageWidth()
    imageHeight = mmc.getImageHeight()
    pixelSize = mmc.getPixelSizeUm()  ## for ids uEye at 20x magnification
    imageWidthUM = pixelSize * imageWidth
    imageHeightUM = pixelSize * imageHeight
    configuration = Configuration()
    numberOfPictures = configuration.numberOfPictures
    distanceBetweenPictures = configuration.distanceBetweenPictures
    ## take 4 images in row and 4 in column for a total of 16
    numberImagesArrayRow = np.arange(0, numberOfPictures)
    numberImagesArrayColumn = np.arange(0, numberOfPictures)
    ## make an array with all the X and Y coordinates (need to start at RightX and TopY)
    # assume it starts at a relatively centered position, so set rightX and TopY to be right and up
    RightX = mmc.getXPosition() - distanceBetweenPictures * 2 - imageWidth * 2
    TopY = mmc.getYPosition() + distanceBetweenPictures * 2 + imageWidth * 2
    # create an array of the indeces the images will be taken at
    distanceBetweenPicturesArray = np.arange(
        0, distanceBetweenPictures * numberOfPictures, distanceBetweenPictures)
    imageHeightArray = np.add(numberImagesArrayColumn * imageHeightUM, TopY)
    imageWidthArray = np.add(numberImagesArrayRow * imageWidthUM, RightX)
    imageHeightArrayWithOffset = np.add(imageHeightArray,
                                        distanceBetweenPicturesArray)
    imageWidthArrayWithOffset = np.add(imageWidthArray,
                                       distanceBetweenPicturesArray)
    ### intialize iteration
    iteration = 0
    ### Start in upper right corner and go to the bottom left
    for y in range(len(imageHeightArrayWithOffset) - 1, 0,
                   -1):  ## go from top down, 0 indexed
        ## make folder for this Y coordinate
        currentY = imageHeightArrayWithOffset[y]
        ## go through x on an even iteration
        if (iteration % 2 == 0):
            ## go from Right to left
            for x in range(0, len(imageWidthArrayWithOffset)):
                ## go to correct x,y location
                currentX = imageWidthArrayWithOffset[x]
                mmc.setXYPosition(currentX, currentY)
                ## move and take photo
                mmc.snapImage()
                singleLayer = mmc.getImage()
                #singleLayer[singleLayer >= 255] = 255
                ## threshold and see which case
                singleLayer = threshholding(singleLayer)
                if whichCase(singleLayer) is not 'j':
                    return 'true'
        ## go through x on an odd iteration
        else:
            ## go from left to right
            for x in range(len(imageWidthArrayWithOffset) - 1, -1, -1):
                ## go to correct x,y location
                currentX = imageWidthArrayWithOffset[x]
                mmc.setXYPosition(currentX, currentY)
                ## move and take photo
                mmc.snapImage()
                singleLayer = mmc.getImage()
                #singleLayer[singleLayer >= 255] = 255
                ## threshold and see which case
                singleLayer = threshholding(singleLayer)
                if whichCase(singleLayer) is not 'j':
                    return 'true'
        iteration = iteration + 1

    return 'false'
def fluorescenceAcquisition(coordinatesList, folder, flatField, mmc):
    mmc.assignImageSynchro('ZeissXYStage')
    mmc.assignImageSynchro('IDS uEye')
    ## get initialFolder
    initialDir = os.getcwd()
    ## make folder
    if not os.path.exists(folder):
        os.makedirs(folder)
    ## change folder
    os.chdir(folder)
    ## change the reflector turret to DAPI
    DAPIOn(mmc)
    ## get information to construct the stitched image
    pixelSize = mmc.getPixelSizeUm()
    imageHeight = mmc.getImageHeight()
    imageWidth = mmc.getImageWidth()
    configuration = Configuration()
    notOverlap = configuration.notOverlap
    ## initialize the size of one row
    ## for ids uEye at 20x magnification
    imageWidthUM = pixelSize * imageWidth
    imageHeightUM = pixelSize * imageHeight
    ## get the number of images that will be taken and make an array with that many
    # number of images
    numberImagesRow = math.ceil(
        abs((min(x[0] for x in coordinatesList)) -
            (max(x[0]
                 for x in coordinatesList))) / imageWidthUM / notOverlap) + 1
    numberImagesColumn = math.ceil(
        abs((max(y[1] for y in coordinatesList)) -
            (min(y[1]
                 for y in coordinatesList))) / imageHeightUM / notOverlap) + 1
    # number of images as an array
    numberImagesArrayRow = np.arange(0, numberImagesRow)
    numberImagesArrayColumn = np.arange(0, numberImagesColumn)
    ## initialize the size of one row
    rowWidth = (numberImagesArrayRow[len(numberImagesArrayRow) - 1] + 1) * (
        imageWidth * notOverlap
    )  ## need to add 1 because we need the total size of the array, if we don't add 1 it's the size of the array up to the last picture
    columnHeight = (numberImagesArrayColumn[len(numberImagesArrayColumn) - 1] +
                    1) * (imageHeight * notOverlap
                          )  ## add 2 for same reason as above
    ## make the matrix
    imageSoFar = np.zeros([int(rowWidth), int(columnHeight)])
    # Convert coordinates into pixels
    pixCoord = np.array(coordinatesList)
    pixCoord = pixCoord / pixelSize
    pixCoord[:, 0] = pixCoord[:, 0] - np.amin(pixCoord[:, 0])
    pixCoord[:, 1] = np.amax(pixCoord[:, 1]) - pixCoord[:, 1]
    ## traverse the coordinate list
    for i in range(0, len(coordinatesList)):
        ## get the x y z coordinates
        x = coordinatesList[i][0]
        y = coordinatesList[i][1]
        z = coordinatesList[i][2]
        ## travel to that x y z coordinate
        mmc.setXYPosition(x, y)
        mmc.setPosition(z)
        ## take the image
        mmc.snapImage()
        img = mmc.getImage()
        img = flatFieldCorrection(flatField, img, mmc)
        ## save the image in Y/X/Z.tiff folders
        path = str(y) + "/" + str(x)
        if not os.path.exists(path):
            os.makedirs(path)
        filePath = path + "/" + str(z) + ".tiff"
        print img.dtype
        imsave16(filePath, img)
        imageSoFar = stitchDAPI(imageSoFar, pixCoord[i, 0], pixCoord[i, 1],
                                img.T, mmc)
    ## change the reflector turret back to BF
    DAPIOff(mmc)
    ## change folder back
    os.chdir(initialDir)
    ## save the image
    imageSoFar = stitchToEnd(imageSoFar.T, mmc)
    imageSoFar = imageSoFar.astype('uint16')
    print imageSoFar.dtype
    imsave(folder + "DAPI.tiff", imageSoFar)