Example #1
0
    def run(self, para=None):
        xs = [0, 30, 117, 255]
        ys = [0, 0, 255, 255]
        data = np.array([30, 57, 93, 105, 110, 117, 108, 87, 52, 39])
        l1 = plt.plot(xs, ys, 'r', lw=3)
        plt.grid()
        plt.title('y = 2.931 * x - 87.931')
        plt.gca().set_ylim(0, 256)
        plt.gca().set_xlim(0, 256)
        plt.figure()
        plt.grid()
        xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        ys = np.round(data * 2.931 - 87.931)
        l1 = plt.plot(xs, ys, '-o')
        plt.show()

        data = np.array([30, 57, 93, 105, 110, 117, 108, 87, 52, 39])
        ori = np.zeros((10, 30, 30), dtype=np.uint8)
        ori.T[:] = np.round(data * 2.931 - 87.931)

        #area = (area-5) * 8
        IPy.show_img([np.hstack(ori)], 'Extend')
Example #2
0
    def run(self, ips, imgs, para=None):
        if not para['slice']: imgs = [ips.img]
        data = []
        msk = ips.get_msk('in')
        for i in range(len(imgs)):
            img = imgs[i] if msk is None else imgs[i][msk]
            maxv = img.max()
            if maxv == 0: continue
            ct = np.histogram(img, maxv, [1, maxv + 1])[0]
            titles = ['slice', 'value', 'count']
            dt = [[i] * len(ct), list(range(maxv + 1)), ct]
            if not para['slice']:
                titles, dt = titles[1:], dt[1:]
            if self.para['fre']:
                fre = ct / float(ct.sum())
                titles.append('frequence')
                dt.append(fre.round(4))
            dt = list(zip(*dt))
            data.extend(dt)

        IPy.show_table(pd.DataFrame(data, columns=titles),
                       ips.title + '-histogram')
Example #3
0
 def on_minmax(self, event):
     ips = IPy.get_ips()
     if ips is None: return
     minv, maxv = ips.get_updown()
     self.range = ips.range = (minv, maxv)
     hist = ips.histogram()
     self.histpan.SetValue(hist)
     self.sli_low.set_para(self.range, 10)
     self.sli_high.set_para(self.range, 10)
     self.sli_low.SetValue(minv)
     self.sli_high.SetValue(maxv)
     self.histpan.set_lim(0, 255)
     ips.update = 'pix'
Example #4
0
 def zoom(self, k, x, y):
     # print 'scale', k
     k1 = self.oldscale * 1.0
     self.oldscale = k2 = k
     self.imgbox[0] = int(self.imgbox[0] + (k1-k2)*x+0.5)
     self.imgbox[1] = int(self.imgbox[1] + (k1-k2)*y+0.5)
     self.imgbox[2] = int(self.ips.size[1] * k2+0.5)
     self.imgbox[3] = int(self.ips.size[0] * k2+0.5)
     lay(self.box, self.imgbox)
     if self.imgbox[2]<=self.scrsize[0]*0.9 and\
     self.imgbox[3]<=self.scrsize[1]*0.9 and IPy.uimode()=='ij':
         self.SetInitialSize((self.imgbox[2], self.imgbox[3]))
         if not self.handle is None: self.handle(self.ips, True)
