Exemplo n.º 1
0
    def __init__(self,
                 stop_words_file=None,
                 allow_speech_tags=util.allow_speech_tags,
                 delimiters=util.sentence_delimiters):
        """
        Keyword arguments:
        stop_words_file  --  str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件
        delimiters       --  默认值是`?!;?!。;…\n`,用来将文本拆分为句子。
        
        Object Var:
        self.words_no_filter      --  对sentences中每个句子分词而得到的两级列表。
        self.words_no_stop_words  --  去掉words_no_filter中的停止词而得到的两级列表。
        self.words_all_filters    --  保留words_no_stop_words中指定词性的单词而得到的两级列表。
        """
        self.text = ''
        self.keywords = None

        self.seg = Segmentation.Segmentation(
            stop_words_file=stop_words_file,
            allow_speech_tags=allow_speech_tags,
            delimiters=delimiters)

        self.sentences = None
        self.words_no_filter = None  # 2维列表
        self.words_no_stop_words = None
        self.words_all_filters = None
Exemplo n.º 2
0
def construction():
    try:
        s = seg.Segmentation()
        s.segmentation()

        b = by.NBayes()
        b.initForTest()
    except Exception, e:
        raise
Exemplo n.º 3
0
def getDSubstance(data, elem):
    if data in dataS.keys():
        if elem in dataS[data].keys():
            path = DicomPath + "/" + dataS[data][elem]["dicomdir"]
            subs = Segmentation.Segmentation(
                dataS[data][elem]["structure"], data, path,
                DataManagement.DataManagement(path),
                dataS[data][elem]["threshold"], dataS[data][elem]["color"],
                dataS[data][elem]["texture"])
            subsDico = dataS[data][elem]
    return subs, subsDico
Exemplo n.º 4
0
def Segment(NumberOfData):
    ImgCount = 0

    AllLength = 0
    AllCorrect = 0
    count = 0
    WrongImgs = 0

    for scanned in os.listdir('dataset/scannedTest'):

        Path = 'dataset/scannedTest/' + scanned
        # Path2 = 'dataset/scanned2/'+scanned
        print(Path)
        Img = cv2.imread(Path)
        # Img2 = cv2.imread(Path2)

        S = Segmentation(Img)
        # S2 = Segmentation(Img2)
        try:
            S.Start()
            # S2.Start()
        except:
            print("Error in reading image")
            continue

        Words = S.GetSegmentedWords()
        # Words2 = S2.GetSegmentedWords()

        for i in range(len(Words)):
            WL = len(Words[i])

            for j in range(WL):
                name = str(ImgCount) + ".png"
                cv2.imwrite("trainTest/" + name, Words[i][j])
                ImgCount += 1

        # AllLength += Length
        # AllCorrect += Correct

        count += 1
        if count == NumberOfData:
            break

    # File.close()
    # AllAccuracy = (AllCorrect / AllLength) * 100
    # print("Segmentation Finished")
    # print(str(WrongImgs) + " Failed Images")
    # print("Testing on " + str(AllLength) + " Words ")
    # print(str(AllCorrect) + " Are Correct")
    # print("Accuracy : " + str(AllAccuracy) + "%")
    return Words
Exemplo n.º 5
0
def Test(Img):
    S = Segmentation(Img)
    S.Start()
    Words = S.GetSegmentedWords()
    Length = len(Words)
    ImgCount = 0
    for i in range(Length):
        WL = len(Words[i])
        for j in range(WL):
            name = str(ImgCount) + ".png"
            cv2.imwrite("Test/" + name, Words[i][j])
            ImgCount += 1

    return ImgCount
Exemplo n.º 6
0
def get_dataset():
    #获取分句后的文本
    stop_words_file = get_default_stop_words_file()
    seg = Segmentation( stop_words_file=stop_words_file,
                        allow_speech_tags=util.allow_speech_tags,
                        delimiters=util.sentence_delimiters)
    text = []
    cnt = 0 
    for line in open(train_data_path,"r",encoding="utf-8"):
        a = json.loads(line)
        result = seg.segment(text=a['content'], lower=False)
        text = text + result.sentences
        cnt += 1
        if cnt % 1000 == 0:
            print(f'{cnt} content finished.')
    print(f'{len(text)} sentences')
    return text
Exemplo n.º 7
0
 def Recognize(self):
     multi = MLP()
     multi.read_xml("MLP.xml")
     original_image = cv2.imread(self.original_path)
     output_image = cv2.imread(self.original_path)
     getimages = Segmentation()
     Coordinates_images = getimages.Segment(self.segmented_path)
     for coordinate in Coordinates_images:
         crop_img = original_image[coordinate.y:coordinate.y + coordinate.h,
                                   coordinate.x:coordinate.x + coordinate.w]
         image = cv2.resize(crop_img, (50, 50))
         gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
         gray = np.reshape(gray, 2500)
         feautures = generante_features_sample(gray, pca_data.totalimages,
                                               pca_data.finalEigenVectors)
         type = multi.determine_class(np.asarray(feautures)) - 1
         output_image = add_rectangle(output_image, coordinate.x,
                                      coordinate.y,
                                      coordinate.x + coordinate.w,
                                      coordinate.y + coordinate.h, type)
     cv2.imshow('IMAGE', output_image)
     cv2.waitKey(400000)
