Beispiel #1
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
Beispiel #2
0
                cRadius = (rad1 + rad2)
            elif (theta == numpy.pi / 2):
                rRadius = (rad1 + rad2)
                cRadius = (rad1 + rad2) / 2
            else:
                rRadius = numpy.abs((r1 - r2) / numpy.cos(theta))
                cRadius = numpy.abs((c1 - c2) / numpy.cos(theta))

            gImgCrop = imageProcess.normalize(
                gImgProc[int(rCenter) - cropSize:int(rCenter) + cropSize + 1,
                         int(cCenter) - cropSize:int(cCenter) + cropSize + 1])
            bImgCrop, flag = fitFunc.fitting(gImgCrop, theta)
            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)
    gImgBlur = ndimage.gaussian_filter(gImgInv, sigma=sigma)
    bImgAdaptive = cv2.adaptiveThreshold(gImgBlur, 255,
                                         cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                         cv2.THRESH_BINARY, 15,
                                         0).astype('bool')

    bImg = numpy.logical_and(bImgKapur, bImgAdaptive)
    bImg = imageProcess.fillHoles(bImg)
    bImg = myCythonFunc.removeBoundaryParticles(bImg.astype('uint8'))
    bImg = myCythonFunc.areaThreshold(bImg.astype('uint8'),
                                      areaRange=areaRange)
    bImg = myCythonFunc.circularThreshold(bImg.astype('uint8'),
                                          circularityRange=circularityRange)
    bImg = imageProcess.convexHull(bImg)

    bImgBdry = imageProcess.normalize(imageProcess.boundary(bImg))
    finalImage = numpy.column_stack((numpy.maximum(gImgNorm,
                                                   bImgBdry), gImgNorm))
    cv2.imwrite(
        outputDir + '/segmentation/result/' + str(frame).zfill(zfillVal) +
        '.png', finalImage)
fp.flush(), fp.close()
comm.Barrier()
#######################################################################

#######################################################################
# CREATE BINARY IMAGES INTO HDF5 FILE
#######################################################################
if (rank == 0):
    print "Creating binary images and writing into h5 file"
import imageProcess
import myCythonFunc
import dataViewer
import misc
import tracking

outputFile = r'Z:\Geeta-Share\cubes assembly\20160614-001-output\20160614-001.h5'
fp = h5py.File(outputFile, 'r')
labelImg = fp['/segmentation/labelStack/'+str(1).zfill(6)].value

fig = plt.figure(figsize=(3,3))
ax = fig.add_axes([0,0,1,1])

for label in [2]:
    bImg = labelImg==label
    bImgBdry = imageProcess.boundary(bImg)
    
    h, theta, d = hough_line(bImgBdry)
    
    ax.imshow(bImgBdry, cmap=plt.cm.gray)
    rows, cols = bImgBdry.shape
    for _, angle, dist in zip(*hough_line_peaks(h, theta, d, num_peaks=4)):
        print numpy.rad2deg(angle)
        y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)
        y1 = (dist - cols * np.cos(angle)) / np.sin(angle)
        ax.plot((0, cols), (y0, y1), '-r')
    ax.axis((0, cols, rows, 0))
    #ax.set_title('Detected lines')
    ax.set_axis_off()
    
