Exemplo n.º 1
0
	def run(self, ips, imgs, para = None):
		k = para['diag']/np.sqrt((np.array(ips.img.shape)**2).sum())
		size = tuple((np.array(ips.img.shape)*k).astype(np.int16))
		IPy.set_info('down sample...')
		news = []
		for img in imgs:
			if k!=0: img = tf.resize(img, size)
			if para['sigma']!=0:
				img = ndimg.gaussian_filter(img, para['sigma'])
			news.append(img)

		IPy.set_info('register...')
		sr = StackReg(eval('StackReg.%s'%para['trans']))
		sr.register_stack(np.array(news), reference=para['ref'])

		mats = sr._tmats.reshape((sr._tmats.shape[0],-1))
		if k!=0: mats[:,[0,1,3,4,6,7]] *= k
		if k!=0: mats[:,[0,1,2,3,4,5]] /= k

		if para['tab']: IPy.show_table(pd.DataFrame(
			mats, columns=['A%d'%(i+1) for i in range(mats.shape[1])]), title='%s-Tmats'%ips.title)

		if para['new'] == 'None': return
		IPy.set_info('transform...')
		for i in range(sr._tmats.shape[0]):
			tform = tf.ProjectiveTransform(matrix=sr._tmats[i])
			img =  tf.warp(imgs[i], tform)
			img -= imgs[i].min(); img *= imgs[i].max() - imgs[i].min()
			if para['new'] == 'Inplace': imgs[i][:] = img
			if para['new'] == 'New': news[i] = img.astype(ips.img.dtype)
			self.progress(i, len(imgs))
		if para['new'] == 'New': IPy.show_img(news, '%s-reg'%ips.title)
Exemplo n.º 2
0
 def run(self, para=None):
     path = "/Volumes/Macintosh/curioData/screening/20181022_wt_mad1/FLUO_80_1_FluoAnalysis/mad1/croppedImgs"
     # TODO this getDir and wx.DirDialog will both crash
     # tmp_dir = IPy.getdir("Choose a directory", "", "")
     list_file = os.listdir(path)
     data = generate_empty_annotation(len(list_file), 70)
     IPy.show_table(data, 'Annotations[%s,%s]' % data.shape)
Exemplo n.º 3
0
    def run(self, ips, imgs, para=None):
        edges, nodes = [], []
        ntitles = ['PartID', 'NodeID', 'Degree', 'X', 'Y', 'Z']
        etitles = ['PartID', 'StartID', 'EndID', 'Length', 'Distance']
        k, unit = ips.unit
        comid = 0
        for g in nx.connected_component_subgraphs(ips.data, False):
            for idx in g.nodes():
                o = g.node[idx]['o']
                nodes.append([
                    comid, idx,
                    g.degree(idx),
                    round(o[1] * k, 2),
                    round(o[0] * k, 2),
                    round(o[2])
                ])
            for (s, e) in g.edges():
                eds = g[s][e]
                for i in eds:
                    l = round(eds[i]['weight'] * k, 2)
                    dis = round(
                        np.linalg.norm(g.node[s]['o'] - g.node[e]['o']) * k, 2)
                    edges.append([comid, s, e, l, dis])
            comid += 1

        IPy.show_table(pd.DataFrame(nodes, columns=ntitles),
                       ips.title + '-nodes')
        IPy.show_table(pd.DataFrame(edges, columns=etitles),
                       ips.title + '-edges')
Exemplo n.º 4
0
 def run(self, ips, imgs, para = None):
     titles = ['Max','Min','Mean','Variance','Standard']
     key = {'Max':'max','Min':'min','Mean':'mean','Variance':'var','Standard':'std'}
     titles = [i for i in titles if para[key[i]]]
     if para['nozero']: imgs = imgs[imgs!=0]
     data = self.count(imgs, para)
     IPy.show_table(pd.DataFrame(data, columns=titles), ips.title+'-statistic')