Exemplo n.º 8
0
 def Recognize(self):
     original_image = cv2.imread(self.original_path)
     output_image = cv2.imread(self.original_path)
     getimages = Segmentation()
     Coordinates_images = getimages.Segment(self.segmented_path)
     r = read_rbf_data()
     for coordinate in Coordinates_images:
         crop_img = original_image[coordinate.y:coordinate.y + coordinate.h,
                                   coordinate.x:coordinate.x + coordinate.w]
         image = cv2.resize(crop_img, (50, 50))
         gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
         gray = np.reshape(gray, 2500)
         feautures = generante_features_sample(gray, pca_data.totalimages,
                                               pca_data.finalEigenVectors)
         type = classify_from_file(feautures, r.k, r.num_classes,
                                   r.avg_list, r.mx_list, r.mn_list,
                                   r.centers, r.weights)
         output_image = add_rectangle(output_image, coordinate.x,
                                      coordinate.y,
                                      coordinate.x + coordinate.w,
                                      coordinate.y + coordinate.h, type)
     cv2.imshow('IMAGE', output_image)
     cv2.waitKey(400000)
Exemplo n.º 9
0
    def calculateLabelHist(self, imgBinary):
        seg = Segmentation.Segmentation(imgBinary, io=self.__io)
        labeled, _ = seg.labelAll()
        x, y = np.shape(labeled)
        val = labeled.flatten()

        histo, _ = np.histogram(val, bins=np.max(labeled) + 1)
        '''
        TEST: background can have less pixels than foreground if no markers are in the image
        '''
        if len(np.unique(labeled)) == 2:
            nrOfwhitePx = len(np.where(imgBinary == 255)[1])
            comp1 = np.max(histo)
            if comp1 == nrOfwhitePx:
                comp1 = np.min(histo)
            idx1 = list(histo).index(comp1)
            histo[idx1] = 0
        else:
            comp1 = np.max(histo)
            idx1 = list(histo).index(comp1)
            histo[idx1] = 0

        for i in range(len(histo)):
            if histo[i] < 100:
                histo[i] = 0
        self.__labelHist = histo

        self.__compsX = [[] for i in range(len(self.__labelHist))]
        self.__compsY = [[] for i in range(len(self.__labelHist))]

        self.__h, self.__w = np.shape(labeled)
        for i in range(self.__w):
            for j in range(self.__h):
                self.__compsX[labeled[j][i]].append(i)
                self.__compsY[labeled[j][i]].append(j)
        return labeled
