Exemplo n.º 1
0
    def get_gate_patch(self):
        '''Returns a matplotlib patch to be drawn on the canvas whose dimensions
        have been computed from the current gate.
        '''
        x_min, x_max = self.subplot.get_xlim()
        x_range = x_max - x_min
        y_min, y_max = self.subplot.get_ylim()
        y_range = y_max - y_min
        
        for subgate in self.gate.get_subgates():       
            col = subgate.get_column()
            if col == self.x_column:
                x_min = subgate.get_min()
                x_range = subgate.get_max() - subgate.get_min()
            if col == self.y_column:
                y_min = subgate.get_min()
                y_range = subgate.get_max() - subgate.get_min()

        if self.patch not in self.subplot.patches:
            rect = Rectangle((x_min, y_min), x_range, y_range, animated=True)
            rect.set_fill(False)
            rect.set_linestyle('dashed')
            self.patch = self.subplot.add_patch(rect)
        else:
            self.patch.set_bounds(x_min, y_min, x_range, y_range)
        return self.patch
Exemplo n.º 2
0
class ImageAreaSelect(object):
    def __init__(self, img, out, fit=False):
        self.img = img
        self.out = out
        self.fit = fit

        plt.figure()
        plt.title("Testing Image")
        plt.xlabel(r'M')
        plt.ylabel(r'N')
        self.ax = plt.gca()
        self.rect = Rectangle((0, 0), 1, 1, antialiased=True, color='b',
                              linestyle='solid', lw=1.2)
        self.rect.set_fill(False)
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None

        self.draw_rect = False

        self.ax.add_patch(self.rect)
        self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
        self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)

        plt.imshow(self.img, cmap="gray")
        plt.show()

    def on_press(self, event):
        self.draw_rect = True
        self.x0 = int(event.xdata)
        self.y0 = int(event.ydata)

    def on_motion(self, event):
        if self.draw_rect:
            if self.x1 != int(event.xdata) or self.y1 != int(event.ydata):
                self.x1 = int(event.xdata)
                self.y1 = int(event.ydata)
                self.rect.set_width(self.x1 - self.x0)
                self.rect.set_height(self.y1 - self.y0)
                self.rect.set_xy((self.x0, self.y0))
                self.ax.figure.canvas.draw()

    def on_release(self, event):
        self.draw_rect = False
        self.x1 = int(event.xdata)
        self.y1 = int(event.ydata)
        self.calc()

    def calc(self):
        if self.x1 == self.x0 or self.y1 == self.y0:
            return
        print('crop(x,y):', self.x0, self.x1, self.y0, self.y1)
        img = self.img[self.y0:self.y1, self.x0:self.x1]
        mtf_from_img(img, self.out + "/" + str(self.x0) + "_" + str(self.x1) + "_" + str(self.y0) + "_" + str(self.y1), True)
Exemplo n.º 3
0
class MainApp(App):
    def build(self):
        """
        some initialization
        Args:
            rect: a dummy rectangle, whose width and height will be reset trigger by user event
            x0, y0: mouse click location
            x1, y1: mouse release location
            canvas: FigureCanvasKivyAgg object. Note that I'm using this back end right now 
            as the FigureCanvas backend has bug with plt.show()
            selectors: store user-drawn rectangle data
            offsetx: translation of origin on x direction
            offsety: translation of origin on y direction
        """
        self.selectors = []
        img = mpimg.imread(sys.argv[1])
        self.fig, self.ax = plt.subplots(1)
        plt.imshow(img)
        width, height = self.fig.canvas.get_width_height()
        pxorigin = self.ax.transData.transform([(0, 0)])
        self.offsetx = pxorigin[0][0]
        self.offsety = height - pxorigin[0][1]
        print('offsetx, offsety', self.offsetx, self.offsety)
        self.rect = Rectangle((0, 0), 1, 1)
        self.rect.set_fill(False)
        self.rect.set_edgecolor('b')
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.canvas = FigureCanvasKivyAgg(
            plt.gcf())  # get the current reference of plt
        box = BoxLayout()
        self.ax.add_patch(self.rect)  # attach our rectangle to axis
        self.canvas.mpl_connect("button_press_event", self.on_press)
        self.canvas.mpl_connect("button_release_event", self.on_release)
        box.add_widget(self.canvas)
        return box

    def on_press(self, event):
        """
        record user click location
        """
        self.x0 = event.xdata
        self.y0 = event.ydata
        print('x0, y0', self.x0, self.y0)

    def on_release(self, event):
        """
        record user mouse release location
        """
        self.x1 = event.xdata
        self.y1 = event.ydata
        self.rect.set_width(self.x1 - self.x0)
        self.rect.set_height(self.y1 - self.y0)
        self.rect.set_xy((self.x0, self.y0))
        xy_pixels = self.ax.transData.transform(
            np.vstack([self.x0, self.y0]).T)
        px, py = xy_pixels.T
        width, height = self.fig.canvas.get_width_height()
        # transform from origin on lower left to orgin on upper right
        py = height - py
        # account for translation factor
        px -= self.offsetx
        py -= self.offsety
        self.selectors.append(
            [px, py, abs(self.x1 - self.x0),
             abs(self.y1 - self.y0)])
        print('your rectangle', px, py, abs(self.x1 - self.x0),
              abs(self.y1 - self.y0))
        self.canvas.draw()