Exemplo n.º 5
0
    def run(self, ips, imgs, para=None):
        sc, sr = ips.get_rect()
        print(sc, sr)
        c, r, w, h = sr.start, sc.start, sr.stop - sr.start, sc.stop - sc.start
        roi = imgs[0][r:r + h, c:c + w].copy()
        track_window = (c, r, w, h)
        hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),
                           np.array((180., 255., 255.)))
        roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
        cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
        # Setup the termination criteria, either 10 iteration or move by atleast 1 pt
        term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
        n = len(imgs)
        locs, mark = [], {'type': 'layers', 'body': {}}
        for i in range(n):
            prgs = (i, n)
            frame = imgs[i].copy()
            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)
            ret, track_window = cv2.meanShift(dst, track_window, term_crit)
            x, y, w, h = track_window
            img2 = cv2.rectangle(frame, (x, y), (x + w, y + h), 255, 2)
            locs.append([x, y, w, h])

            layer = {'type': 'layer', 'body': []}
            layer['body'].append({
                'type': 'rectangle',
                'body': (x + w / 2, y + h / 2, w, h)
            })
            mark['body'][i] = layer

        ips.mark = GeometryMark(mark)
        IPy.show_table(pd.DataFrame(locs, columns=['X', 'Y', 'W', 'H']),
                       ips.title + '-region')
Exemplo n.º 6
0
    def run(self, ips, imgs, para=None):
        titles = ['P1', 'P2', 'P3', 'angle']
        k, unit = ips.unit
        graph = ips.data
        datas = []
        for s in graph.nodes():
            o = graph.node[s]['o']
            x = graph[s]
            if len(x) <= 1: continue
            rst = []
            for e in x:
                eds = x[e]
                for ed in eds:
                    l = eds[ed]['pts']
                    if len(l) < 10: continue
                    if norm(l[0] - o) > norm(l[-1] - o): l = l[::-1]
                    p1, p2 = l[0], l[5]
                    rst.append((s, e, p2 - p1))
            if len(rst) < 2: continue
            com = combinations(range(len(rst)), 2)
            for i1, i2 in com:
                v1, v2 = rst[i1][2], rst[i2][2]
                a = np.arccos(np.dot(v1, v2) / norm(v1) / norm(v2))
                datas.append([rst[i1][1], rst[i1][0], rst[i2][1], round(a, 4)])

        print(titles, datas)
        IPy.show_table(pd.DataFrame(datas, columns=titles),
                       ips.title + '-graph')
Exemplo n.º 7
0
 def run(self, ips, imgs, para=None):
     self.modedict = {
         'SQDIFF': cv2.TM_SQDIFF,
         'SQDIFF_NORMED': cv2.TM_SQDIFF_NORMED,
         'CCORR': cv2.TM_CCORR,
         'CCORR_NORMED': cv2.TM_CCORR_NORMED,
         'CCOEFF': cv2.TM_CCOEFF
     }
     data = []
     sly, slx = ips.get_rect()
     #将矩形中的线进行等分,x是固定的
     print(sly, slx)
     img_moudle = imgs[0][sly, slx.start + 60:slx.stop - 60]
     n = len(imgs)
     locs = []
     for i in range(n):
         prgs = (i, n)
         self.progress(i, len(imgs))
         x, y = self.mathc_img(imgs[i][sly, slx.start:slx.stop], img_moudle,
                               self.modedict[self.para['mode']])
         temp = imgs[i][self.para['amp_x'] +
                        (x - self.para['amp_x']):-self.para['amp_x'] +
                        (x - self.para['amp_x']), self.para['amp_y'] +
                        (y - self.para['amp_y']):-self.para['amp_y'] +
                        (y - self.para['amp_y'])]
         imgs[i][self.para['amp_x']:-self.para['amp_x'],
                 self.para['amp_y']:-self.para['amp_y']] = temp
         locs.append((x, y))
     # print(locs)
     # IPy.show_table(pd.DataFrame(locs, ['X','Y']),'locations')
     IPy.show_table(pd.DataFrame(locs, columns=['X', 'Y']), 'locations')
