示例#1
0
def makeBeamBlockerMask(inputImg, maskImg):
    img = cv2.imread(inputImg, 0)
    gradImg = flt.sobel(img)
    bImg = gradImg > numpy.percentile(gradImg, 99.5)
    bImg = filters.areaFilter(bImg)
    labelImg, numLabel, dictionary = imageProcess.regionProps(bImg)
    line1 = [
        dictionary['centroid'][0][0], dictionary['centroid'][0][1],
        dictionary['orientation'][0]
    ]
    line2 = [
        dictionary['centroid'][1][0], dictionary['centroid'][1][1],
        dictionary['orientation'][1]
    ]
    bImg = imageDraw.fillBetweenLines([line1, line2], bImg)
    bImg = imageProcess.binary_dilation(bImg, iterations=25)
    bImg = numpy.logical_not(bImg)
    cv2.imwrite(maskImg, bImg * 255)

    plt.figure()
    plt.subplot(121), plt.imshow(img)
    plt.subplot(122), plt.imshow(bImg)
    plt.show()

    return None
示例#2
0
def generateLabelImages(fp,
                        imgDir,
                        fontScale=1,
                        size=1,
                        rank=0,
                        structure=[[1, 1, 1], [1, 1, 1], [1, 1, 1]]):
    [row, col, numFrames, frameList] = misc.getVitals(fp)
    particleList = fp.attrs['particleList']
    zfillVal = fp.attrs['zfillVal']
    procFrameList = numpy.array_split(frameList, size)
    for frame in procFrameList[rank]:
        labelImg = fp['/segmentation/labelStack/' +
                      str(frame).zfill(zfillVal)].value
        gImg = fp['/dataProcessing/gImgRawStack/' +
                  str(frame).zfill(zfillVal)].value
        bImg = labelImg.astype('bool')
        bImgBdry = imageProcess.normalize(imageProcess.boundary(bImg))
        label, numLabel, dictionary = imageProcess.regionProps(
            bImg, gImg, structure=structure, centroid=True)
        bImg = imageProcess.normalize(bImg)
        for j in range(len(dictionary['id'])):
            bImgLabelN = label == dictionary['id'][j]
            ID = numpy.max(bImgLabelN * labelImg)
            bImg = imageProcess.textOnGrayImage(
                bImg,
                str(ID), (int(dictionary['centroid'][j][0]) + 3,
                          int(dictionary['centroid'][j][1]) - 3),
                fontScale=fontScale,
                color=127,
                thickness=1)
        finalImage = numpy.column_stack((bImg, numpy.maximum(bImgBdry, gImg)))
        cv2.imwrite(imgDir + '/' + str(frame).zfill(zfillVal) + '.png',
                    finalImage)
    return 0
示例#3
0
def generateLabelImagesMatplotlib(fp,
                                  imgDir,
                                  fontScale=1,
                                  size=1,
                                  rank=0,
                                  structure=[[1, 1, 1], [1, 1, 1], [1, 1, 1]]):
    [row, col, numFrames, frameList] = misc.getVitals(fp)
    particleList = fp.attrs['particleList']
    zfillVal = fp.attrs['zfillVal']
    procFrameList = numpy.array_split(frameList, size)
    fig = plt.figure(figsize=(2, 1))
    ax1 = fig.add_axes([0, 0, 0.5, 1])
    ax2 = fig.add_axes([0.5, 0, 0.5, 1])
    for frame in procFrameList[rank]:
        labelImg = fp['/segmentation/labelStack/' +
                      str(frame).zfill(zfillVal)].value
        gImg = fp['/dataProcessing/gImgRawStack/' +
                  str(frame).zfill(zfillVal)].value
        gImgBlur = fp['/dataProcessing/filterStack/' +
                      str(frame).zfill(zfillVal)].value
        id_center = []
        for label in numpy.unique(labelImg)[1:]:
            bImgLabelN = labelImg == label
            temp1, temp2, dictionary = imageProcess.regionProps(
                bImgLabelN, bImgLabelN, structure=structure, centroid=True)
            id_center.append([
                label, dictionary['centroid'][0][0],
                dictionary['centroid'][0][1]
            ])
        ax1.imshow(gImg)
        ax1.imshow(labelImg, cmap='jet', alpha=0.5, vmax=100)
        ax2.imshow(gImgBlur)
        for label, r, c in id_center:
            ax1.text(c, r, label, color='#FFFFFF', fontsize=1.5)
        ax1.get_xaxis().set_visible(False)
        ax1.get_yaxis().set_visible(False)
        ax2.get_xaxis().set_visible(False)
        ax2.get_yaxis().set_visible(False)
        plt.savefig(imgDir + '/' + str(frame).zfill(zfillVal) + '.png')
        ax1.cla(), ax2.cla()
    plt.close()
    return 0