Exemplo n.º 10
0
def threadCrown(filepath):
    global io

    rtpSkel = -1
    crownT = OrderedDict()
    imgL = []
    stemCorrection = bool(int(options[8][1]))

    print io.getHomePath()
    oldHome = io.getHomePath()
    os.chdir(io.getHomePath())
    io.setHomePath('./Crown/')
    f = io.scanDir()
    for (counter, i) in enumerate(f):
        io.setFileName(os.path.basename(i))
        io.setidIdx(imgID)

        print 'processing Crown file: ' + i
        xScale = allPara[counter][7]
        yScale = allPara[counter][8]
        analysis = Analysis.Analysis(io, (xScale + yScale) / 2)
        rtp = RootTipPaths.RootTipPaths(io)

        try:
            img = scipy.misc.imread(i, flatten=True)
        except:
            print 'Image not readable'
            img = -1

        if len(img) > 0:
            seg = Segmentation.Segmentation(img, io)
            imgL = seg.label()
            print 'compute root profile'
            currT = time.time()
            if ifAnyKeyIsTrue([
                    'AVG_DENSITY', 'WIDTH_MED', 'WIDTH_MAX', 'DIA_STM_SIMPLE',
                    'D10', 'D20', 'D30', 'D40', 'D50', 'D60', 'D70', 'D80',
                    'D90', 'DS10', 'DS20', 'DS30', 'DS40', 'DS50', 'DS60',
                    'DS70', 'DS80', 'DS90', 'AREA', 'ANG_TOP', 'ANG_BTM'
            ]):
                crownT['AVG_DENSITY'], crownT['WIDTH_MED'], crownT[
                    'WIDTH_MAX'], crownT['D10'], crownT['D20'], crownT[
                        'D30'], crownT['D40'], crownT['D50'], crownT[
                            'D60'], crownT['D70'], crownT['D80'], crownT[
                                'D90'], crownT['DS10'], crownT['DS20'], crownT[
                                    'DS30'], crownT['DS40'], crownT[
                                        'DS50'], crownT['DS60'], crownT[
                                            'DS70'], crownT['DS80'], crownT[
                                                'DS90'], crownT['AREA'], crownT[
                                                    'DIA_STM_SIMPLE'], crownT[
                                                        'ANG_TOP'], crownT[
                                                            'ANG_BTM'] = analysis.getWidthOverHeight(
                                                                imgL, xScale,
                                                                yScale)
                print 'Mask traits computed ' + str(time.time() - currT) + 's'

            if ifAnyKeyIsTrue([
                    'DIA_STM', 'TD_MED', 'TD_AVG', 'STA_RANGE', 'STA_DOM_I',
                    'STA_DOM_II', 'STA_25_I', 'STA_25_II', 'STA_50_I',
                    'STA_50_II', 'STA_75_I', 'STA_75_II', 'STA_90_I',
                    'STA_90_II', 'RTA_DOM_I', 'RTA_DOM_II', 'STA_MIN',
                    'STA_MAX', 'STA_MED', 'RTA_RANGE', 'RTA_MIN', 'RTA_MAX',
                    'RTA_MED', 'NR_RTP_SEG_I', 'NR_RTP_SEG_II', 'ADVT_COUNT',
                    'BASAL_COUNT', 'ADVT_ANG', 'BASAL_ANG', 'HYP_DIA',
                    'TAP_DIA', 'MAX_DIA_90', 'DROP_50', 'CP_DIA25', 'CP_DIA50',
                    'CP_DIA75', 'CP_DIA90', 'SKL_DEPTH', 'SKL_WIDTH'
            ]):
                currT = time.time()
                skel = Skeleton.Skeleton(imgL)
                testSkel, testDia = skel.skel(imgL)
                scipy.misc.imsave(
                    io.getHomePath() + '/Skeleton/' + io.getFileName() +
                    '_skel.png', testSkel)
                print 'Medial axis computed ' + str(time.time() - currT) + 's'
                currT = time.time()
                path, skelGraph, crownT[
                    'DIA_STM'], skelSize = seg.findThickestPath(
                        testSkel, testDia, xScale, yScale)
                allPara[counter][10] = skelSize
                print 'Central path computed ' + str(time.time() - currT) + 's'

            if ifAnyKeyIsTrue([
                    'TD_MED', 'TD_AVG', 'STA_RANGE', 'STA_DOM_I', 'STA_DOM_II',
                    'STA_25_I', 'STA_25_II', 'STA_50_I', 'STA_50_II',
                    'STA_75_I', 'STA_75_II', 'STA_90_I', 'STA_90_II',
                    'RTA_DOM_I', 'RTA_DOM_II', 'STA_MIN', 'STA_MAX', 'STA_MED',
                    'RTA_RANGE', 'RTA_MIN', 'RTA_MAX', 'RTA_MED',
                    'NR_RTP_SEG_I', 'NR_RTP_SEG_II', 'ADVT_COUNT',
                    'BASAL_COUNT', 'ADVT_ANG', 'BASAL_ANG', 'HYP_DIA',
                    'TAP_DIA', 'MAX_DIA_90', 'DROP_50', 'CP_DIA25', 'CP_DIA50',
                    'CP_DIA75', 'CP_DIA90', 'SKL_DEPTH', 'SKL_WIDTH',
                    'RTP_COUNT'
            ]):
                print 'Compute RTP skeleton'
                currT = time.time()
                rtpSkel, crownT['RTP_COUNT'], crownT['TD_MED'], crownT[
                    'TD_AVG'], crownT['MAX_DIA_90'], rtps, tips, crownT[
                        'SKL_WIDTH'], crownT['SKL_DEPTH'] = rtp.getRTPSkeleton(
                            path, skelGraph, True)
                seg.setTips(tips)
                print 'RTP Skeleton computed ' + str(time.time() - currT) + 's'

            allPara[len(allPara) - 1][2] = seg.getFail()

            if ifAnyKeyIsTrue(['RDISTR_X', 'RDISTR_Y']):
                print 'Compute spatial root distribution'
                currT = time.time()
                crownT['RDISTR_X'], crownT['RDISTR_Y'] = analysis.getSymmetry(
                    rtps, rtpSkel)
                print 'Symmetry computed ' + str(time.time() - currT) + 's'

            if rtpSkel != -1:
                if ifAnyKeyIsTrue([
                        'NR_RTP_SEG_I', 'NR_RTP_SEG_II', 'ADVT_COUNT',
                        'BASAL_COUNT', 'ADVT_ANG', 'BASAL_ANG', 'HYP_DIA',
                        'TAP_DIA'
                ]):
                    print 'searching for hypocotyl'
                    currT = time.time()
                    branchRad, nrPaths = seg.findHypocotylCluster(
                        path, rtpSkel)
                    print 'hypocotyl computed ' + str(time.time() -
                                                      currT) + 's'
                    print 'starting kmeans'
                    try:
                        currT = time.time()
                        c1x, c1y, c2x, c2y = analysis.plotDiaRadius(
                            nrPaths, branchRad, path, 2)

                        print '2 clusters computed in ' + str(time.time() -
                                                              currT) + 's'

                        currT = time.time()
                        segImg = seg.makeSegmentationPicture(
                            path, rtpSkel, img, xScale, yScale, c1x, c1y, c2x,
                            c2y)
                        scipy.misc.imsave(
                            io.getHomePath() + '/Result/' + io.getFileName() +
                            'Seg2.png', segImg)
                        crownT['ADVT_COUNT'], crownT['BASAL_COUNT'], crownT[
                            'NR_RTP_SEG_I'], crownT['NR_RTP_SEG_II'], crownT[
                                'HYP_DIA'], crownT[
                                    'TAP_DIA'] = analysis.countRootsPerSegment(
                                        c1y, c2y, c1x, c2x)
                    except:
                        c1x = None
                        c1y = None
                        c2x = None
                        c2y = None
                        pass
                    crownT['DROP_50'] = analysis.RTPsOverDepth(path, rtpSkel)
                    print 'count roots per segment'
                    print 'Root classes computed in ' + str(time.time() -
                                                            currT) + 's'

                if ifAnyKeyIsTrue([
                        'ADVT_ANG', 'BASAL_ANG', 'STA_RANGE', 'STA_DOM_I',
                        'STA_DOM_II', 'STA_25_I', 'STA_25_II', 'STA_50_I',
                        'STA_50_II', 'STA_75_I', 'STA_75_II', 'STA_90_I',
                        'STA_90_II', 'RTA_DOM_I', 'RTA_DOM_II', 'STA_MIN',
                        'STA_MAX', 'STA_MED', 'RTA_RANGE', 'RTA_MIN',
                        'RTA_MAX', 'RTA_MED'
                ]):
                    currT = time.time()
                    lat, corrBranchpts = seg.findLaterals(
                        rtps, rtpSkel, (xScale + yScale) / 2, None)
                    print 'seg.findLaterals computed in ' + str(time.time() -
                                                                currT) + 's'
                    print 'Compute angles at 2cm'
                    currT = time.time()
                    if c1x != None and c1y != None and c2x != None and c2y != None:
                        crownT['ADVT_ANG'], crownT[
                            'BASAL_ANG'] = analysis.anglesPerClusterAtDist(
                                c1y,
                                c2y,
                                rtpSkel,
                                path,
                                lat,
                                corrBranchpts, (xScale + yScale) / 2,
                                dist=20)
                    else:
                        crownT['ADVT_ANG'] = 'nan'
                        crownT['BASAL_NG'] = 'nan'
                    print 'angles at 2cm computed in ' + str(time.time() -
                                                             currT) + 's'

                    if ifAnyKeyIsTrue([
                            'STA_25_I', 'STA_25_II', 'STA_50_I', 'STA_50_II',
                            'STA_75_I', 'STA_75_II', 'STA_90_I', 'STA_90_II'
                    ]):
                        try:
                            print 'compute quantile angles'
                            currT = time.time()
                            a25, a50, a75, a90 = analysis.calculateAngleQuantiles(
                                path, lat, corrBranchpts, rtpSkel)
                            print 'angles computed in ' + str(time.time() -
                                                              currT) + 's'
                        except:
                            a25 = ['nan']
                            a50 = ['nan']
                            a75 = ['nan']
                            a90 = ['nan']
                            print 'ERROR: No quantile angles calculated'

                    if ifAnyKeyIsTrue(
                        ['RTA_RANGE', 'RTA_MIN', 'RTA_MAX', 'RTA_MED']):
                        try:
                            print 'compute angles'
                            currT = time.time()
                            crownT['RTA_MED'], crownT['RTA_MIN'], crownT[
                                'RTA_MAX'], crownT[
                                    'RTA_RANGE'], anglesN = analysis.calculateAngles(
                                        path, lat, corrBranchpts, rtpSkel)
                            print 'RTA angle characteristics computed in ' + str(
                                time.time() - currT) + 's'
                        except:
                            print 'ERROR: No RTA angles calculated'

                    if ifAnyKeyIsTrue(
                        ['STA_RANGE', 'STA_MIN', 'STA_MAX', 'STA_MED']):
                        try:
                            print 'compute STA angles'
                            currT = time.time()
                            crownT['STA_RANGE'], crownT['STA_MED'], crownT[
                                'STA_MIN'], crownT[
                                    'STA_MAX'], angles = analysis.getLateralAngles(
                                        path, lat, corrBranchpts, rtpSkel)
                            print 'STA angles characteristics computed in ' + str(
                                time.time() - currT) + 's'
                        except:
                            print 'ERROR: No STA angles calculated'

                    if ifAnyKeyIsTrue(
                        ['CP_DIA25', 'CP_DIA50', 'CP_DIA75', 'CP_DIA90']):
                        try:
                            print 'compute diameter quantils'
                            currT = time.time()
                            crownT['CP_DIA25'], crownT['CP_DIA50'], crownT[
                                'CP_DIA75'], crownT[
                                    'CP_DIA90'] = analysis.getDiameterQuantilesAlongSinglePath(
                                        path, rtpSkel)
                            print 'Tap diameters computed in ' + str(
                                time.time() - currT) + 's'
                        except:
                            print 'ERROR: No quantile diameters calculated'

                    if ifAnyKeyIsTrue(['STA_DOM_I', 'STA_DOM_II']):
                        try:
                            print 'compute STA dominant angles'
                            currT = time.time()
                            crownT['STA_DOM_I'], crownT[
                                'STA_DOM_II'] = analysis.findHistoPeaks(angles)
                            print 'STA dominant angles computed in ' + str(
                                time.time() - currT) + 's'
                        except:
                            print 'ERROR: No dominant angles calculated (STA)'

                    if ifAnyKeyIsTrue(['STA_25_I', 'STA_25_II']):
                        try:
                            currT = time.time()
                            crownT['STA_25_I'], crownT[
                                'STA_25_II'] = analysis.findHistoPeaks(a25)
                            print 'STA 25 angles computed in ' + str(
                                time.time() - currT) + 's'
                        except:
                            print 'ERROR: No dominant angles25 calculated'

                    if ifAnyKeyIsTrue(['STA_50_I', 'STA_50_II']):
                        try:
                            currT = time.time()
                            crownT['STA_50_I'], crownT[
                                'STA_50_II'] = analysis.findHistoPeaks(a50)
                            print 'STA 50 angles computed in ' + str(
                                time.time() - currT) + 's'
                        except:
                            print 'ERROR: No dominant angles50 calculated'

                    if ifAnyKeyIsTrue(['STA_75_I', 'STA_75_II']):
                        try:
                            currT = time.time()
                            crownT['STA_75_I'], crownT[
                                'STA_75_II'] = analysis.findHistoPeaks(a75)
                            print 'STA 75 angles computed in ' + str(
                                time.time() - currT) + 's'
                        except:
                            print 'ERROR: No dominant angles75 calculated'

                    if ifAnyKeyIsTrue(['STA_90_I', 'STA_90_II']):
                        try:
                            currT = time.time()
                            crownT['STA_90_I'], crownT[
                                'STA_90_II'] = analysis.findHistoPeaks(a90)
                            print 'STA 90 angles computed in ' + str(
                                time.time() - currT) + 's'
                        except:
                            print 'ERROR: No dominant angles90 calculated'

                    if ifAnyKeyIsTrue(['RTA_DOM_I', 'RTA_DOM_II']):
                        try:
                            currT = time.time()
                            crownT['RTA_DOM_I'], crownT[
                                'RTA_DOM_II'] = analysis.findHistoPeaks(
                                    anglesN)
                            print 'angles computed in ' + str(time.time() -
                                                              currT) + 's'
                        except:
                            print 'ERROR: No dominant RTA angles calculated'
    io.setHomePath(oldHome)
    if maxExRoot >= 1:
        rtpSkel = -1
        os.chdir(io.getHomePath())
        io.setHomePath('./Lateral/')
        f = io.scanDir()
        for (counter, i) in enumerate(f):
            print 'processing lateral file: ' + i

            if maxExRoot > 0:
                xScale = allPara[counter / maxExRoot][7]
                yScale = allPara[counter / maxExRoot][8]
                io.setFileName(os.path.basename(i))
            else:
                xScale = allPara[counter][7]
                yScale = allPara[counter][8]
                io.setFileName(os.path.basename(i))
                io.setidIdx(counter)

            rtp = RootTipPaths.RootTipPaths(io)

            analysis = Analysis.Analysis(io, (xScale + yScale) / 2)

            try:
                img = scipy.misc.imread(i, flatten=True)
            except:
                print 'Image not readable'
                img = []
                pass
            if len(img) > 0:

                seg = Segmentation.Segmentation(img, io=io)
                imgL = seg.label()

                if imgL != None:
                    skel = Skeleton.Skeleton(imgL)
                    testSkel, testDia = skel.skel(imgL)
                    path, skelGraph = seg.findThickestPathLateral(
                        testSkel, testDia, xScale, yScale)
                    if ifAnyKeyIsTrue([
                            'LT_AVG_LEN', 'NODAL_LEN', 'LT_BRA_FRQ',
                            'NODAL_AVG_DIA', 'LT_AVG_ANG', 'LT_ANG_RANGE',
                            'LT_MIN_ANG', 'LT_MAX_ANG', 'LT_DIST_FIRST',
                            'LT_MED_DIA', 'LT_AVG_DIA'
                    ]):
                        rtpSkel, _, crownT['LT_MED_DIA'], crownT[
                            'LT_AVG_DIA'], _, rtps, _, _, _ = rtp.getRTPSkeleton(
                                path, skelGraph, True)

                    if rtpSkel != -1:
                        if ifAnyKeyIsTrue(['LT_BRA_FRQ']):
                            crownT[
                                'LT_BRA_FRQ'] = analysis.getBranchingfrequencyAlongSinglePath(
                                    rtps, path)
                            crownT[
                                'NODAL_AVG_DIA'], _ = analysis.getDiametersAlongSinglePath(
                                    path, rtpSkel, (xScale + yScale) / 2)
                            crownT['NODAL_LEN'] = analysis.getLengthOfPath(
                                path)
                        if ifAnyKeyIsTrue([
                                'LT_DIST_FIRST', 'LT_AVG_LEN', 'LT_BRA_FRQ',
                                'LT_ANG_RANGE', 'LT_AVG_ANG', 'LT_MIN_ANG',
                                'LT_MAX_ANG'
                        ]):
                            lat, corrBranchpts, crownT[
                                'LT_DIST_FIRST'] = seg.findLaterals(
                                    rtps, rtpSkel, (xScale + yScale) / 2, path)
                            if ifAnyKeyIsTrue(['LT_AVG_LEN']):
                                crownT[
                                    'LT_AVG_LEN'] = analysis.getLateralLength(
                                        lat, path, rtpSkel)
                            if ifAnyKeyIsTrue([
                                    'LT_ANG_RANGE', 'LT_AVG_ANG', 'LT_MIN_ANG',
                                    'LT_MAX_ANG'
                            ]):
                                crownT['LT_ANG_RANGE'], crownT[
                                    'LT_AVG_ANG'], crownT['LT_MIN_ANG'], crownT[
                                        'LT_MAX_ANG'], _ = analysis.getLateralAngles(
                                            path, lat, corrBranchpts, rtpSkel)
            allCrown.append(crownT.copy())
    else:
        allCrown.append(crownT.copy())

    io.setHomePath(oldHome)