plt.show()
    def calculateOP(self, distanceRangePixel, stepSize):
        print('Calculate ordered paramter')
        opImgDir = self.outputImgDir + '/orderedParamerter-' + str(
            distanceRangePixel[0]) + '_' + str(
                distanceRangePixel[1]) + '_' + str(stepSize)
        opImgSeqDir = self.outputImgDir + '/orderedParamerter-' + str(
            distanceRangePixel[0]) + '_' + str(
                distanceRangePixel[1]) + '_' + str(stepSize) + '_seq'
        fileIO.mkdir(opImgDir)
        fileIO.mkdir(opImgSeqDir)
        counter = 0

        distanceArr, qArr = [], []
        for distance in range(distanceRangePixel[0], distanceRangePixel[1] + 1,
                              stepSize):
            meanDistance = (distance + distance + stepSize) / 2.0
            qDistance = 10 / (meanDistance * self.pixelSize)
            distanceArr.append(meanDistance)
            qArr.append(qDistance)
        self.distanceArr = numpy.asarray(distanceArr)
        self.qArr = numpy.asarray(qArr)

        minCount = 1e10
        for frame in tqdm(range(self.firstFrame, self.lastFrame + 1)):
            imgNPY = numpy.load(self.npyDir + '/' + str(frame).zfill(6) +
                                '.npy')
            count = imgNPY[self.mask == True]
            minCount = min(minCount, count.min())

        for frame, centreR, centreC in tqdm(
                zip(range(self.firstFrame, self.lastFrame + 1),
                    self.driftCorrectionParams[:, 0],
                    self.driftCorrectionParams[:, 1])):
            distanceMesh = numpy.sqrt((self.RR - centreR)**2 +
                                      (self.CC - centreC)**2)
            meanArr,medianArr,stdArr,ordParamArr_mean,ordParamArr_median = [],[],[],[],[]
            imgNPY = numpy.load(self.npyDir + '/' + str(frame).zfill(6) +
                                '.npy') - minCount
            imgPNG = cv2.imread(
                self.imgDir + '/' + str(frame).zfill(6) + '.png', 0)
            shellBorderImg = numpy.zeros(imgPNG.shape, dtype='bool')

            for distance in range(distanceRangePixel[0],
                                  distanceRangePixel[1] + 1, stepSize):
                distanceMask = numpy.logical_and(
                    numpy.logical_and(distanceMesh >= distance,
                                      distanceMesh < distance + stepSize),
                    self.mask)
                count = imgNPY[distanceMask == True]
                avgCount = numpy.mean(count)
                medianCount = numpy.median(count)
                stdCount = numpy.std(count)
                meanArr.append(avgCount)
                medianArr.append(medianCount)
                stdArr.append(stdCount)
                ordParamArr_mean.append(stdCount / avgCount)
                ordParamArr_median.append(stdCount / medianCount)

                if (frame == self.firstFrame):
                    gImg = cv2.imread(self.imgDir + '/000001.png', 0)
                    finalImg = numpy.maximum(gImg, distanceMask * 200)
                    counter += 1
                    cv2.imwrite(
                        opImgDir + '/' + str(counter).zfill(3) + '.png',
                        finalImg)

                distanceMaskBdry = imageProcess.boundary(distanceMask)
                distanceMaskBdry = imageProcess.binary_dilation(
                    distanceMaskBdry, iterations=1)
                imgPNG = numpy.maximum(imgPNG, distanceMaskBdry * 255)

            meanArr = numpy.asarray(meanArr)
            medianArr = numpy.asarray(medianArr)
            stdArr = numpy.asarray(stdArr)
            ordParamArr_mean = numpy.asarray(ordParamArr_mean)
            ordParamArr_median = numpy.asarray(ordParamArr_median)

            if (frame == self.firstFrame):
                self.meanArr = meanArr.copy()
                self.medianArr = medianArr.copy()
                self.stdArr = stdArr.copy()
                self.ordParamArr_mean = ordParamArr_mean.copy()
                self.ordParamArr_median = ordParamArr_median.copy()
            else:
                self.meanArr = numpy.row_stack((self.meanArr, meanArr))
                self.medianArr = numpy.row_stack((self.medianArr, medianArr))
                self.stdArr = numpy.row_stack((self.stdArr, stdArr))
                self.ordParamArr_mean = numpy.row_stack(
                    (self.ordParamArr_mean, ordParamArr_mean))
                self.ordParamArr_median = numpy.row_stack(
                    (self.ordParamArr_median, ordParamArr_median))

            cv2.imwrite(opImgSeqDir + '/' + str(frame).zfill(6) + '.png',
                        imgPNG)

        numpy.save(
            self.outputDataDir + '/distanceArr-' + str(distanceRangePixel[0]) +
            '_' + str(distanceRangePixel[1]) + '_' + str(stepSize) + '.npy',
            self.distanceArr)
        numpy.save(
            self.outputDataDir + '/qArr-' + str(distanceRangePixel[0]) + '_' +
            str(distanceRangePixel[1]) + '_' + str(stepSize) + '.npy',
            self.qArr)
        numpy.save(
            self.outputDataDir + '/meanArr-' + str(distanceRangePixel[0]) +
            '_' + str(distanceRangePixel[1]) + '_' + str(stepSize) + '.npy',
            self.meanArr)
        numpy.save(
            self.outputDataDir + '/medianArr-' + str(distanceRangePixel[0]) +
            '_' + str(distanceRangePixel[1]) + '_' + str(stepSize) + '.npy',
            self.medianArr)
        numpy.save(
            self.outputDataDir + '/stdArr-' + str(distanceRangePixel[0]) +
            '_' + str(distanceRangePixel[1]) + '_' + str(stepSize) + '.npy',
            self.stdArr)
        numpy.save(
            self.outputDataDir + '/ordParamArr_mean-' +
            str(distanceRangePixel[0]) + '_' + str(distanceRangePixel[1]) +
            '_' + str(stepSize) + '.npy', self.ordParamArr_mean)
        numpy.save(
            self.outputDataDir + '/ordParamArr_median-' +
            str(distanceRangePixel[0]) + '_' + str(distanceRangePixel[1]) +
            '_' + str(stepSize) + '.npy', self.ordParamArr_median)