示例#1
0
    def make_mark(self, x, y):
        wins = self.para['win']
        rect = {
            'type': 'rectangle',
            'body': (x, y, wins * 2, wins * 2),
            'color': self.para['color']
        }
        mark = {'type': 'layer', 'body': [rect]}
        r = 2 if self.status == 'local_brush' else self.para['r'] / 2
        mark['body'].append({
            'type': 'circle',
            'body': (x, y, r),
            'color': self.para['color']
        })

        mark['body'].append({
            'type':
            'text',
            'body': (x - wins, y - wins,
                     'S:%s W:%s' % (self.para['ms'], self.para['win'])),
            'pt':
            False,
            'color':
            self.para['color']
        })
        return GeometryMark(mark)
示例#2
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')
示例#3
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
示例#4
0
 def run(self, ips, imgs, para=None):
     pts = (np.random.rand(200) * 512).reshape((100, 2))
     ips.mark = GeometryMark({
         'type': 'points',
         'color': (255, 0, 0),
         'lw': 1,
         'body': pts
     })
示例#5
0
 def run(self, ips, imgs, para=None):
     f = open(para['path'])
     geo = json.load(f)
     f.close()
     if geo['type'] == 'layers':
         body = geo['body']
         for i in list(body.keys()):
             body[int(i)] = body.pop(i)
     ips.mark = GeometryMark(geo)
示例#6
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')
示例#7
0
 def preview(self, ips, para):
     grayimg = ips.img if ips.img.ndim == 2 else ips.img.mean(axis=-1)
     grayimg /= grayimg.max()
     pts = blob_doh(grayimg,
                    min_sigma=para['min_sigma'],
                    max_sigma=para['max_sigma'],
                    num_sigma=para['num_sigma'],
                    threshold=para['threshold'],
                    overlap=para['overlap'],
                    log_scale=para['log_scale'])
     ips.mark = GeometryMark({'type': 'circles', 'body': pts[:, [1, 0, 2]]})
示例#8
0
 def run(self, ips, imgs, para=None):
     marks = {'type': 'layers', 'body': {}}
     for i, img in enumerate(imgs):
         tmp = img.copy().astype('float32') / 255.0
         out = self.net(tmp[None, None, :, :])
         pred = np.argmax(out, -1)
         marks['body'][i] = {
             'type': 'text',
             'color': (255, 0, 0),
             'body': (2, -2, str(pred))
         }
     ips.mark = GeometryMark(marks)
示例#9
0
 def preview(self, ips, para):
     grayimg = ips.img if ips.img.ndim == 2 else ips.img.mean(axis=-1)
     grayimg /= grayimg.max()
     pts = blob_dog(grayimg,
                    min_sigma=para['min_sigma'],
                    max_sigma=para['max_sigma'],
                    sigma_ratio=para['sigma_ratio'],
                    threshold=para['threshold'],
                    overlap=para['overlap'],
                    exclude_border=para['exclude_border'])
     pts[:, 2] *= np.sqrt(2)
     ips.mark = GeometryMark({'type': 'circles', 'body': pts[:, [1, 0, 2]]})
示例#10
0
 def draw(self,ips):
     mark = {'type':'layers', 'body':{}}
     layer = {'type':'layer', 'body':[]}
     layer['body'].append({'type':'points', 'body':self.buf})
     if len(self.buf)>1:
         lines=route_through(ips, ips.img,[self.buf],self.para)
         lst=[]
         for line in lines:lst.append([(j,i) for i,j in line])
         layer['body'].append({'type':'lines', 'body':lst})
     mark['body'][0] = layer
     ips.mark = GeometryMark(mark)
     ips.update()     
示例#11
0
 def update(self, ips):
     ips.mark = GeometryMark({
         'type':
         'layer',
         'body': [{
             'type': 'points',
             'body': [(i[0], i[1]) for i in ips.data['adjc']]
         }, {
             'type': 'circles',
             'body': [(i[0], i[1], i[2]) for i in ips.data['adjc']]
         }, {
             'type':
             'texts',
             'body':
             [(i[0], i[1], 'z=%.1f' % i[3]) for i in ips.data['adjc']]
         }]
     })
     ips.update()
示例#12
0
    def run(self, ips, imgs, para=None):
        if not para['slice']: imgs = [ips.img]

        data, sid, fid, mark = [], [], [], {'type': 'layers', 'body': {}}

        for i in range(len(imgs)):
            grayimg = imgs[i] if imgs[i].ndim == 2 else imgs[i].mean(axis=-1)
            grayimg /= grayimg.max()
            pts = blob_log(grayimg,
                           min_sigma=para['min_sigma'],
                           max_sigma=para['max_sigma'],
                           num_sigma=para['num_sigma'],
                           threshold=para['threshold'],
                           overlap=para['overlap'],
                           log_scale=para['log_scale'],
                           exclude_border=para['exclude_border'])
            pts[:, 2] *= np.sqrt(2)
            sid.extend([i] * len(pts))
            fid.extend(range(1, len(pts) + 1))
            data.append(pts)

            layer = {
                'type': 'layer',
                'body': [{
                    'type': 'circles',
                    'body': pts[:, [1, 0, 2]]
                }]
            }
            if para['showid']:
                layer['body'].append({
                    'type':
                    'texts',
                    'body': [(x, y, 'id=%d' % i)
                             for (x, y), i in zip(pts[:, 1::-1], fid)]
                })
            mark['body'][i] = layer

        ips.mark = GeometryMark(mark)
        df = pd.DataFrame(np.vstack(data) * ips.unit[0],
                          columns=['X', 'Y', 'R'])
        df.insert(0, 'FID', fid)
        if para['slice']: df.insert(o, 'SliceID', sid)
        IPy.show_table(df, ips.title + '-dohblob')
示例#13
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']), '人脸参数')
示例#14
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')
示例#15
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 = [], {'type': 'layers', 'body': {}}
        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:]

            layer = {'type': 'layer', 'body': []}
            texts = [(i.centroid[::-1]) + ('id=%d' % n, )
                     for i, n in zip(ls, range(len(ls)))]
            layer['body'].append({'type': 'texts', 'body': texts})
            if para['cov']:
                ellips = [
                    i.centroid[::-1] + (i.major_axis_length / 2,
                                        i.minor_axis_length / 2, i.orientation)
                    for i in ls
                ]
                layer['body'].append({'type': 'ellipses', 'body': ellips})
            mark['body'][i] = layer

            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 = GeometryMark(mark)
        IPy.show_table(pd.DataFrame(data, columns=titles),
                       ips.title + '-region')
示例#16
0
 def preview(self, ips, para):
     grid, lines, row, col = self.grid(ips, para)
     lines = lines.reshape((-1, 2, 2))
     polygons = {'type': 'lines', 'body': lines}
     ips.mark = GeometryMark(polygons)
     ips.update()