Exemplo n.º 11
0
Arquivo: main.py Projeto: avrajit/DIRT
def threadLateral(filepath):
    tipdiameter = 0.
    os.chdir(io.getHomePath())
    io.setHomePath('./Lateral/')
    f = io.scanDir()
    for (counter, i) in enumerate(f):
        print 'processing lateral file: ' + i
        if maxExRoot > 0:
            xScale = allPara[counter / maxExRoot][7]
            yScale = allPara[counter / maxExRoot][8]
            io.setFileName(os.path.basename(i))
        else:
            xScale = allPara[counter][7]
            yScale = allPara[counter][8]
            io.setFileName(os.path.basename(i))
            io.setidIdx(counter)

        rtp = RootTipPaths.RootTipPaths(io, tipdiameter)
        rtp.setTipDiaFilter(tipdiameter)

        analysis = Analysis.Analysis(io, (xScale + yScale) / 2)

        lateralT = []

        try:
            img = scipy.misc.imread(i, flatten=True)
        except:
            print 'Image not readable'
            img = []
            pass
        if len(img) > 0:

            seg = Segmentation.Segmentation(img, io=io)
            imgL = seg.label()

            if imgL != None:
                skel = Skeleton.Skeleton(imgL)
                testSkel, testDia = skel.skel(imgL)
                path, skelGraph = seg.findThickestPathLateral(
                    testSkel, testDia, xScale, yScale)
                rtpSkel, _, medianD, meanD, _, _, rtps, _, _, _ = rtp.getRTPSkeleton(
                    path, skelGraph, True)

                if rtpSkel != -1:
                    lBranchFreq = analysis.getBranchingfrequencyAlongSinglePath(
                        rtps, path)
                    avgLatDiameter, slope = analysis.getDiametersAlongSinglePath(
                        path, rtpSkel, (xScale + yScale) / 2)
                    lengthNodalRoot = analysis.getLengthOfPath(path)
                    lat, corrBranchpts, distToFirst = seg.findLaterals(
                        rtps, rtpSkel, (xScale + yScale) / 2)
                    avgLLength = analysis.getLateralLength(lat, path, rtpSkel)
                    angRange, avgAngle, minangle, maxAngle, _ = analysis.getLateralAngles(
                        path, lat, corrBranchpts, rtpSkel)
                    lateralT = [
                        avgLLength * ((xScale + yScale) / 2),
                        float(lengthNodalRoot) * ((xScale + yScale) / 2),
                        lBranchFreq, avgLatDiameter, slope, avgAngle, angRange,
                        minangle, maxAngle,
                        float(distToFirst) * ((xScale + yScale) / 2), medianD,
                        meanD
                    ]
                else:
                    lateralT = [
                        'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                        'nan', 'nan', 'nan', 'nan'
                    ]
            else:
                lateralT = [
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan'
                ]
            allLat.append(lateralT)
            if options[5][1] == '0':
                crownT = [
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan'
                ]
                allCrown.append(crownT)

    io.setHomePath(os.getcwd())