Exemplo n.º 8
0
    def run(self, ips, imgs, para=None):
        titles = [
            'PartID', 'Noeds', 'Edges', 'TotalLength', 'Density', 'AveConnect'
        ]
        k, unit = ips.unit

        gs = nx.connected_component_subgraphs(
            ips.data, False) if para['parts'] else [ips.data]
        comid, datas = 0, []
        for g in gs:
            sl = 0
            for (s, e) in g.edges():
                sl += sum([i['weight'] for i in g[s][e].values()])
            datas.append([
                comid,
                g.number_of_nodes(),
                g.number_of_edges(),
                round(sl * k, 2),
                round(nx.density(g), 2),
                round(nx.average_node_connectivity(g), 2)
            ][1 - para['parts']:])
            comid += 1
        print(titles, datas)
        IPy.show_table(pd.DataFrame(datas, columns=titles[1 - para['parts']:]),
                       ips.title + '-graph')
Exemplo n.º 9
0
    def run(self, ips, imgs, para = None):
        inten = ImageManager.get(para['inten'])
        if not para['slice']:
            imgs = [inten.img]
            msks = [ips.img]
        else: 
            msks = ips.imgs
            imgs = inten.imgs
            if len(msks)==1:
                msks *= len(imgs)
        buf = imgs[0].astype(np.uint16)
        strc = ndimage.generate_binary_structure(2, 1 if para['con']=='4-connect' else 2)
        idct = ['Max','Min','Mean','Variance','Standard','Sum']
        key = {'Max':'max','Min':'min','Mean':'mean',
               'Variance':'var','Standard':'std','Sum':'sum'}
        idct = [i for i in idct if para[key[i]]]
        titles = ['Slice', 'ID'][0 if para['slice'] else 1:] 
        if para['center']: titles.extend(['Center-X','Center-Y'])
        if para['extent']: titles.extend(['Min-Y','Min-X','Max-Y','Max-X'])
        titles.extend(idct)
        k = ips.unit[0]
        data, mark = [],{'type':'layers', 'body':{}}
        # data,mark=[],[]
        for i in range(len(imgs)):
            n = ndimage.label(msks[i], strc, output=buf)
            index = range(1, n+1)
            dt = []
            if para['slice']:dt.append([i]*n)
            dt.append(range(n))
            
            xy = ndimage.center_of_mass(imgs[i], buf, index)
            xy = np.array(xy).round(2).T
            if para['center']:dt.extend([xy[1]*k, xy[0]*k])

            boxs = [None] * n
            if para['extent']:
                boxs = ndimage.find_objects(buf)
                boxs = [( i[1].start+(i[1].stop-i[1].start)/2, i[0].start+(i[0].stop-i[0].start)/2, i[1].stop-i[1].start,i[0].stop-i[0].start) for i in boxs]
                for j in (0,1,2,3):
                    dt.append([i[j]*k for i in boxs])
            if para['max']:dt.append(ndimage.maximum(imgs[i], buf, index).round(2))
            if para['min']:dt.append(ndimage.minimum(imgs[i], buf, index).round(2))        
            if para['mean']:dt.append(ndimage.mean(imgs[i], buf, index).round(2))
            if para['var']:dt.append(ndimage.variance(imgs[i], buf, index).round(2)) 
            if para['std']:dt.append(ndimage.standard_deviation(imgs[i], buf, index).round(2))
            if para['sum']:dt.append(ndimage.sum(imgs[i], buf, index).round(2))      
 
            layer = {'type':'layer', 'body':[]}
            xy=np.int0(xy).T

            texts = [(i[1],i[0])+('id=%d'%n,) for i,n in zip(xy,range(len(xy)))]
            layer['body'].append({'type':'texts', 'body':texts})
            if para['extent']: layer['body'].append({'type':'rectangles', 'body':boxs})
            mark['body'][i] = layer

            data.extend(list(zip(*dt)))
        IPy.show_table(pd.DataFrame(data, columns=titles), inten.title+'-region statistic')
        inten.mark = GeometryMark(mark)
        inten.update = True