Exemplo n.º 4
0
class IMaGE(object):
    def __init__(self, fit=False):
        self.ax = plt.gca()
        self.rect = Rectangle((0, 0),
                              1,
                              1,
                              antialiased=True,
                              color='b',
                              linestyle='solid',
                              lw=1.2)
        self.rect.set_fill(False)
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.fit = fit

        self.key = False
        self.count = 0

        self.ax.add_patch(self.rect)
        self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.ax.figure.canvas.mpl_connect('motion_notify_event',
                                          self.on_motion)

    def on_press(self, event):
        self.count += 1
        self.key = True if self.key % 2 == 0 else False

        if self.key % 2 == 0:
            self.x = range(int(self.x0), int(self.x1))
            self.cut(im, x0=self.x0, y0=self.y0, x1=self.x1, y1=self.y1)
            self.ESF()
            self.LSF()
            self.MTF()

        self.x0 = event.xdata
        self.y0 = event.ydata

    def on_motion(self, event):
        if self.key:
            self.x1 = event.xdata
            self.y1 = event.ydata
            self.rect.set_width(self.x1 - self.x0)
            self.rect.set_height(self.y1 - self.y0)
            self.rect.set_xy((self.x0, self.y0))
            self.ax.figure.canvas.draw()

    def cut(self, image, **args):
        for i in args.keys():
            print "{} : {}".format(i, args[i])

        M = image[int(args["y0"]):int(args["y1"]),
                  int(args["x0"]):int(args["x1"])]
        self.M_out = 0.299 * M[:, :, 0] + 0.589 * M[:, :, 1] + 0.114 * M[:, :,
                                                                         2]

        # plt.figure()
        # plt.title("operator box-area")
        # plt.imshow(self.M_out)
        # name = "box_selection_{}.png".format(self.count)
        # imag = Image.fromarray(np.asarray(self.M_out),mode = "RGB")
        # imag.save("prueba.png")
        # plt.show()

    def ESF(self):
        """
        Edge Spread Function calculation
        """

        self.X = self.M_out[100, :]
        mu = np.sum(self.X) / self.X.shape[0]
        tmp = (self.X[:] - mu)**2
        sigma = np.sqrt(np.sum(tmp) / self.X.shape[0])
        self.edge_function = (self.X[:] - mu) / sigma

        self.edge_function = self.edge_function[::3]
        x = range(0, self.edge_function.shape[0])

        plt.figure()
        plt.title(r'ESF')
        plt.plot(x, self.edge_function, '-ob')
        plt.show()

    def LSF(self):
        """
        Line Spread Function calculation
        """
        self.lsf = self.edge_function[:-2] - self.edge_function[2:]
        x = range(0, self.lsf.shape[0])

        # plt.figure()
        # plt.title("LSF")
        # plt.xlabel(r'pixel') ; plt.ylabel('intensidad')
        # plt.plot(x,self.lsf,'-or')
        # plt.show()

    def MTF(self):
        """
        Modulation Transfer Function calculation
        """
        self.mtf = abs(np.fft.fft(self.lsf))
        self.mtf = self.mtf[:] / np.max(self.mtf)
        self.mtf = self.mtf[:len(self.mtf) // 2]
        ix = np.arange(self.mtf.shape[0]) / (self.mtf.shape[0])
        mtf_poly = np.polyfit(ix, self.mtf, 6)
        poly = np.poly1d(mtf_poly)

        plt.figure()
        plt.title("MTF")
        plt.xlabel(r'Frecuency $[cycles/pixel]$')
        plt.ylabel('mtf')
        p, = plt.plot(ix, self.mtf, '-or')
        ll, = plt.plot(ix, poly(ix))
        plt.legend([p, ll], ["MTF values", "polynomial fit"])
        plt.grid()
        plt.show()
Exemplo n.º 5
0
    def draw_chiprep2(dm, cx, axi=0, fsel=None, in_image_bit=False, axi_color=0,
                      bbox_bit=None, 
                      ell_alpha=None,
                      ell_bit=None,
                      xy_bit=None,
                      color=None,
                      qcm=None,
                      **kwargs):
        '''
        Draws a chip representation over an already drawn chip
        cx           - the chiprep to draw. Managed by the chip manager
        axi          - the axis index to draw it in
        #TODO: in_image_bit becomes data_coordinates
        in_image_bit - are the data coordinates image or rotated chip? 
                       raw the chip by itself or in its original image
        axi_color    - use the color associated with axis index 
                       (used for ploting queries)
        ---
        Others are preference overloads
        bbox_bit - 
        ell_alpha
        ell_bit 
        xy_bit
        ell_color
        '''
        # Allows display of cross database queries
        cm = dm.hs.cm if qcm is None else qcm
        # Grab Preferences
        xy_bit  = dm.draw_prefs.points_bit    if xy_bit    is None else xy_bit
        ell_bit = dm.draw_prefs.ellipse_bit   if ell_bit   is None else ell_bit
        bbox_bit  = dm.draw_prefs.bbox_bit      if bbox_bit  is None else bbox_bit
        ell_alpha = dm.draw_prefs.ellipse_alpha if ell_alpha is None else ell_alpha 

        # Make sure alpha in range [0,1]
        if ell_alpha > 1: ell_alpha = 1.0
        if ell_alpha < 0: ell_alpha = 0.0

        # Get color from colormap or overloaded parameter
        if color is None:
            color   = plt.get_cmap('hsv')(float(axi_color)/len(dm.ax_list))[0:3]
            if axi_color == 0: 
                color = [color[0], color[1]+.5, color[2]]
        
        # Axis We are drawing to.
        ax     = dm.ax_list[axi]
        T_data = ax.transData # data coordinates -> display coordinates
        # Data coordinates are chip coords

        if xy_bit or ell_bit or fsel != None:
            T_fpts = T_data if not in_image_bit else\
                    Affine2D(cm.cx2_T_chip2img(cx) ) + T_data
            fpts = cm.get_fpts(cx)
            if fsel is None: fsel = range(len(fpts))
            # ---DEVHACK---
            # Randomly sample the keypoints. (Except be sneaky)
            elif fsel == 'rand': 
                # Get Relative Position
                minxy = fpts.min(0)[0:2]
                maxxy = fpts.max(0)[0:2] 
                rel_pos = (fpts[:,0]-minxy[0])/(maxxy[0]-minxy[0])
                to_zero = 1 - np.abs(rel_pos - .5)/.5
                pdf = (to_zero / to_zero.sum())
                # Transform Relative Position to Probabilities
                # making it more likely to pick a centerpoint
                fsel = np.random.choice(xrange(len(fpts)), size=88, replace=False, p=pdf)
            # ---/DEVHACK---
            # Plot ellipses
            if ell_bit and len(fpts) > 0 and len(fsel) > 0: 
                ells = dm._get_fpt_ell_collection(fpts[fsel,:],
                                                  T_fpts,
                                                  ell_alpha,
                                                  color)
                ax.add_collection(ells)
            # Plot xy points
            if xy_bit and len(fpts) > 0 and len(fsel) > 0: 
                ax.plot(fpts[fsel,0], fpts[fsel,1], 'o',\
                        markeredgecolor=color,\
                        markerfacecolor=color,\
                        transform=T_fpts,\
                        markersize=2)
        # === 
        if bbox_bit:
            # Draw Bounding Rectangle in Image Coords
            [rx,ry,rw,rh] = cm.cx2_roi[cx]
            rxy = (rx,ry)
            # Convert to Chip Coords if needbe
            T_bbox = T_data if in_image_bit else\
                Affine2D( np.linalg.inv(cm.cx2_T_chip2img(cx)) ) + T_data
            bbox = Rectangle(rxy,rw,rh,transform=T_bbox) 
            # Visual Properties
            bbox.set_fill(False)
            bbox.set_edgecolor(color)
            ax.add_patch(bbox)

            # Draw Text Annotation
            cid   = cm.cx2_cid[cx]
            name  = cm.cx2_name(cx)
            # Lower the value to .2 for the background color and set alpha=.7 
            rgb_textFG = [1,1,1]
            hsv_textBG = colorsys.rgb_to_hsv(*color)[0:2]+(.2,)
            rgb_textBG = colorsys.hsv_to_rgb(*hsv_textBG)+(.7,)
            # Draw Orientation Backwards
            degrees = 0 if not in_image_bit else -cm.cx2_theta[cx]*180/np.pi
            txy = (0,rh) if not in_image_bit else (rx, ry+rh)

            chip_text =  'name='+name+'\n'+'cid='+str(cid)
            ax.text(txy[0]+1, txy[1]+1, chip_text,
                    horizontalalignment ='left',
                    verticalalignment   ='top',
                    transform           =T_data,
                    rotation            =degrees,
                    color               =rgb_textFG,
                    backgroundcolor     =rgb_textBG)
        return fsel
Exemplo n.º 6
0
class IMaGE(object):
    def __init__(self,fit = False):
        self.ax = plt.gca()
        self.rect = Rectangle((0,0), 1, 1,antialiased = True,color = 'b',
							linestyle = 'solid', lw = 1.2)
        self.rect.set_fill(False)
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.fit = fit

        self.key = False
        self.count = 0

        self.ax.add_patch(self.rect)
        self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)

    def on_press(self, event):
        self.count += 1
        self.key = True if self.key % 2 == 0 else False

        if self.key % 2 == 0:
            self.x = range(int(self.x0),int(self.x1))
            self.cut(im,x0 = self.x0,y0 = self.y0,x1 = self.x1,y1 = self.y1)
            self.ESF()
            self.LSF()
            self.MTF()

        self.x0 = event.xdata
        self.y0 = event.ydata

    def on_motion(self,event):
        if self.key:
            self.x1 = event.xdata
            self.y1 = event.ydata
            self.rect.set_width(self.x1 - self.x0)
            self.rect.set_height(self.y1 - self.y0)
            self.rect.set_xy((self.x0, self.y0))
            self.ax.figure.canvas.draw()

    def cut(self,image,**args):
        for i in args.keys():
            print "{} : {}".format(i,args[i])

        M = image[int(args["y0"]):int(args["y1"]),int(args["x0"]):int(args["x1"])]
        self.M_out = 0.299*M[:,:,0] + 0.589*M[:,:,1]+0.114*M[:,:,2]
        
        # plt.figure()
        # plt.title("operator box-area")
        # plt.imshow(self.M_out)
        # name = "box_selection_{}.png".format(self.count)
        # imag = Image.fromarray(np.asarray(self.M_out),mode = "RGB")
        # imag.save("prueba.png")
        # plt.show()

    def ESF(self):
        """
        Edge Spread Function calculation
        """

        self.X = self.M_out[100,:]
        mu = np.sum(self.X)/self.X.shape[0]
        tmp = (self.X[:] - mu)**2
        sigma = np.sqrt(np.sum(tmp)/self.X.shape[0])
        self.edge_function = (self.X[:] - mu)/sigma
        
        self.edge_function = self.edge_function[::3]
        x = range(0,self.edge_function.shape[0])

        plt.figure()
        plt.title(r'ESF')
        plt.plot(x,self.edge_function,'-ob')
        plt.show()

    def LSF(self):
        """
        Line Spread Function calculation
        """
        self.lsf = self.edge_function[:-2] - self.edge_function[2:]
        x = range(0,self.lsf.shape[0])
        
        # plt.figure()
        # plt.title("LSF")
        # plt.xlabel(r'pixel') ; plt.ylabel('intensidad')
        # plt.plot(x,self.lsf,'-or')
        # plt.show()

    def MTF(self):
        """
        Modulation Transfer Function calculation
        """
        self.mtf = abs(np.fft.fft(self.lsf))
        self.mtf = self.mtf[:]/np.max(self.mtf)
        self.mtf = self.mtf[:len(self.mtf)//2]
        ix = np.arange(self.mtf.shape[0]) / (self.mtf.shape[0])
        mtf_poly =  np.polyfit(ix, self.mtf, 6)
        poly = np.poly1d(mtf_poly)
        
        plt.figure()
        plt.title("MTF")
        plt.xlabel(r'Frecuency $[cycles/pixel]$') ; plt.ylabel('mtf')
        p, = plt.plot(ix,self.mtf,'-or')
        ll, = plt.plot(ix,poly(ix))
        plt.legend([p,ll],["MTF values","polynomial fit"])
        plt.grid()
        plt.show()
Exemplo n.º 7
0
    def draw_chiprep2(
        dm,
        cx,
        axi=0,
        fsel=None,
        in_image_bit=False,
        axi_color=0,
        bbox_bit=None,
        ell_alpha=None,
        ell_bit=None,
        xy_bit=None,
        color=None,
        qcm=None,
        **kwargs
    ):
        """
        Draws a chip representation over an already drawn chip
        cx           - the chiprep to draw. Managed by the chip manager
        axi          - the axis index to draw it in
        #TODO: in_image_bit becomes data_coordinates
        in_image_bit - are the data coordinates image or rotated chip? 
                       raw the chip by itself or in its original image
        axi_color    - use the color associated with axis index 
                       (used for ploting queries)
        ---
        Others are preference overloads
        bbox_bit - 
        ell_alpha
        ell_bit 
        xy_bit
        ell_color
        """
        # Allows display of cross database queries
        cm = dm.hs.cm if qcm is None else qcm
        # Grab Preferences
        xy_bit = dm.draw_prefs.points_bit if xy_bit is None else xy_bit
        ell_bit = dm.draw_prefs.ellipse_bit if ell_bit is None else ell_bit
        bbox_bit = dm.draw_prefs.bbox_bit if bbox_bit is None else bbox_bit
        ell_alpha = dm.draw_prefs.ellipse_alpha if ell_alpha is None else ell_alpha

        # Make sure alpha in range [0,1]
        if ell_alpha > 1:
            ell_alpha = 1.0
        if ell_alpha < 0:
            ell_alpha = 0.0

        # Get color from colormap or overloaded parameter
        if color is None:
            color = plt.get_cmap("hsv")(float(axi_color) / len(dm.ax_list))[0:3]
            if axi_color == 0:
                color = [color[0], color[1] + 0.5, color[2]]

        # Axis We are drawing to.
        ax = dm.ax_list[axi]
        T_data = ax.transData  # data coordinates -> display coordinates
        # Data coordinates are chip coords

        if xy_bit or ell_bit or fsel != None:
            T_fpts = T_data if not in_image_bit else Affine2D(cm.cx2_T_chip2img(cx)) + T_data
            fpts = cm.get_fpts(cx)
            if fsel is None:
                fsel = range(len(fpts))
            # ---DEVHACK---
            # Randomly sample the keypoints. (Except be sneaky)
            elif fsel == "rand":
                # Get Relative Position
                minxy = fpts.min(0)[0:2]
                maxxy = fpts.max(0)[0:2]
                rel_pos = (fpts[:, 0] - minxy[0]) / (maxxy[0] - minxy[0])
                to_zero = 1 - np.abs(rel_pos - 0.5) / 0.5
                pdf = to_zero / to_zero.sum()
                # Transform Relative Position to Probabilities
                # making it more likely to pick a centerpoint
                fsel = np.random.choice(xrange(len(fpts)), size=88, replace=False, p=pdf)
            # ---/DEVHACK---
            # Plot ellipses
            if ell_bit and len(fpts) > 0 and len(fsel) > 0:
                ells = dm._get_fpt_ell_collection(fpts[fsel, :], T_fpts, ell_alpha, color)
                ax.add_collection(ells)
            # Plot xy points
            if xy_bit and len(fpts) > 0 and len(fsel) > 0:
                ax.plot(
                    fpts[fsel, 0],
                    fpts[fsel, 1],
                    "o",
                    markeredgecolor=color,
                    markerfacecolor=color,
                    transform=T_fpts,
                    markersize=2,
                )
        # ===
        if bbox_bit:
            # Draw Bounding Rectangle in Image Coords
            [rx, ry, rw, rh] = cm.cx2_roi[cx]
            rxy = (rx, ry)
            # Convert to Chip Coords if needbe
            T_bbox = T_data if in_image_bit else Affine2D(np.linalg.inv(cm.cx2_T_chip2img(cx))) + T_data
            bbox = Rectangle(rxy, rw, rh, transform=T_bbox)
            # Visual Properties
            bbox.set_fill(False)
            bbox.set_edgecolor(color)
            ax.add_patch(bbox)

            # Draw Text Annotation
            cid = cm.cx2_cid[cx]
            name = cm.cx2_name(cx)
            # Lower the value to .2 for the background color and set alpha=.7
            rgb_textFG = [1, 1, 1]
            hsv_textBG = colorsys.rgb_to_hsv(*color)[0:2] + (0.2,)
            rgb_textBG = colorsys.hsv_to_rgb(*hsv_textBG) + (0.7,)
            # Draw Orientation Backwards
            degrees = 0 if not in_image_bit else -cm.cx2_theta[cx] * 180 / np.pi
            txy = (0, rh) if not in_image_bit else (rx, ry + rh)

            chip_text = "name=" + name + "\n" + "cid=" + str(cid)
            ax.text(
                txy[0] + 1,
                txy[1] + 1,
                chip_text,
                horizontalalignment="left",
                verticalalignment="top",
                transform=T_data,
                rotation=degrees,
                color=rgb_textFG,
                backgroundcolor=rgb_textBG,
            )
        return fsel