Exemplo n.º 12
0
Arquivo: main.py Projeto: avrajit/DIRT
def threadCrown(filepath):
    imgL = []
    tipdiameter = float(options[8][1])
    print io.getHomePath()
    os.chdir(io.getHomePath())
    io.setHomePath('./Crown/')
    f = io.scanDir()
    for (counter, i) in enumerate(f):
        io.setFileName(os.path.basename(i))
        io.setidIdx(imgID)

        print 'processing Crown file: ' + i
        xScale = allPara[counter][7]
        yScale = allPara[counter][8]
        analysis = Analysis.Analysis(io, (xScale + yScale) / 2)
        rtp = RootTipPaths.RootTipPaths(io, tp=tipdiameter)
        rtp.setTipDiaFilter(tipdiameter * (xScale + yScale) / 2)
        crownT = []

        try:
            img = scipy.misc.imread(i, flatten=True)
        except:
            print 'Image not readable'
            img = -1
        if len(img) > 0:
            seg = Segmentation.Segmentation(img, io)
            imgL = seg.label()
            print 'compute root profile'
            currT = time.time()
            rootDensity, medianWidth, maxWidth, D, DS, _, _, _, _ = analysis.getWidthOverHeight(
                imgL, xScale, yScale)
            print 'Mask traits computed ' + str(time.time() - currT) + 's'
            currT = time.time()
            skel = Skeleton.Skeleton(imgL)
            testSkel, testDia = skel.skel(imgL)
            print 'Medial axis computed ' + str(time.time() - currT) + 's'
            currT = time.time()
            path, skelGraph, stemDia, skelSize = seg.findThickestPath(
                testSkel, testDia, xScale, yScale)
            allPara[counter][10] = skelSize
            print 'Central path computed ' + str(time.time() - currT) + 's'
            print 'compute rtp skeleton'
            currT = time.time()
            rtpSkel, nrOfRTP, medianTipDiameter, meanDiameter, dia90, _, rtps, tips, _, _ = rtp.getRTPSkeleton(
                path, skelGraph, True)
            allPara[len(allPara) - 1][2] = seg.getFail()
            seg.setTips(tips)
            print 'RTP Skeleton computed ' + str(time.time() - currT) + 's'
            print 'compute symmetry'
            currT = time.time()
            vecSym = analysis.getSymmetry(rtps, rtpSkel)
            print 'Symmetry computed ' + str(time.time() - currT) + 's'

            if rtpSkel != -1:

                lat, corrBranchpts, _ = seg.findLaterals(
                    rtps, rtpSkel, (xScale + yScale) / 2)

                try:
                    print 'compute quantile angles'
                    currT = time.time()
                    a25, a50, a75, a90 = analysis.calculateAngleQuantiles(
                        path, lat, corrBranchpts, rtpSkel)
                    print 'angles computed in ' + str(time.time() -
                                                      currT) + 's'
                except:
                    raise
                    a25 = ['nan']
                    a50 = ['nan']
                    a75 = ['nan']
                    a90 = ['nan']

                    print 'ERROR: No quantile angles calculated'

                try:
                    print 'compute angles'
                    currT = time.time()
                    angRangeN, avgAngleN, minangleN, maxAngleN, anglesN = analysis.calculateAngles(
                        path, lat, corrBranchpts, rtpSkel)
                    print 'angles computed in ' + str(time.time() -
                                                      currT) + 's'
                except:
                    avgAngleN = 'nan'
                    minangleN = 'nan'
                    maxAngleN = 'nan'
                    angRangeN = 'nan'
                    anglesN = 'nan'
                    print 'ERROR: No angles calculated'

                try:
                    print 'compute RTA angles'
                    currT = time.time()
                    angRange, avgAngle, minangle, maxAngle, angles = analysis.getLateralAngles(
                        path, lat, corrBranchpts, rtpSkel)
                    print 'angles computed in ' + str(time.time() -
                                                      currT) + 's'
                except:
                    raise
                    avgAngle = 'nan'
                    minangle = 'nan'
                    maxAngle = 'nan'
                    angRange = 'nan'
                    angles = 'nan'
                    print 'ERROR: No RTA angles calculated'
                try:

                    print 'compute diameter quantils'
                    currT = time.time()
                    d25, d50, d75, d90 = analysis.getDiameterQuantilesAlongSinglePath(
                        path, rtpSkel)
                    print 'diameters computed in ' + str(time.time() -
                                                         currT) + 's'
                except:
                    d25 = 'nan'
                    d50 = 'nan'
                    d75 = 'nan'
                    d90 = 'nan'
                    print 'ERROR: No quantile angles calculated'
                    raise

                try:
                    print 'compute dominant angles'
                    currT = time.time()
                    ang1, ang2 = analysis.findHistoPeaks(angles)
                    print 'angles computed in ' + str(time.time() -
                                                      currT) + 's'
                except:
                    ang1 = 'nan'
                    ang2 = 'nan'
                    print 'ERROR: No dominant angles calculated'
                try:
                    currT = time.time()
                    ang25_1, ang25_2 = analysis.findHistoPeaks(a25)
                    print 'angles computed in ' + str(time.time() -
                                                      currT) + 's'
                except:
                    ang25_1 = 'nan'
                    ang25_2 = 'nan'
                    print 'ERROR: No dominant angles25 calculated'
                try:
                    currT = time.time()
                    ang50_1, ang50_2 = analysis.findHistoPeaks(a50)
                    print 'angles computed in ' + str(time.time() -
                                                      currT) + 's'
                except:
                    ang50_1 = 'nan'
                    ang50_2 = 'nan'
                    print 'ERROR: No dominant angles50 calculated'
                try:
                    currT = time.time()
                    ang75_1, ang75_2 = analysis.findHistoPeaks(a75)
                    print 'angles computed in ' + str(time.time() -
                                                      currT) + 's'
                except:
                    ang75_1 = 'nan'
                    ang75_2 = 'nan'
                    print 'ERROR: No dominant angles75 calculated'
                try:
                    currT = time.time()
                    ang90_1, ang90_2 = analysis.findHistoPeaks(a90)
                    print 'angles computed in ' + str(time.time() -
                                                      currT) + 's'
                except:
                    ang90_1 = 'nan'
                    ang90_2 = 'nan'
                    print 'ERROR: No dominant angles90 calculated'

                try:
                    currT = time.time()
                    angN_1, angN_2 = analysis.findHistoPeaks(anglesN)
                    print 'angles computed in ' + str(time.time() -
                                                      currT) + 's'
                except:
                    angN_1 = 'nan'
                    angN_2 = 'nan'
                    print 'ERROR: No dominant angles90 calculated'

                crownT = [
                    stemDia, rootDensity, angRange, ang1, ang2, ang25_1,
                    ang25_2, ang50_1, ang50_2, ang75_1, ang75_2, ang90_1,
                    ang90_2, angN_1, angN_2, minangle, maxAngle, avgAngle,
                    angRangeN, avgAngleN, minangleN, maxAngleN, nrOfRTP,
                    medianTipDiameter, meanDiameter, dia90, medianWidth,
                    maxWidth, D[0], D[1], D[2], D[3], D[4], D[5], D[6], D[7],
                    D[8], DS[0], DS[1], DS[2], DS[3], DS[4], DS[5], DS[6],
                    DS[7], DS[8], vecSym[0], vecSym[1], d25, d50, d75, d90
                ]

            else:
                crownT = [
                    stemDia, rootDensity, 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', medianWidth, maxWidth, D[0], D[1],
                    D[2], D[3], D[4], D[5], D[6], D[7], D[8], DS[0], DS[1],
                    DS[2], DS[3], DS[4], DS[5], DS[6], DS[7], DS[8], vecSym[0],
                    vecSym[1], d25, d50, d75, d90
                ]

            if maxExRoot > 1:
                for i in range(maxExRoot):
                    allCrown.append(crownT)
            else:
                allCrown.append(crownT)
            if options[4][1] == '0':
                lateralT = [
                    'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan',
                    'nan', 'nan', 'nan', 'nan'
                ]
                allLat.append(lateralT)
    io.setHomePath(os.getcwd())