Exemplo n.º 10
0
    def run(self, ips, imgs, para = None):
        if not para['slice']:imgs = [ips.img]
        k = ips.unit[0]

        titles = ['Slice', 'ID'][0 if para['slice'] else 1:]
        if para['center']:titles.extend(['Center-X','Center-Y'])
        if para['area']:titles.append('Area')
        if para['l']:titles.append('Perimeter')
        if para['extent']:titles.extend(['Min-Y','Min-X','Max-Y','Max-X'])
        if para['ed']:titles.extend(['Diameter'])
        if para['ca']:titles.extend(['ConvexArea'])
        if para['holes']:titles.extend(['Holes'])
        if para['fa']:titles.extend(['FilledArea'])
        if para['solid']:titles.extend(['Solidity'])
        if para['cov']:titles.extend(['Major','Minor','Ori'])
        buf = imgs[0].astype(np.uint16)
        data, mark = [], []
        strc = generate_binary_structure(2, 1 if para['con']=='4-connect' else 2)
        for i in range(len(imgs)):
            label(imgs[i], strc, output=buf)
            ls = regionprops(buf)

            dt = [[i]*len(ls), list(range(len(ls)))]
            if not para['slice']:dt = dt[1:]

            if not para['cov']: cvs = [None] * len(ls)
            else: cvs = [(i.major_axis_length, i.minor_axis_length, i.orientation) for i in ls]
            centroids = [i.centroid for i in ls]
            mark.append([(center, cov) for center,cov in zip(centroids, cvs)])
            if para['center']:
                dt.append([round(i.centroid[1]*k,1) for i in ls])
                dt.append([round(i.centroid[0]*k,1) for i in ls])
            if para['area']:
                dt.append([i.area*k**2 for i in ls])
            if para['l']:
                dt.append([round(i.perimeter*k,1) for i in ls])
            if para['extent']:
                for j in (0,1,2,3):
                    dt.append([i.bbox[j]*k for i in ls])
            if para['ed']:
                dt.append([round(i.equivalent_diameter*k, 1) for i in ls])
            if para['ca']:
                dt.append([i.convex_area*k**2 for i in ls])
            if para['holes']:
                dt.append([1-i.euler_number for i in ls])
            if para['fa']:
                dt.append([i.filled_area*k**2 for i in ls])
            if para['solid']:
                dt.append([round(i.solidity, 2) for i in ls])
            if para['cov']:
                dt.append([round(i.major_axis_length*k, 1) for i in ls])
                dt.append([round(i.minor_axis_length*k, 1) for i in ls])
                dt.append([round(i.orientation*k, 1) for i in ls])

            data.extend(list(zip(*dt)))
        ips.mark = Mark(mark)
        IPy.show_table(pd.DataFrame(data, columns=titles), ips.title+'-region')
Exemplo n.º 11
0
    def run(self, ips, imgs, para=None):
        sc, sr = ips.get_rect()
        print(sc, sr)
        c, r, w, h = sr.start, sc.start, sr.stop - sr.start, sc.stop - sc.start
        roi = imgs[0][r:r + h, c:c + w].copy()
        track_window = (c, r, w, h)
        hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),
                           np.array((180., 255., 255.)))
        roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
        cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
        # Setup the termination criteria, either 10 iteration or move by atleast 1 pt
        term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
        n = len(imgs)
        locs = []
        locs, mark = [], {'type': 'layers', 'body': {}}
        for i in range(n):
            prgs = (i, n)
            frame = imgs[i].copy()
            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)
            ret, track_window = cv2.CamShift(dst, track_window, term_crit)
            pts = cv2.boxPoints(ret)
            pts = np.int0(pts)

            layer = {'type': 'layer', 'body': []}
            temp = [tuple(i) for i in pts]
            layer['body'].append({
                'type':
                'line',
                'body': [(pts[0][0], pts[0][1]), (pts[1][0], pts[1][1]),
                         (pts[2][0], pts[2][1]), (pts[3][0], pts[3][1])]
            })
            layer['body'].append({
                'type':
                'line',
                'body': [(pts[0][0], pts[0][1]), (pts[3][0], pts[3][1])]
            })
            mark['body'][i] = layer
            locs.append([
                pts[0][0], pts[0][1], pts[1][0], pts[1][1], pts[2][0],
                pts[2][1], pts[3][0], pts[3][1]
            ])
        ips.mark = GeometryMark(mark)
        IPy.show_table(
            pd.DataFrame(locs,
                         columns=[
                             'P1_X',
                             'P1_y',
                             'P2_X',
                             'P2_y',
                             'P3_X',
                             'P3_y',
                             'P4_X',
                             'P4_y',
                         ]), ips.title + '-region')