Example #5
0
 def on_mouseevent(self, me):
     tool = self.ips.tool
     if tool == None : tool = ToolsManager.curtool
     x,y = self.to_data_coor(me.GetX(), me.GetY())
     if me.Moving() and not me.LeftIsDown() and not me.RightIsDown() and not me.MiddleIsDown():
         xx,yy = int(round(x)), int(round(y))
         k, unit = self.ips.unit
         if xx>=0 and xx<self.ips.img.shape[1] and yy>=0 and yy<self.ips.img.shape[0]:
             IPy.set_info('Location:%.1f %.1f  Value:%s'%(x*k, y*k, self.ips.img[yy,xx]))
     if tool==None:return
     
     sta = [me.AltDown(), me.ControlDown(), me.ShiftDown()]
     if me.ButtonDown():tool.mouse_down(self.ips, x, y, me.GetButton(), alt=sta[0], ctrl=sta[1], shift=sta[2], canvas=self)
     if me.ButtonUp():tool.mouse_up(self.ips, x, y, me.GetButton(), alt=sta[0], ctrl=sta[1], shift=sta[2], canvas=self)
     if me.Moving():tool.mouse_move(self.ips, x, y, None, alt=sta[0], ctrl=sta[1], shift=sta[2], canvas=self)
     btn = [me.LeftIsDown(), me.MiddleIsDown(), me.RightIsDown(),True].index(True)
     if me.Dragging():tool.mouse_move(self.ips, x, y, 0 if btn==3 else btn+1, alt=sta[0], ctrl=sta[1], shift=sta[2], canvas=self)
     wheel = np.sign(me.GetWheelRotation())
     if wheel!=0:tool.mouse_wheel(self.ips, x, y, wheel, alt=sta[0], ctrl=sta[1], shift=sta[2], canvas=self)
     if hasattr(tool, 'cursor'):
         self.SetCursor(wx.Cursor(tool.cursor))
     else : self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
Example #6
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')
    def run(self, ips, imgs, para=None):
        ls = []
        for x, y, z in ips.roi.body:
            x, y, z = int(x), int(y), int(z)
            r, g, b = imgs[z][y, x]
            ls.append([x, y, z, r, g, b])

        data = pd.DataFrame(ls, columns=[*'XYZRGB'])
        rst = {}

        if para['sum']: rst['sum'] = data[[*'RGB']].sum()
        if para['mean']: rst['mean'] = data[[*'RGB']].mean()
        if para['max']: rst['max'] = data[[*'RGB']].max()
        if para['min']: rst['min'] = data[[*'RGB']].min()
        if para['var']: rst['var'] = data[[*'RGB']].var()
        if para['std']: rst['std'] = data[[*'RGB']].std()
        if para['skew']: rst['skew'] = data[[*'RGB']].skew()
        if para['kurt']: rst['kurt'] = data[[*'RGB']].kurt()

        if para['lst']:
            IPy.show_table(data, ips.title + '-pts color')
        IPy.show_table(pd.DataFrame(rst), ips.title + '-pts color statistic')
Example #8
0
 def run(self, ips, snap, img, para=None):
     # 人脸检测
     # 获取当前工作路径
     path = os.getcwd()
     face_cascade = cv2.CascadeClassifier(
         path + '\menus\Opencv\Filters\haarcascade_frontalface_default.xml')
     gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
     faces = face_cascade.detectMultiScale(gray, 1.3, 5)
     for (x, y, w, h) in faces:
         ips.mark = GeometryMark({
             'type': 'rectangles',
             'color': (255, 0, 0),
             'lw': 2,
             'fcolor': (0, 0, 0),
             'fill': False,
             'body': [(x, y, w, h)]
         })
         # 用下面这句会影响到原图像,导致不能再编辑,可以用上面的标记
         # cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
     IPy.show_table(
         pd.DataFrame([[x, y, w, h]],
                      index=['矩形'],
                      columns=['x', 'y', 'w', 'h']), '人脸参数')
Example #9
0
	def on_8bit( self, event ):
		ips = IPy.get_ips()
		if ips is None: return
		self.range = ips.range = (0,255)
		hist = ips.histogram()
		self.histpan.set_hist(hist)
		self.sli_low.SetMax(255)
		self.sli_low.SetMin(0)
		self.sli_high.SetMax(255)
		self.sli_high.SetMin(0)
		self.sli_low.SetValue(0)
		self.sli_high.SetValue(255)
		self.histpan.set_lim(0,255)
		ips.update = 'pix'