Exemplo n.º 13
0
        print "assign_color done in ", time2 - time1, " s"
        self.set_canvascolor()
        im = Image.new("RGB", (400, 400), (255, 255, 255))
        for obj in self.layers.segs:
            for subseg in obj.subsegment:
                slayer = Seg_layer(subseg.edge, subseg.pix, self.canvas.canvas,
                                   im)
                slayer.render()
        '''
        for n in range(self.canvas.canvas.shape[0]):
            for p in range(self.canvas.canvas.shape[1]):
		if(self.canvas.canvas[n][p][3]<1.0):
                	print self.canvas.canvas[n][p][3]
	'''
        plt.imshow(self.canvas.canvas)
        plt.show()


if __name__ == '__main__':
    sg = Segmentation()
    sg.imread('ball.jpg')
    sg.set_no(1)

    sg.set_ns(1)
    sg.segment()
    canvas = Canvas()
    canvas.set_canvas(250, 250)
    canvas.set_paper('paper.jpg')
    pt = Painter(sg, canvas)
    pt.paint()
Exemplo n.º 14
0
def Train(NumberOfData):

    ImgCount = 0

    AllLength = 0
    AllCorrect = 0
    count = 0
    WrongImgs = 0

    try:
        shutil.rmtree("train")
    except:
        print("No train folder")

    os.mkdir("train")

    File = open("associtations.txt", "w")
    # exit(0)
    for scanned in os.listdir('dataset/scanned'):

        Path = 'dataset/scanned/' + scanned
        # Path2 = 'dataset/scanned2/'+scanned
        print(Path)
        Img = cv2.imread(Path)
        S = Segmentation(Img)
        try:
            S.Start()
        except:
            print("Error in reading image")
            continue

        FileName = 'dataset/text/' + scanned[:-4] + '.txt'
        print(FileName)

        File = open(FileName, "r")
        Lines = File.readlines()
        RealWords = Lines[0].split(" ")
        Words = S.GetSegmentedWords()

        Length = len(RealWords)
        print("================================")
        print(Length)
        print(len(Words))
        # print(len(Words2))

        if Length != len(Words):
            print("Error in Words")
            print("Number Of True Words: " + str(Length))
            print("Number of Words: " + str(len(Words)))
            WrongImgs += 1
            continue

        File = open("associtations.txt", "a")
        Correct = 0
        for i in range(Length):
            WL = len(Words[i])
            if WordLength(RealWords[i]) == WL:
                Correct += 1
                for j in range(WL):
                    name = str(ImgCount) + ".png"
                    Char = RealWords[i][j]
                    cv2.imwrite("train/" + name, Words[i][j])
                    if j < WL - 1:
                        if (RealWords[i][j] + RealWords[i][j + 1]) == "لا":
                            Char += 'ا'
                    File.write(str(Dict[Char]) + " " + name + "\n")
                    ImgCount += 1

        print(str((Correct / Length) * 100) + "%")

        print("================================")
        AllLength += Length
        AllCorrect += Correct

        count += 1
        if count == NumberOfData:
            break

    File.close()
    AllAccuracy = (AllCorrect / AllLength) * 100
    print("Segmentation Finished")
    print(str(WrongImgs) + " Failed Images")
    print("Testing on " + str(AllLength) + " Words ")
    print(str(AllCorrect) + " Are Correct")
    print("Accuracy : " + str(AllAccuracy) + "%")
Exemplo n.º 15
0
try:
    np.load = lambda *a,**k: np_load_old1(*a, allow_pickle=True, **k)
except:
    pass


#  To Train First Uncomment The Following Line
# Train()

# InputFolder = "PublicTestCases/Input"
# OutputFolder = "PublicTestCases/Output1"
InputFolder = args.inputfolder
OutputFolder = args.outputfolder



for filename in sorted(glob.glob(InputFolder+"/*")):
    try:
        outfilename = OutputFolder+filename.rsplit('.', 1)[0].replace(InputFolder,"")+".txt"

        image = io.imread(filename)

        x = PreProcessings(image)

        SegmentedNotes,NotesPerOctave,locations,Staffs,StaffThickness,StaffHeight = Segmentation(x)

        Classifier(SegmentedNotes,NotesPerOctave,locations,Staffs,StaffThickness,StaffHeight,out = outfilename,k=5)
    except:
        f = open(outfilename, "w")
        f.write("[]")
        f.close()