Exemplo n.º 12
0
 def run(self, para=None):
     p = subprocess.Popen('%s -m pip list' % sys.executable,
                          stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE,
                          shell=True)
     lst = str(p.stdout.read(), encoding='utf-8').replace('\r\n',
                                                          '\n').split('\n')
     IPy.show_table(pd.DataFrame([[i] for i in lst], columns=['Packages']),
                    'Packages')
Exemplo n.º 13
0
 def report(self, title):
     rst = []
     titles = ['Area', 'OX', 'OY']
     for pg in self.body:
         plg = Polygon(pg)
         area, xy = plg.area, plg.centroid
         unit = 1 if self.unit==None else self.unit[0]
         axy = [area*unit**2, xy.x*unit, xy.y*unit]
         rst.append([round(i,1) for i in axy])
     IPy.show_table(pd.DataFrame(rst, columns=titles), title)
Exemplo n.º 14
0
 def run(self, tps, snap, data, para=None):
     rst, axis = {}, (0, 1)[para['axis'] == 'Row']
     if para['sum']: rst['sum'] = snap.sum(axis=axis)
     if para['mean']: rst['mean'] = snap.mean(axis=axis)
     if para['max']: rst['max'] = snap.max(axis=axis)
     if para['min']: rst['min'] = snap.min(axis=axis)
     if para['var']: rst['var'] = snap.var(axis=axis)
     if para['std']: rst['std'] = snap.std(axis=axis)
     if para['skew']: rst['skew'] = snap.skew(axis=axis)
     if para['kurt']: rst['kurt'] = snap.kurt(axis=axis)
     IPy.show_table(pd.DataFrame(rst), tps.title + '-statistic')
Exemplo n.º 15
0
    def report(self, title):
        rst, titles = [], ['K']
        for line in self.body:
            pts = np.array(line)
            mid = (pts[:-1]+pts[1:])/2

            dxy = (pts[:-1]-pts[1:])
            dxy[:,1][dxy[:,1]==0] = 1
            l = norm(dxy, axis=1)*-np.sign(dxy[:,1])
            rst.append(np.round(np.arccos(dxy[:,0]/l)/np.pi*180,1))
        IPy.show_table(pd.DataFrame(rst, columns=titles), title)
Exemplo n.º 16
0
    def run(self, ips, imgs, para = None):
        if para['nozero']: imgs = imgs[imgs!=0]
        minv, maxv = imgs.min(), imgs.max()
        bins = para['bins']
        if bins==0:bins = int(maxv - minv)+1
        ct, bins = np.histogram(imgs, bins, [minv, maxv+1])
        titles = ['value','count','frequence']
        dt = [bins[:-1].round(2), ct, (ct/ct.sum()).round(4)]
        dt = list(zip(*dt))

        IPy.show_table(pd.DataFrame(dt, columns=titles), ips.title+'-histogram')