Example #10
0
    def start(self):
        #if not WidgetsManager.getref(self.title) is None: return
        pan = self.pan(IPy.curapp)
        WidgetsManager.addref(pan)
        IPy.curapp.auimgr.AddPane(
            pan,
            aui.AuiPaneInfo().Caption(self.title).Left().Layer(15).PinButton(
                True).Float().Resizable().FloatingSize(
                    wx.DefaultSize).Dockable(
                        IPy.uimode() == 'ipy').DestroyOnClose())

        IPy.curapp.Layout()
        IPy.curapp.auimgr.Update()
        '''
Example #11
0
    def run(self, para=None):
        xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
        ys = [10, 12, 16, 22, 26, 28, 30, 30, 25, 21, 16, 11]
        lbs = [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'
        ]
        plt.xticks(xs, lbs)

        plt.plot(xs, ys, '-o')
        plt.grid()

        plt.title('Temperature in ChengDu')
        plt.xlabel('Month')
        plt.ylabel('Temperature (C)')

        plt.show()

        area = np.zeros((12, 30, 30), dtype=np.uint8)
        temp = np.array([10, 12, 16, 22, 26, 28, 30, 30, 25, 21, 16, 11])
        area.T[:] = temp
        area = (area - 5) * 8
        IPy.show_img([np.hstack(area)], 'Chengdu Temperature')
Example #12
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:] + [
            'Center-X', 'Center-Y', 'N', 'Neighbors'
        ]
        buf = imgs[0].astype(np.uint32)
        data, mark = [], {'type': 'layers', 'body': {}}
        for i in range(len(imgs)):
            if para['labled']: buf = imgs[i]
            else: label(imgs[i], generate_binary_structure(2, 1), output=buf)
            conarr = connect(buf, 1 if para['con'] == '4-connect' else 2,
                             not self.para['nozero'])
            conmap = mapidx(conarr)

            ls = regionprops(buf)
            dt = [[i] * len(ls), list(range(1, 1 + len(ls)))]

            if not para['slice']: dt = dt[1:]

            layer = {'type': 'layer', 'body': []}
            texts = [(i.centroid[::-1]) + ('id=%d' % i.label, ) for i in ls]
            lines = [(ls[i - 1].centroid[::-1], ls[j - 1].centroid[::-1])
                     for i, j in conarr]
            layer['body'].append({'type': 'texts', 'body': texts})
            layer['body'].append({'type': 'lines', 'body': lines})
            mark['body'][i] = layer

            dt.append([round(i.centroid[1] * k, 1) for i in ls])
            dt.append([round(i.centroid[0] * k, 1) for i in ls])
            neibs = [conmap[i.label] if i.label in conmap else [] for i in ls]
            dt.extend([[len(i) for i in neibs], neibs])
            data.extend(list(zip(*dt)))
        ips.mark = GeometryMark(mark)
        IPy.show_table(pd.DataFrame(data, columns=titles),
                       ips.title + '-region')
Example #13
0
 def on_8bit(self, event):
     ips = IPy.get_ips()
     if ips is None: return
     rg = (0, 255)
     ips.chan_range[self.active] = rg
     if (rg[0] == rg[1]): rg = (rg[0] - 1e-4, rg[1] + 1e-4)
     slis = 'all' if self.chk_stack.GetValue() else ips.cur
     hist = ips.histogram(rg, slis, self.active, 512)
     self.histpan.SetValue(hist)
     self.sli_low.set_para(rg, 10)
     self.sli_high.set_para(rg, 10)
     self.sli_low.SetValue(rg[0])
     self.sli_high.SetValue(rg[1])
     self.histpan.set_lim(0, 255)
     ips.update()
Example #14
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
        IPy.show_table(pd.DataFrame(datas, columns=titles[1 - para['parts']:]),
                       ips.title + '-graph')
Example #15
0
    def run(self, para=None):
        xs = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
        ys = np.array([1, 2, 1, 2, 2, 3, 8, 9, 8, 10, 9, 10], dtype=np.float32)
        ds = ndimg.convolve1d(ys, [0, 1, -1])
        lbs = [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'
        ]
        plt.xticks(xs, lbs)

        plt.plot(xs, ys, '-o', label='Temperature')
        plt.plot(xs, ds, '-o', label='Difference')
        plt.grid()
        plt.gca().legend()

        plt.title('Temperature in XX')
        plt.xlabel('Month')
        plt.ylabel('Temperature (C)')

        plt.show()
        IPy.show_img([block((ys - ys.min()) * (180 / ys.max() - ys.min()))],
                     'Temperature')
        IPy.show_img([block((ds - ds.min()) * (180 / ds.max() - ds.min()))],
                     'Difference')
Example #16
0
    def run(self, ips, imgs, para=None):
        name = self.para['name']
        if ips.get_nslices() == 1 or self.para['stack'] == False:
            if ips.roi == None:
                img = ips.img.copy()
                ipsd = ImagePlus([img], name)
            else:
                img = ips.get_subimg().copy()
                ipsd = ImagePlus([img], name)
                box = ips.roi.get_box()
                ipsd.roi = ips.roi.affine(np.eye(2), (-box[0], -box[1]))
        elif ips.get_nslices() > 1 and self.para['stack']:
            if ips.roi == None:
                if ips.is3d: imgs = imgs.copy()
                else: imgs = [i.copy() for i in imgs]
            else:
                sc, sr = ips.get_rect()
                if ips.is3d: imgs = imgs[:, sc, sr].copy()
                else: imgs = [i[sc, sr].copy() for i in imgs]
            ipsd = ImagePlus(imgs, name)
            if ips.roi != None:
                ipsd.roi = ips.roi.affine(np.eye(2), (-sr.start, -sc.start))

        IPy.show_ips(ipsd)
Example #17
0
 def run(self, ips, imgs, para=None):
     name = para['name']
     print('name------------------', name)
     if ips.get_nslices() == 1 or self.para['stack'] == False:
         if ips.roi == None:
             img = ips.img.copy()
             ipsd = ImagePlus([img], name)
             ipsd.back = ips.back
         else:
             img = ips.get_subimg().copy()
             ipsd = ImagePlus([img], name)
             box = ips.roi.get_box()
             ipsd.roi = ips.roi.affine(np.eye(2), (-box[0], -box[1]))
             '''
             if not ips.backimg is None:
                 sr, sc = ips.get_rect()
                 ipsd.backimg = ips.backimg[sr, sc]
             '''
     elif ips.get_nslices() > 1 and self.para['stack']:
         imgs = imgs[para['start'] - 1:para['end']]
         if ips.roi == None:
             if ips.is3d: imgs = imgs.copy()
             else: imgs = [i.copy() for i in imgs]
             #backimg = ips.backimg
         else:
             sc, sr = ips.get_rect()
             if ips.is3d: imgs = imgs[:, sc, sr].copy()
             else: imgs = [i[sc, sr].copy() for i in imgs]
             #if not ips.backimg is None:
             #    backimg = None #ips.backimg[sr, sr]
         ipsd = ImagePlus(imgs, name)
         if ips.roi != None:
             ipsd.roi = ips.roi.affine(np.eye(2), (-sr.start, -sc.start))
         #if not ips.backimg is None: ipsd.backimg = backimg
     ipsd.chan_mode = ips.chan_mode
     IPy.show_ips(ipsd)
Example #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['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'])

        buf = imgs.astype(np.uint32)
        strc = generate_binary_structure(
            3, 1 if para['con'] == '4-connect' else 2)
        label(imgs, strc, output=buf)
        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['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])
        IPy.show_table(pd.DataFrame(list(zip(*dt)), columns=titles),
                       ips.title + '-region')
Example #19
0
 def start(self, para=None, callafter=None):
     wb = pyxl.load_workbook(self.cont)
     xlreport.repair(wb)
     info, key = xlreport.parse(wb)
     if para is not None:
         return self.runasyn(wb, info, para, callafter)
     dialog = GridDialog(IPy.curapp, self.title, info, key)
     rst = dialog.ShowModal()
     para = dialog.GetValue()
     dialog.Destroy()
     if rst != 5100: return
     filt = '|'.join(['%s files (*.%s)|*.%s' % ('XLSX', 'xlsx', 'xlsx')])
     if not IPy.getpath('Save..', filt, 'save', para): return
     win = WidgetsManager.getref('Macros Recorder')
     if win != None: win.write('{}>{}'.format(self.title, para))
     self.runasyn(wb, info, key, para, callafter)
    def load(self):

        dirdialog = wx.DirDialog(IPy.get_window(),
                                 message=wx.DirSelectorPromptStr,
                                 defaultPath="",
                                 style=wx.DD_DEFAULT_STYLE,
                                 pos=wx.DefaultPosition,
                                 size=wx.DefaultSize,
                                 name=wx.DirDialogNameStr)

        if dirdialog.ShowModal() == wx.ID_OK:
            self.pathAPI = dirdialog.GetPath()
            self.pathAPI = self.pathAPI + os.path.sep
        else:
            return False

        if platform.system() == 'Windows':
            self.python = 'python'
        else:
            self.python = 'python3'
        subprocess.check_output(
            [self.python, self.pathAPI + 'listFrameworks.py'])
        data = json.load(open('data.json'))
        frameworks = data['frameworks']

        subprocess.check_output(
            [self.python, self.pathAPI + 'listModels.py', '-f', 'Keras'])
        data = json.load(open('data.json'))
        models = data['models']

        Para = {'f': 'Keras', 'm': 'VGG16'}
        View = [('lab', 'Select the framework and the model'),
                (list, frameworks, str, 'Framework', 'f', ''),
                (list, models, str, 'Model', 'm', '')]
        md = MyDialog(None, 'DeepClas4BioPy', self.pathAPI, self.python, View,
                      Para)
        md.initView()

        if md.ShowModal() == wx.ID_OK:
            self.framework = md.para['f']
            self.model = md.para['m']
            md.Destroy()
            return True
        else:
            md.Destroy()
            return False
Example #21
0
 def on_gray(self, event):
     ips = IPy.get_ips()
     if ips is None: return
     if not isinstance(ips.chan, int): ips.chan = 0
     chanrg = ips.chan_range[ips.chan]
     rg = ips.get_updown('all', ips.chan, 512)
     if (rg[0] == rg[1]): rg = (rg[0] - 1e-4, rg[1] + 1e-4)
     slis = 'all' if self.chk_stack.GetValue() else ips.cur
     hist = ips.histogram(rg, slis, ips.chan, 512)
     self.histpan.SetValue(hist)
     self.sli_low.set_para(rg, 10)
     self.sli_high.set_para(rg, 10)
     self.sli_low.SetValue(chanrg[0])
     self.sli_high.SetValue(chanrg[1])
     self.active = ips.chan
     lim1 = (chanrg[0] - rg[0]) / (rg[1] - rg[0])
     lim2 = (chanrg[1] - rg[0]) / (rg[1] - rg[0])
     self.histpan.set_lim(lim1 * 255, lim2 * 255)
     ips.update()
Example #22
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('请检查数据格式!')
Example #23
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)
Example #24
0
 def on_p(self, event, k):
     ips = IPy.get_ips()
     if ips is None: return
     rg = ips.get_updown('all', self.active, 512)
     if (rg[0] == rg[1]): rg = (rg[0] - 1e-4, rg[1] + 1e-4)
     slis = 'all' if self.chk_stack.GetValue() else ips.cur
     hist = ips.histogram(rg, slis, self.active, 512)
     msk = np.abs(np.cumsum(hist) / hist.sum() - 0.5) < k / 2
     idx = np.where(msk)[0]
     vs = np.array([idx.min(), idx.max()])
     vs = vs * (rg[1] - rg[0]) / 255 + rg[0]
     ips.chan_range[self.active] = tuple(vs)
     self.histpan.SetValue(hist)
     self.sli_low.set_para(rg, 10)
     self.sli_high.set_para(rg, 10)
     print(rg, vs)
     self.sli_low.SetValue(vs[0])
     self.sli_high.SetValue(vs[1])
     lim1 = (vs[0] - rg[0]) / (rg[1] - rg[0])
     lim2 = (vs[1] - rg[0]) / (rg[1] - rg[0])
     self.histpan.set_lim(lim1 * 255, lim2 * 255)
     ips.update()
Example #25
0
    def run(self, ips, imgs, para=None, preview=False):
        if len(ips.imgs) == 1: ips.img[:] = ips.snap
        key = {'chans': None, 'grade': para['grade'], 'w': para['w']}
        key['items'] = [i for i in ['ori', 'blr', 'sob', 'eig'] if para[i]]
        slir, slic = ips.get_rect()
        labs = [i[slir, slic] for i in imgs]
        ori = ImageManager.get(para['img']).imgs
        if len(imgs) == 1: ori = [ImageManager.get(para['img']).img]
        oris = [i[slir, slic] for i in ori]

        IPy.set_info('extract features...')
        feat, lab, key = feature.get_feature(oris,
                                             labs,
                                             key,
                                             callback=self.progress)

        IPy.set_info('training data...')
        self.progress(None, 1)
        model = self.classify(para)
        model.fit(feat, lab)

        IPy.set_info('predict data...')
        if preview:
            return feature.get_predict(oris,
                                       model,
                                       key,
                                       labs,
                                       callback=self.progress)
        if len(imgs) == 1: ips.swap()
        outs = feature.get_predict(oris, model, key, callback=self.progress)
        nips = ImagePlus(outs, ips.title + 'rst')
        nips.range, nips.lut = ips.range, ips.lut
        nips.back, nips.chan_mode = ips.back, 0.4
        IPy.show_ips(nips)
        global model_para
        model_para = model, key
Example #26
0
    def profile(self, body, img):
        (x1, y1), (x2, y2) = body[0]
        dx, dy = x2-x1, y2-y1
        n = max(abs(dx), abs(dy)) + 1
        xs = np.linspace(x1, x2, n).round().astype(np.int16)
        ys = np.linspace(y1, y2, n).round().astype(np.int16)
        msk = (xs>=0) * (xs<img.shape[1])
        msk*= (ys>=0) * (ys<img.shape[0])
        ix = np.arange(len(xs))

        frame = IPy.plot('Profile', 'Profile - Line', 'pixels coordinate', 'value of pixcels')
        frame.clear()
        if len(img.shape) == 3:
            vs = np.zeros((3,len(xs)), dtype=np.int16)
            vs[:,msk] = img[ys[msk], xs[msk]].T
            frame.add_data(ix, vs[0], (255,0,0), 1)
            frame.add_data(ix, vs[1], (0,255,0), 1)
            frame.add_data(ix, vs[2], (0,0,255), 1)
        else: 
            vs = np.zeros(len(xs), dtype=np.int16)
            vs[msk] = img[ys[msk], xs[msk]]
            frame.add_data(ix, vs, (0,0,0), 1)
        frame.draw()
Example #27
0
 def on_run(self, event):
     if self.active != event.GetIndex():
         return IPy.alert('please double click to activate an item')
     code = event.GetKeyCode()
     title = self.buf[event.GetIndex()][0]
     txt = self.buf[event.GetIndex()][1]
     if code == wx.WXK_DELETE:
         txt = ''
     elif code == wx.WXK_CONTROL:
         txt = self.ist(txt, 'Ctrl')
     elif code == wx.WXK_ALT:
         txt = self.ist(txt, 'Alt')
     elif code == wx.WXK_SHIFT:
         txt = self.ist(txt, 'Shift')
     elif code in range(340, 352):
         fs = ['F' + str(i) for i in range(1, 13)]
         txt = self.ist(txt, fs[code - 340])
     elif code < 100:
         txt = self.ist(txt, chr(event.GetKeyCode()))
     if len(txt) > 0 and txt[-1] == '-': txt = txt[:-1]
     self.buf[event.GetIndex()][1] = txt
     self.lst_plgs.RefreshItem(event.GetIndex())
     if txt == '': ShotcutManager.rm(title)
     ShotcutManager.set(title, txt)
Example #28
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 self.para['stack']:
            data = []
            for n in range(ips.get_nslices()):
                data.append(self.count(imgs[n], para))
                IPy.set_progress(round((n + 1) * 100.0 / len(imgs)))
            IPy.set_progress(0)
        else:
            data = [self.count(ips.get_img(), para)]
        IPy.table(ips.title + '-statistic', data, titles)
Example #29
0
    def run(self, para=None):
        xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        ys = np.array([30, 57, 93, 105, 110, 117, 108, 87, 52, 39])
        l1 = plt.plot(xs, ys, '-o', label='orignal')
        l2 = plt.plot(xs, ys + 100, '-o', label='add')
        l3 = plt.plot(xs, ys * 2, '-o', label='multiply')
        plt.grid()
        plt.title('Math Operator')
        plt.gca().set_ylim(0, 255)
        plt.gca().legend()
        plt.show()

        ori = np.zeros((10, 30, 30), dtype=np.uint8)
        add = np.zeros((10, 30, 30), dtype=np.uint8)
        mul = np.zeros((10, 30, 30), dtype=np.uint8)
        ori.T[:], add.T[:], mul.T[:] = ys, ys + 100, ys * 2

        #area = (area-5) * 8
        IPy.show_img([np.hstack(ori)], 'Orignal Line')
        IPy.show_img([np.hstack(add)], 'Add 100')
        IPy.show_img([np.hstack(mul)], 'Multiply 2')
Example #30
0
    def run(self, ips, imgs, para=None):
        ips1 = ImageManager.get(para['img1'])
        ips2 = ImageManager.get(para['img2'])
        ips1.snapshot()

        sl1, sl2 = ips1.get_nslices(), ips2.get_nslices()
        cn1, cn2 = ips1.get_nchannels(), ips2.get_nchannels()
        if ips1.dtype != ips2.dtype:
            IPy.alert('Two stack must be equal dtype!')
            return
        elif sl1 > 1 and sl2 > 1 and sl1 != sl2:
            IPy.alert('Two stack must have equal slices!')
            return
        elif cn1 > 1 and cn2 > 1 and cn1 != cn2:
            IPy.alert('Two stack must have equal channels!')
            return

        w, h = ips1.size, ips2.size
        w, h = min(w[0], h[0]), min(w[1], h[1])
        if sl1 == 1:
            bliter.blit(ips1.get_subimg(), ips2.get_subimg(), mode=para['op'])
        elif sl1 > 1 and sl2 == 1:
            for i in range(sl1):
                self.progress(i, sl1)
                ss1, se1 = ips1.get_rect()
                bliter.blit(ips1.imgs[i][ss1, se1],
                            ips2.get_subimg(),
                            mode=para['op'])
        elif sl1 > 1 and sl2 > 1:
            for i in range(sl1):
                self.progress(i, sl1)
                ss1, se1 = ips1.get_rect()
                ss2, se2 = ips2.get_rect()
                bliter.blit(ips1.imgs[i][ss1, se1],
                            ips2.imgs[i][ss2, se2],
                            mode=para['op'])
        ips1.update = 'pix'