示例#4
0
            if (flag == False):
                bImgCrop, flag = fitFunc.fitting(gImgCrop, -theta)
            bImgCropBdry = imageProcess.normalize(
                imageProcess.boundary(bImgCrop))
            bImgBdry[int(rCenter) - cropSize:int(rCenter) + cropSize + 1,
                     int(cCenter) - cropSize:int(cCenter) + cropSize +
                     1] = bImgCropBdry

            #muR,muC,majorAxis,minorAxis,theta

            if (flag == True):
                bImg = imageProcess.fillHoles(bImgBdry)
                label, numLabel, dictionary = imageProcess.regionProps(
                    bImg,
                    gImgRaw,
                    structure=[[1, 1, 1], [1, 1, 1], [1, 1, 1]],
                    centroid=True,
                    area=True,
                    effRadius=True)
                outFile.write(
                    "%d 1 %f %f %f %f\n" %
                    (frame, dictionary['centroid'][0][0],
                     dictionary['centroid'][0][1], dictionary['effRadius'][0],
                     dictionary['area'][0] * pixInNM * pixInNM))
                #outFile.write("%d 1 %f %f %f %f %f %f\n" %(frame,int(rCenter)-cropSize+muR,int(cCenter)-cropSize+muC,theta,numpy.pi*majorAxis*minorAxis,majorAxis,minorAxis))

                #frame,particle,r,c,rad,area,a,b,theta

    finalImg = numpy.column_stack((numpy.maximum(gImgNorm,
                                                 bImgBdry), gImgNorm))
    cv2.imwrite(
示例#5
0
def labelParticles(fp,
                   centerDispRange=[5, 5],
                   perAreaChangeRange=[10, 20],
                   missFramesTh=10,
                   structure=[[0, 1, 0], [1, 1, 1], [0, 1, 0]]):

    [row, col,
     numFrames] = fp.attrs['row'], fp.attrs['col'], fp.attrs['numFrames']
    frameList = fp.attrs['frameList']
    zfillVal = fp.attrs['zfillVal']

    labelStack = numpy.zeros([row, col, numFrames], dtype='uint32')
    for frame in frameList:
        str1 = str(frame) + '/' + str(frameList[-1])
        str2 = '\r' + ' ' * len(str1) + '\r'
        sys.stdout.write(str1)
        bImg = fp['/segmentation/bImgStack/' +
                  str(frame).zfill(zfillVal)].value
        gImg = fp['/dataProcessing/gImgRawStack/' +
                  str(frame).zfill(zfillVal)].value

        if (frame == frameList[0]):
            labelImg_0, numLabel_0, dictionary_0 = imageProcess.regionProps(
                bImg, gImg, structure=structure, centroid=True, area=True)
            maxID = numLabel_0
            occurenceFrameList = [frame] * maxID
            dictionary_0['frame'] = []
            for i in range(len(dictionary_0['id'])):
                dictionary_0['frame'].append(frame)
            labelStack[:, :, frame - 1] = labelImg_0
        else:
            labelImg_1, numLabel_1, dictionary_1 = imageProcess.regionProps(
                bImg, gImg, structure=structure, centroid=True, area=True)
            if (numLabel_1 > 0):
                areaMin = min(dictionary_1['area'])
                areaMax = max(dictionary_1['area'])
            for i in range(len(dictionary_1['id'])):
                flag = 0
                bImg_1_LabelN = labelImg_1 == dictionary_1['id'][i]
                center_1 = dictionary_1['centroid'][i]
                area_1 = dictionary_1['area'][i]
                frame_1 = frame
                if (areaMax - areaMin > 0):
                    factor = 1.0 * (area_1 - areaMin) / (areaMax - areaMin)
                    perAreaChangeTh = perAreaChangeRange[1] - factor * (
                        perAreaChangeRange[1] - perAreaChangeRange[0])
                    centerDispTh = centerDispRange[1] - factor * (
                        centerDispRange[1] - centerDispRange[0])
                else:
                    perAreaChangeTh = perAreaChangeRange[1]
                    centerDispTh = centerDispRange[1]
                closeness, J = 1e10, 0
                for j in range(len(dictionary_0['id']) - 1, -1, -1):
                    center_0 = dictionary_0['centroid'][j]
                    area_0 = dictionary_0['area'][j]
                    frame_0 = dictionary_0['frame'][j]
                    centerDisp = numpy.sqrt((center_1[0] - center_0[0])**2 +
                                            (center_1[1] - center_0[1])**2)
                    perAreaChange = 100.0 * numpy.abs(area_1 -
                                                      area_0) / numpy.maximum(
                                                          area_1, area_0)
                    missFrames = frame_1 - frame_0
                    if (centerDisp <= centerDispTh):
                        if (perAreaChange <= perAreaChangeTh):
                            if (missFrames <= missFramesTh):
                                if (centerDisp < closeness):
                                    closeness = centerDisp
                                    J = j
                                    flag = 1

                if (flag == 1):
                    labelStack[:, :, frame -
                               1] += (bImg_1_LabelN *
                                      dictionary_0['id'][J]).astype('uint32')
                    dictionary_0['centroid'][J] = center_1
                    dictionary_0['area'][J] = area_1
                    dictionary_0['frame'][J] = frame
                if (flag == 0):
                    maxID += 1
                    occurenceFrameList.append(frame)
                    labelN_1 = bImg_1_LabelN * maxID
                    labelStack[:, :, frame - 1] += labelN_1.astype('uint32')
                    dictionary_0['id'].append(maxID)
                    dictionary_0['centroid'].append(center_1)
                    dictionary_0['area'].append(area_1)
                    dictionary_0['frame'].append(frame)
        sys.stdout.flush()
        sys.stdout.write(str2)
    sys.stdout.flush()

    #if (labelStack.max() < 256):
    #labelStack = labelStack.astype('uint8')
    #elif (labelStack.max()<65536):
    #labelStack = labelStack.astype('uint16')

    print "Checking for multiple particles in a single frame"
    for frame in frameList:
        labelImg = labelStack[:, :, frame - 1]
        numLabel = imageProcess.regionProps(labelImg.astype('bool'),
                                            gImg,
                                            structure=structure)[1]
        if (numLabel != numpy.size(numpy.unique(labelImg)[1:])):
            for N in numpy.unique(labelImg)[1:]:
                labelImgN = labelImg == N
                numLabel = imageProcess.regionProps(labelImgN,
                                                    gImg,
                                                    structure=structure)[1]
                if (numLabel > 1):
                    labelImg[labelImg == N] = 0
                    labelStack[:, :, frame - 1] = labelImg

    for frame in frameList:
        fileIO.writeH5Dataset(
            fp, '/segmentation/labelStack/' + str(frame).zfill(zfillVal),
            labelStack[:, :, frame - 1])
    del labelStack
    return maxID, occurenceFrameList
 labelImg = fp['/segmentation/labelStack/' +
               str(frame).zfill(zfillVal)].value
 gImgRaw = fp['/dataProcessing/gImgRawStack/' +
              str(frame).zfill(zfillVal)].value
 outFile.write("%f " % (1.0 * frame / fps))
 for particle in particleList:
     bImg = labelImg == particle
     if (bImg.max() == True):
         label, numLabel, dictionary = imageProcess.regionProps(
             bImg,
             gImgRaw,
             structure=structure,
             centroid=centroid,
             area=area,
             perimeter=perimeter,
             circularity=circularity,
             pixelList=pixelList,
             bdryPixelList=bdryPixelList,
             effRadius=effRadius,
             radius=radius,
             circumRadius=circumRadius,
             inRadius=inRadius,
             radiusOFgyration=radiusOFgyration)
         outFile.write("%f %f %f %f %f %f " %
                       (dictionary['centroid'][0][1] * pixInNM,
                        (row - dictionary['centroid'][0][0]) * pixInNM,
                        dictionary['area'][0] * pixInNM * pixInNM,
                        dictionary['perimeter'][0] * pixInNM,
                        dictionary['circularity'][0],
                        dictionary['effRadius'][0] * pixInNM))
     else:
示例#7
0
def labelSubstacks(fp, frameList, comm, size, rank, centerDispRange,
                   perAreaChangeRange, missFramesTh, structure):
    if (rank == 0):
        print "Labelling image stack"
    labelStack = numpy.zeros([row, col, len(frameList)], dtype='uint32')
    for frame in frameList:
        bImg = fp['/segmentation/bImgStack/' +
                  str(frame).zfill(zfillVal)].value
        gImg = fp['/dataProcessing/gImgRawStack/' +
                  str(frame).zfill(zfillVal)].value
        if (frame == frameList[0]):
            labelImg_0, numLabel_0, dictionary_0 = imageProcess.regionProps(
                bImg, gImg, structure=structure, centroid=True, area=True)
            maxID = numLabel_0
            dictionary_0['frame'] = []
            dictionary_0['initialCentroid'], dictionary_0[
                'initialArea'], dictionary_0['initialFrame'] = [], [], []
            for i in range(len(dictionary_0['id'])):
                dictionary_0['frame'].append(frame)
                dictionary_0['initialCentroid'].append(
                    dictionary_1['centroid'][i])
                dictionary_0['initialArea'].append(dictionary_1['area'][i])
                dictionary_0['initialFrame'].append(frame)
            labelStack[:, :, frame - frameList[0]] = labelImg_0
        else:
            labelImg_1, numLabel_1, dictionary_1 = imageProcess.regionProps(
                bImg, gImg, structure=structure, centroid=True, area=True)
            if (numLabel_1 > 0):
                areaMin = min(dictionary_1['area'])
                areaMax = max(dictionary_1['area'])
            for i in range(len(dictionary_1['id'])):
                flag = 0
                bImg_1_LabelN = labelImg_1 == dictionary_1['id'][i]
                center_1 = dictionary_1['centroid'][i]
                area_1 = dictionary_1['area'][i]
                frame_1 = frame
                if (areaMax - areaMin > 0):
                    factor = 1.0 * (area_1 - areaMin) / (areaMax - areaMin)
                    perAreaChangeTh = perAreaChangeRange[1] - factor * (
                        perAreaChangeRange[1] - perAreaChangeRange[0])
                    centerDispTh = centerDispRange[1] - factor * (
                        centerDispRange[1] - centerDispRange[0])
                else:
                    perAreaChangeTh = perAreaChangeRange[1]
                    centerDispTh = centerDispRange[1]
                closeness, J = 1e10, 0
                for j in range(len(dictionary_0['id']) - 1, -1, -1):
                    center_0 = dictionary_0['centroid'][j]
                    area_0 = dictionary_0['area'][j]
                    frame_0 = dictionary_0['frame'][j]
                    centerDisp = numpy.sqrt((center_1[0] - center_0[0])**2 +
                                            (center_1[1] - center_0[1])**2)
                    perAreaChange = 100.0 * numpy.abs(area_1 -
                                                      area_0) / numpy.maximum(
                                                          area_1, area_0)
                    missFrames = frame_1 - frame_0
                    if (centerDisp <= centerDispTh):
                        if (perAreaChange <= perAreaChangeTh):
                            if (missFrames <= missFramesTh):
                                if (centerDisp < closeness):
                                    closeness = centerDisp
                                    J = j
                                    flag = 1

                if (flag == 1):
                    labelStack[:, :, frame - frameList[0]] += (
                        bImg_1_LabelN * dictionary_0['id'][J]).astype('uint32')
                    dictionary_0['centroid'][J] = center_1
                    dictionary_0['area'][J] = area_1
                    dictionary_0['frame'][J] = frame
                if (flag == 0):
                    maxID += 1
                    labelN_1 = bImg_1_LabelN * maxID
                    labelStack[:, :, frame -
                               frameList[0]] += labelN_1.astype('uint32')
                    dictionary_0['id'].append(maxID)
                    dictionary_0['centroid'].append(center_1)
                    dictionary_0['area'].append(area_1)
                    dictionary_0['frame'].append(frame)
                    dictionary_0['initialCentroid'].append(center_1)
                    dictionary_0['initialArea'].append(area_1)
                    dictionary_0['initialFrame'].append(frame)

    if (rank == 0):
        print "Checking for multiple particles in a single frame"
    for frame in frameList:
        labelImg = labelStack[:, :, frame - frameList[0]]
        numLabel = imageProcess.regionProps(labelImg.astype('bool'),
                                            gImg,
                                            structure=structure)[1]
        if (numLabel != numpy.size(numpy.unique(labelImg)[1:])):
            for N in numpy.unique(labelImg)[1:]:
                labelImgN = labelImg == N
                numLabel = imageProcess.regionProps(labelImgN,
                                                    gImg,
                                                    structure=structure)[1]
                if (numLabel > 1):
                    labelImg[labelImg == N] = 0
                    labelStack[:, :, frame - frameList[0]] = labelImg

    numpy.save('labelStack_' + str(rank) + '.npy', labelStack)
    pickle.dump(dictionary_0, open('dictionary_' + str(rank), 'wb'))
    return 0
    totalCount += 1
    gImg = numpy.reshape(x, (row, col))
    gImgNorm = imageProcess.normalize(gImg)
    gImg = imageProcess.invert(gImgNorm)

    # THRESHOLD METHOD 1 (OTSU)
    bImg = gImg >= imageProcess.otsuThreshold(gImg)

    # THRESHOLD METHOD 2 (KAPUR)
    # bImg = gImg >= imageProcess.threshold_kapur(gImg)

    # THRESHOLD METHOD 2 (MEAN)
    # bImg = gImg >= numpy.mean(gImg)

    bImg = imageProcess.binary_opening(bImg, iterations=4)
    labelImg, numLabel, dictionary = imageProcess.regionProps(bImg)

    distanceFromCentre = 1e10
    for i in range(numLabel):
        rCenter, cCenter = dictionary['centroid'][i]
        distance = numpy.sqrt((rCenter - row / 2.0)**2 +
                              (cCenter - col / 2.0)**2)
        if (distance < distanceFromCentre):
            distanceFromCentre = distance
            centerLabel = i + 1
    nearestNeighborDistance = 1e10
    for i in range(numLabel):
        if (i != centerLabel - 1):
            if (dictionary['minDist'][centerLabel - 1][i] <
                    nearestNeighborDistance):
                nearestNeighborDistance = dictionary['minDist'][centerLabel -