Exemplo n.º 17
0
	def run(self, para=None):
		import calendar
		ls = calendar.month(para['year'], para['month']).split('\n')
		title = ls[0].strip()
		titles = ls[1].split(' ')
		table = []
		for i in ls[2:-1]:
			a = i.replace('   ', ' None ').strip()
			table.append(a.replace('  ', ' ').split(' '))
		dataframe = pd.DataFrame(table, columns=titles)
		IPy.show_table(dataframe, ls[0].strip())
Exemplo n.º 18
0
    def run(self, ips, imgs, para=None):
        k = ips.unit[0]

        titles = ['ID']
        if para['center']: titles.extend(['Center-X', 'Center-Y', 'Center-Z'])
        if para['surf']: titles.append('Surface')
        if para['vol']: titles.append('Volume')
        if para['extent']:
            titles.extend(
                ['Min-Z', 'Min-Y', 'Min-X', 'Max-Z', 'Max-Y', 'Max-X'])
        if para['ed']: titles.extend(['Diameter'])
        if para['fa']: titles.extend(['FilledArea'])
        if para['cov']: titles.extend(['Axis1', 'Axis2', 'Axis3'])

        strc = generate_binary_structure(
            3, 1 if para['con'] == '4-connect' else 2)
        buf, n = label(imgs, strc, output=np.uint32)
        ls = regionprops(buf)

        dt = [range(len(ls))]

        centroids = [i.centroid for i in ls]
        if para['center']:
            dt.append([round(i.centroid[1] * k, 1) for i in ls])
            dt.append([round(i.centroid[0] * k, 1) for i in ls])
            dt.append([round(i.centroid[2] * k, 1) for i in ls])
        if para['surf']:
            buf[find_boundaries(buf, mode='outer')] = 0
            vts, fs, ns, cs = marching_cubes_lewiner(buf, level=0)
            lst = [[] for i in range(n + 1)]
            for i in fs:
                lst[int(cs[i[0]])].append(i)
            dt.append([
                0 if len(i) == 0 else mesh_surface_area(vts, np.array(i)) *
                k**2 for i in lst
            ][1:])
        if para['vol']:
            dt.append([i.area * k**3 for i in ls])
        if para['extent']:
            for j in (0, 1, 2, 3, 4, 5):
                dt.append([i.bbox[j] * k for i in ls])
        if para['ed']:
            dt.append([round(i.equivalent_diameter * k, 1) for i in ls])
        if para['fa']:
            dt.append([i.filled_area * k**3 for i in ls])
        if para['cov']:
            ites = np.array([i.inertia_tensor_eigvals for i in ls])
            rst = np.sqrt(np.clip(ites.sum(axis=1) // 2 - ites.T, 0, 1e10)) * 4
            for i in rst[::-1]:
                dt.append(np.abs(i))
        IPy.show_table(pd.DataFrame(list(zip(*dt)), columns=titles),
                       ips.title + '-region')
Exemplo n.º 19
0
    def run(self, ips, imgs, para = None):
        titles = ['Max','Min','Mean','Variance','Standard']
        key = {'Max':'max','Min':'min','Mean':'mean','Variance':'var','Standard':'std'}
        titles = [i for i in titles if para[key[i]]]

        if not self.para['slice']:imgs = [ips.img]
        data = []
        msk = ips.get_msk('in')
        for n in range(len(imgs)):
            img = imgs[n] if msk is None else imgs[n][msk]
            data.append(self.count(img, para))
            self.progress(n, len(imgs))
        IPy.show_table(pd.DataFrame(data, columns=titles), ips.title+'-statistic')
Exemplo n.º 20
0
 def run(self, ips, snap, img, para = None):
     ips.lut = self.buflut
     k, unit = ips.unit
     lev, ds, step = para['thr'], para['ds'], para['step']
     scube = np.cumprod(ips.imgs.shape)[-1] * k**3
     sfront = (ips.imgs[::ds,::ds,::ds]>lev).sum() * ds ** 3 * k**3
     sback = scube - sfront
     print(scube, sfront, sback)
     vts, fs, ns, cs =  marching_cubes_lewiner(ips.imgs[::ds,::ds,::ds], lev, step_size=step)
     area = mesh_surface_area(vts, fs) * (ds**2 * k **2)
     rst = [round(i,3) for i in [scube, sfront, sback, sfront/scube, area, area/sfront]]
     titles = ['Cube Volume', 'Volume', 'Blank', 'Volume/Cube', 'Surface', 'Volume/Surface']
     IPy.show_table(pd.DataFrame([rst], columns=titles), ips.title+'-Volume Measure')
Exemplo n.º 21
0
 def report(self, title):
     rst = []
     for line in self.body:
         pts = np.array(line)
         dis = norm((pts[:-1] - pts[1:]), axis=1)
         dis *= 1 if self.unit is None else self.unit[0]
         rst.append(list(dis.round(2)))
     lens = [len(i) for i in rst]
     maxlen = max(lens)
     fill = [[0] * (maxlen - i) for i in lens]
     rst = [i + j for i, j in zip(rst, fill)]
     titles = ['L{}'.format(i + 1) for i in range(maxlen)]
     IPy.show_table(pd.DataFrame(rst, columns=titles), title)
Exemplo n.º 22
0
 def lineregress(self, ips):
     thick = self.body[1]['z']
     gray = [
         self.get_gray(ips.imgs[0].copy(), i) for i in self.body[0]['body']
     ]
     print(thick, gray)
     slope, intercept = lineregress(thick, gray)
     print(slope, intercept)
     a = np.arange(256)
     IPy.show_table(pd.DataFrame(np.array([a, slope * a + intercept])),
                    title='temp')
     wx.CallAfter(pub.sendMessage,
                  'lineregress_plot',
                  para=([thick, gray], slope, intercept))
Exemplo n.º 23
0
 def run(self, ips, imgs, para = None):
     data = []
     sly, slx = ips.get_rect()
     xs = np.linspace(0, slx.stop-slx.start-1, para['num']).astype(int)
     for img in imgs:
         img = img[sly, slx]
         ys = np.array([np.where(img[:,i]==255)[0].max() for i in xs])
         data.append(ys+sly.start)
     xs += slx.start
     ips.mark = Mark(xs, data)
     k,unit = ips.unit
     data = (np.array(data)*k).round(3)
     # IPy.table(ips.title+'-pts', data, ['%.3f'%i for i in xs*k])
     IPy.show_table(pd.DataFrame(data, columns=['%.3f'%i for i in xs*k]), ips.title+'-pts')
Exemplo n.º 24
0
 def run(self, tps, snap, data, para=None):
     rst, axis = {}, (0, 1)[para['axis'] == 'Row']
     if para['sum']: rst['sum'] = snap.sum(axis=axis)
     if para['mean']: rst['mean'] = snap.mean(axis=axis)
     if para['max']: rst['max'] = snap.max(axis=axis)
     if para['min']: rst['min'] = snap.min(axis=axis)
     if para['var']: rst['var'] = snap.var(axis=axis)
     if para['std']: rst['std'] = snap.std(axis=axis)
     if para['skew']: rst['skew'] = snap.skew(axis=axis)
     if para['kurt']: rst['kurt'] = snap.kurt(axis=axis)
     cols = ['sum', 'mean', 'min', 'max', 'var', 'std', 'skew', 'kurt']
     cols = [i for i in cols if i in rst]
     IPy.show_table(
         pd.DataFrame(rst, columns=cols).T, tps.title + '-statistic')
Exemplo n.º 25
0
	def run(self, para):
		fs = glob(para['path']+'/*.tif')
		boxes, csr = [], {}
		for i in fs:
			print('build', i, '...')
			rs = gdal.Open(i)
			csr = rs.GetProjection()
			m = rs.GetGeoTransform()
			m = np.array(m).reshape((2,3))
			shp = (rs.RasterYSize, rs.RasterXSize)
			boxes.append([raster_box(shp, csr, m), i])
		gdf = gpd.GeoDataFrame(boxes, columns=['geometry', 'path'])
		print(csr)
		gdf.crs = makeprj(csr).ExportToProj4()
		IPy.show_table(gdf, 'geoindex')
Exemplo n.º 26
0
    def run(self, para = None):
        path = para['path']
        date = para['time']
        check = para['check']
        line = para['line']
        point = para['type'] == '点图'
        text = [para['t%d'%i] for i in (1,2,3,4,5,6,7,8)]
        text = [i for i in text if len(i)>1]

        try:
            rst = draw(path, date, text, point, line, check)
            if check: IPy.show_table(rst, '新增地名列表')
            else: IPy.show_img([rst], '草地贪夜蛾分布示意图')
        except: 
            IPy.alert('请检查数据格式!')
Exemplo n.º 27
0
 def run(self, ips, imgs, para=None):
     if para['method'] == 'Simple Ratio':
         rst, value, ratio = simple_ratio(imgs, ips.img, not para['new'],
                                          self.progress)
         body = pd.DataFrame({'Mean value': value, 'Ratio': ratio})
         IPy.show_table(body, '%s-simple ratio' % ips.title)
     if para['method'] == 'Exponential Fit':
         rst, popt, intensity, fitrst = exponential_fit(
             imgs, not para['new'], self.progress)
         plot_after(popt, intensity, fitrst)
         body = {'Intensity': intensity, 'Fit': fitrst}
         IPy.show_table(pd.DataFrame(body), '%s-exp fit' % ips.title)
     if para['method'] == 'Histogram Match':
         rst = histogram_match(imgs, ips.img, not para['new'],
                               self.progress)
     if para['new']: IPy.show_img(rst, '%s-corrected' % ips.title)
Exemplo n.º 28
0
 def report(self, title):
     rst = []
     for line in self.body:
         pts = np.array(line)
         v1 = pts[:-2]-pts[1:-1]
         v2 = pts[2:]-pts[1:-1]
         a = np.sum(v1*v2, axis=1)*1.0
         a/=norm(v1,axis=1)*norm(v2,axis=1)
         ang = np.arccos(a)/np.pi*180
         rst.append(list(ang.round(1)))
     lens = [len(i) for i in rst]
     maxlen = max(lens)
     fill = [[0]*(maxlen-i) for i in lens]
     rst = [i+j for i,j in zip(rst, fill)]
     titles = ["A{}".format(i+1) for i in range(maxlen)]
     IPy.show_table(pd.DataFrame(rst, columns=titles), title)
Exemplo n.º 29
0
 def run(self, tps, snap, data, para=None):
     rg = None if para['auto'] else (para['min'], para['max'])
     for i in para['cn']:
         hist, bins = np.histogram(data[i], para['bins'], rg)
         vs = {'bins': bins[:-1]}
         if para['count']: vs['count'] = hist
         if para['fre']: vs['frequency'] = hist / hist.sum()
         if para['weight']:
             vs['weight'] = np.histogram(data[i], bins, rg,
                                         weights=data[i])[0]
         df = pd.DataFrame(
             vs,
             columns=[
                 i for i in ['bins', 'count', 'frequency', 'weight']
                 if i in vs
             ])
         IPy.show_table(df, '%s-frequency' % i)
Exemplo n.º 30
0
 def run(self, ips, snap, img, para=None):
     icemsk = ips.get_msk()
     grid, lines, row, col = self.grid(ips, para)
     from time import time
     a = time()
     mjd = []
     for pts in grid:
         msk = polygon(*pts.T[::-1], shape=img.shape[:2])
         inice = icemsk[msk] > 0
         if inice.sum() <= len(msk[0]) // 2: mjd.append(-3)
         else:
             value = img[msk[0][inice], msk[1][inice]].mean()
             mjd.append(value if value > para['thr'] else 0)
         #ips.img[msk[0], msk[1]] = 0
     data = np.array(mjd).reshape(row, col)
     print('value', time() - a)
     IPy.show_table(pd.DataFrame(data), title=ips.title + '-Field')