Exemple #1
0
    def set_data(self, x, y, A):
        """
        Set the grid for the pixel centers, and the pixel values.

          *x* and *y* are 1-D ndarrays of lengths N and M, respectively,
             specifying pixel centers

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.
        """
        x = np.asarray(x, np.float32)
        y = np.asarray(y, np.float32)
        A = cbook.safe_masked_invalid(A)
        if len(x.shape) != 1 or len(y.shape) != 1\
           or A.shape[0:2] != (y.shape[0], x.shape[0]):
            raise TypeError("Axes don't match array shape")
        if len(A.shape) not in [2, 3]:
            raise TypeError("Can only plot 2D or 3D data")
        if len(A.shape) == 3 and A.shape[2] not in [1, 3, 4]:
            raise TypeError("3D arrays must have three (RGB) "
                            "or four (RGBA) color components")
        if len(A.shape) == 3 and A.shape[2] == 1:
            A.shape = A.shape[0:2]
        self._A = A
        self._Ax = x
        self._Ay = y
        self._imcache = None

        # I am adding this in accor with _AxesImageBase.set_data --
        # examples/pylab_examples/image_nonuniform.py was breaking on
        # the call to _get_unsampled_image when the oldxslice attr was
        # accessed - JDH 3/3/2010
        self._oldxslice = None
        self._oldyslice = None
Exemple #2
0
    def set_data(self, A):
        """
        Set the image array

        ACCEPTS: numpy/PIL Image A
        """
        # check if data is PIL Image without importing Image
        if hasattr(A, 'getpixel'):
            self._A = pil_to_array(A)
        else:
            self._A = cbook.safe_masked_invalid(A)

        if (self._A.dtype != np.uint8 and
                not np.can_cast(self._A.dtype, np.float)):
            raise TypeError("Image data can not convert to float")

        if (self._A.ndim not in (2, 3) or
                (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
            raise TypeError("Invalid dimensions for image data")

        self._imcache = None
        self._rgbacache = None
        self._oldxslice = None
        self._oldyslice = None
        self.stale = True
Exemple #3
0
    def set_data(self, x, y, A):
        A = cbook.safe_masked_invalid(A)
        if x is None:
            x = np.arange(0, A.shape[1]+1, dtype=np.float64)
        else:
            x = np.asarray(x, np.float64).ravel()
        if y is None:
            y = np.arange(0, A.shape[0]+1, dtype=np.float64)
        else:
            y = np.asarray(y, np.float64).ravel()

        if A.shape[:2] != (y.size-1, x.size-1):
            print A.shape
            print y.size
            print x.size
            raise ValueError("Axes don't match array shape")
        if A.ndim not in [2, 3]:
            raise ValueError("A must be 2D or 3D")
        if A.ndim == 3 and A.shape[2] == 1:
            A.shape = A.shape[:2]
        self.is_grayscale = False
        if A.ndim == 3:
            if A.shape[2] in [3, 4]:
                if (A[:,:,0] == A[:,:,1]).all() and (A[:,:,0] == A[:,:,2]).all():
                    self.is_grayscale = True
            else:
                raise ValueError("3D arrays must have RGB or RGBA as last dim")
        self._A = A
        self._Ax = x
        self._Ay = y
        self._rgbacache = None
Exemple #4
0
    def _scale_to_res(self):
        """ Change self._A and _extent to render an image whose
        resolution is matched to the eventual rendering."""

        ax = self.axes
        shp = self._full_res.shape
        transform = self._get_transform()
        x0, x1, sx, y0, y1, sy = extract_matched_slices(ax, shp, transform)

        # have we already calculated what we need?
        if (
            self._bounds is not None
            and sx >= self._sx
            and sy >= self._sy
            and x0 >= self._bounds[0]
            and x1 <= self._bounds[1]
            and y0 >= self._bounds[2]
            and y1 <= self._bounds[3]
        ):
            return
        self._A = self._full_res[y0:y1:sy, x0:x1:sx]
        self._A = cbook.safe_masked_invalid(self._A)

        extentLim = extent_to_bbox(x0 - 0.5, x1 - 0.5, y0 - 0.5, y1 - 0.5, self.origin)
        extentLim = transform.inverted().transform_bbox(extentLim)
        extent = bbox_to_extent(extentLim, self.origin)
        self.set_extent(extent)

        self._sx = sx
        self._sy = sy
        self._bounds = (x0, x1, y0, y1)
        self.changed()
Exemple #5
0
    def set_data(self, x, y, A):
        """
        Set the grid for the pixel centers, and the pixel values.

          *x* and *y* are monotonic 1-D ndarrays of lengths N and M,
             respectively, specifying pixel centers

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.
        """
        x = np.array(x, np.float32)
        y = np.array(y, np.float32)
        A = cbook.safe_masked_invalid(A, copy=True)
        if not (x.ndim == y.ndim == 1 and A.shape[0:2] == y.shape + x.shape):
            raise TypeError("Axes don't match array shape")
        if A.ndim not in [2, 3]:
            raise TypeError("Can only plot 2D or 3D data")
        if A.ndim == 3 and A.shape[2] not in [1, 3, 4]:
            raise TypeError("3D arrays must have three (RGB) "
                            "or four (RGBA) color components")
        if A.ndim == 3 and A.shape[2] == 1:
            A.shape = A.shape[0:2]
        self._A = A
        self._Ax = x
        self._Ay = y
        self._imcache = None

        self.stale = True
Exemple #6
0
    def _scale_to_res(self):
        """ Change self._A and _extent to render an image whose
        resolution is matched to the eventual rendering."""

        ax = self.axes
        shp = self._full_res.shape
        x0, x1, sx, y0, y1, sy = extract_matched_slices(ax, shp)
        # have we already calculated what we need?
        if (
            sx >= self._sx
            and sy >= self._sy
            and x0 >= self._bounds[0]
            and x1 <= self._bounds[1]
            and y0 >= self._bounds[2]
            and y1 <= self._bounds[3]
        ):
            return
        self._A = self._full_res[y0:y1:sy, x0:x1:sx]
        self._A = cbook.safe_masked_invalid(self._A)
        if self.origin == "upper":
            self.set_extent([x0 - 0.5, x1 - 0.5, y1 - 0.5, y0 - 0.5])
        else:
            self.set_extent([x0 - 0.5, x1 - 0.5, y0 - 0.5, y1 - 0.5])
        self._sx = sx
        self._sy = sy
        self._bounds = (x0, x1, y0, y1)
        self.changed()
Exemple #7
0
    def set_data(self, x, y, A):
        """
        Set the grid for the pixel centers, and the pixel values.

          *x* and *y* are 1-D ndarrays of lengths N and M, respectively,
             specifying pixel centers

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.
        """
        x = np.asarray(x, np.float32)
        y = np.asarray(y, np.float32)
        A = cbook.safe_masked_invalid(A)
        if len(x.shape) != 1 or len(y.shape) != 1\
           or A.shape[0:2] != (y.shape[0], x.shape[0]):
            raise TypeError("Axes don't match array shape")
        if A.ndim not in [2, 3]:
            raise TypeError("Can only plot 2D or 3D data")
        if A.ndim == 3 and A.shape[2] not in [1, 3, 4]:
            raise TypeError("3D arrays must have three (RGB) "
                            "or four (RGBA) color components")
        if A.ndim == 3 and A.shape[2] == 1:
            A.shape = A.shape[0:2]
        self._A = A
        self._Ax = x
        self._Ay = y
        self._imcache = None

        self.stale = True
Exemple #8
0
    def set_data(self, x, y, A):
        A = cbook.safe_masked_invalid(A)
        if x is None:
            x = np.arange(0, A.shape[1] + 1, dtype=np.float64)
        else:
            x = np.asarray(x, np.float64).ravel()
        if y is None:
            y = np.arange(0, A.shape[0] + 1, dtype=np.float64)
        else:
            y = np.asarray(y, np.float64).ravel()

        if A.shape[:2] != (y.size - 1, x.size - 1):
            print(A.shape)
            print(y.size)
            print(x.size)
            raise ValueError("Axes don't match array shape")
        if A.ndim not in [2, 3]:
            raise ValueError("A must be 2D or 3D")
        if A.ndim == 3 and A.shape[2] == 1:
            A.shape = A.shape[:2]
        self.is_grayscale = False
        if A.ndim == 3:
            if A.shape[2] in [3, 4]:
                if ((A[:, :, 0] == A[:, :, 1]).all()
                        and (A[:, :, 0] == A[:, :, 2]).all()):
                    self.is_grayscale = True
            else:
                raise ValueError("3D arrays must have RGB or RGBA as last dim")
        self._A = A
        self._Ax = x
        self._Ay = y
        self._rgbacache = None
Exemple #9
0
    def set_data(self, x, y, A):
        """
        Set the grid for the pixel centers, and the pixel values.

          *x* and *y* are 1-D ndarrays of lengths N and M, respectively,
             specifying pixel centers

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.
        """
        x = np.asarray(x, np.float32)
        y = np.asarray(y, np.float32)
        A = cbook.safe_masked_invalid(A)
        if len(x.shape) != 1 or len(y.shape) != 1\
           or A.shape[0:2] != (y.shape[0], x.shape[0]):
            raise TypeError("Axes don't match array shape")
        if len(A.shape) not in [2, 3]:
            raise TypeError("Can only plot 2D or 3D data")
        if len(A.shape) == 3 and A.shape[2] not in [1, 3, 4]:
            raise TypeError("3D arrays must have three (RGB) "
                            "or four (RGBA) color components")
        if len(A.shape) == 3 and A.shape[2] == 1:
            A.shape = A.shape[0:2]
        self._A = A
        self._Ax = x
        self._Ay = y
        self._imcache = None

        # I am adding this in accor with _AxesImageBase.set_data --
        # examples/pylab_examples/image_nonuniform.py was breaking on
        # the call to _get_unsampled_image when the oldxslice attr was
        # accessed - JDH 3/3/2010
        self._oldxslice = None
        self._oldyslice = None
Exemple #10
0
    def set_data(self, A):
        """
        Set the image array

        ACCEPTS: numpy/PIL Image A
        """
        # check if data is PIL Image without importing Image
        if hasattr(A, 'getpixel'):
            self._A = pil_to_array(A)
        else:
            self._A = cbook.safe_masked_invalid(A)

        if (self._A.dtype != np.uint8
                and not np.can_cast(self._A.dtype, np.float)):
            raise TypeError("Image data can not convert to float")

        if (self._A.ndim not in (2, 3)
                or (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
            raise TypeError("Invalid dimensions for image data")

        self._imcache = None
        self._rgbacache = None
        self._oldxslice = None
        self._oldyslice = None
        self.stale = True
Exemple #11
0
    def _scale_to_res(self):
        """ Change self._A and _extent to render an image whose
resolution is matched to the eventual rendering."""
        # extent has to be set BEFORE set_data
        if self._origExtent is None:
            if self.origin == "upper":
                self._origExtent = (0, self._full_res.shape[1],
                                    self._full_res.shape[0], 0)
            else:
                self._origExtent = (0, self._full_res.shape[1],
                                    0, self._full_res.shape[0])

        if self.origin == "upper":
            origXMin, origXMax, origYMax, origYMin = self._origExtent[0:4]
        else:
            origXMin, origXMax, origYMin, origYMax = self._origExtent[0:4]
        ax = self.axes
        ext = ax.transAxes.transform([1, 1]) - ax.transAxes.transform([0, 0])
        xlim, ylim = ax.get_xlim(), ax.get_ylim()
        xlim = max(xlim[0], origXMin), min(xlim[1], origXMax)
        if ylim[0] > ylim[1]:
            ylim = max(ylim[1], origYMin), min(ylim[0], origYMax)
        else:
            ylim = max(ylim[0], origYMin), min(ylim[1], origYMax)
        # print("THOSE LIMITS ARE TO BE COMPARED WITH THE EXTENT")
        # print("IN ORDER TO KNOW WHAT IT IS LIMITING THE DISPLAY")
        # print("IF THE AXES OR THE EXTENT")
        dx, dy = xlim[1] - xlim[0], ylim[1] - ylim[0]

        y0 = max(0, ylim[0] - 5)
        y1 = min(self._full_res.shape[0], ylim[1] + 5)
        x0 = max(0, xlim[0] - 5)
        x1 = min(self._full_res.shape[1], xlim[1] + 5)
        y0, y1, x0, x1 = [int(a) for a in [y0, y1, x0, x1]]

        sy = int(max(1, min((y1 - y0) / 5., numpy.ceil(dy / ext[1]))))
        sx = int(max(1, min((x1 - x0) / 5., numpy.ceil(dx / ext[0]))))

        # have we already calculated what we need?
        if (self._sx is not None) and (self._sy is not None):
            if (sx >= self._sx and sy >= self._sy and
                    x0 >= self._bounds[0] and x1 <= self._bounds[1] and
                    y0 >= self._bounds[2] and y1 <= self._bounds[3]):
                return

        self._A = self._full_res[y0:y1:sy, x0:x1:sx]
        self._A = cbook.safe_masked_invalid(self._A)
        x1 = x0 + self._A.shape[1] * sx
        y1 = y0 + self._A.shape[0] * sy

        if self.origin == "upper":
            self.set_extent([x0, x1, y1, y0])
        else:
            self.set_extent([x0, x1, y0, y1])
        self._sx = sx
        self._sy = sy
        self._bounds = (x0, x1, y0, y1)
        self.changed()
Exemple #12
0
    def _scale_to_res(self):
        """ Change self._A and _extent to render an image whose
        resolution is matched to the eventual rendering."""
        # extent has to be set BEFORE set_data
        if self._origExtent is None:
            if self.origin == "upper":
                self._origExtent = (0, self._full_res.shape[1],
                                    self._full_res.shape[0], 0)
            else:
                self._origExtent = (0, self._full_res.shape[1], 0,
                                    self._full_res.shape[0])

        if self.origin == "upper":
            origXMin, origXMax, origYMax, origYMin = self._origExtent[0:4]
        else:
            origXMin, origXMax, origYMin, origYMax = self._origExtent[0:4]
        ax = self.axes
        ext = ax.transAxes.transform([1, 1]) - ax.transAxes.transform([0, 0])
        xlim, ylim = ax.get_xlim(), ax.get_ylim()
        xlim = max(xlim[0], origXMin), min(xlim[1], origXMax)
        if ylim[0] > ylim[1]:
            ylim = max(ylim[1], origYMin), min(ylim[0], origYMax)
        else:
            ylim = max(ylim[0], origYMin), min(ylim[1], origYMax)
        # print("THOSE LIMITS ARE TO BE COMPARED WITH THE EXTENT")
        # print("IN ORDER TO KNOW WHAT IT IS LIMITING THE DISPLAY")
        # print("IF THE AXES OR THE EXTENT")
        dx, dy = xlim[1] - xlim[0], ylim[1] - ylim[0]

        y0 = max(0, ylim[0] - 5)
        y1 = min(self._full_res.shape[0], ylim[1] + 5)
        x0 = max(0, xlim[0] - 5)
        x1 = min(self._full_res.shape[1], xlim[1] + 5)
        y0, y1, x0, x1 = [int(a) for a in [y0, y1, x0, x1]]

        sy = int(max(1, min((y1 - y0) / 5., np.ceil(dy / ext[1]))))
        sx = int(max(1, min((x1 - x0) / 5., np.ceil(dx / ext[0]))))

        # have we already calculated what we need?
        if (self._sx is not None) and (self._sy is not None):
            if (sx >= self._sx and sy >= self._sy and x0 >= self._bounds[0]
                    and x1 <= self._bounds[1] and y0 >= self._bounds[2]
                    and y1 <= self._bounds[3]):
                return

        self._A = self._full_res[y0:y1:sy, x0:x1:sx]
        self._A = cbook.safe_masked_invalid(self._A)
        x1 = x0 + self._A.shape[1] * sx
        y1 = y0 + self._A.shape[0] * sy

        if self.origin == "upper":
            self.set_extent([x0, x1, y1, y0])
        else:
            self.set_extent([x0, x1, y0, y1])
        self._sx = sx
        self._sy = sy
        self._bounds = (x0, x1, y0, y1)
        self.changed()
Exemple #13
0
    def set_data(self, x, y, A):
        """
        Set the grid for the rectangle boundaries, and the data values.

          *x* and *y* are monotonic 1-D ndarrays of lengths N+1 and M+1,
             respectively, specifying rectangle boundaries.  If None,
             they will be created as uniform arrays from 0 through N
             and 0 through M, respectively.

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.

        """
        A = cbook.safe_masked_invalid(A, copy=True)
        if x is None:
            x = np.arange(0, A.shape[1]+1, dtype=np.float64)
        else:
            x = np.array(x, np.float64).ravel()
        if y is None:
            y = np.arange(0, A.shape[0]+1, dtype=np.float64)
        else:
            y = np.array(y, np.float64).ravel()

        if A.shape[:2] != (y.size-1, x.size-1):
            raise ValueError(
                "Axes don't match array shape. Got %s, expected %s." %
                (A.shape[:2], (y.size - 1, x.size - 1)))
        if A.ndim not in [2, 3]:
            raise ValueError("A must be 2D or 3D")
        if A.ndim == 3 and A.shape[2] == 1:
            A.shape = A.shape[:2]
        self.is_grayscale = False
        if A.ndim == 3:
            if A.shape[2] in [3, 4]:
                if ((A[:, :, 0] == A[:, :, 1]).all() and
                        (A[:, :, 0] == A[:, :, 2]).all()):
                    self.is_grayscale = True
            else:
                raise ValueError("3D arrays must have RGB or RGBA as last dim")

        # For efficient cursor readout, ensure x and y are increasing.
        if x[-1] < x[0]:
            x = x[::-1]
            A = A[:, ::-1]
        if y[-1] < y[0]:
            y = y[::-1]
            A = A[::-1]

        self._A = A
        self._Ax = x
        self._Ay = y
        self._rgbacache = None
        self.stale = True
Exemple #14
0
    def set_data(self, x, y, A):
        """
        Set the grid for the rectangle boundaries, and the data values.

          *x* and *y* are monotonic 1-D ndarrays of lengths N+1 and M+1,
             respectively, specifying rectangle boundaries.  If None,
             they will be created as uniform arrays from 0 through N
             and 0 through M, respectively.

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.

        """
        A = cbook.safe_masked_invalid(A, copy=True)
        if x is None:
            x = np.arange(0, A.shape[1]+1, dtype=np.float64)
        else:
            x = np.array(x, np.float64).ravel()
        if y is None:
            y = np.arange(0, A.shape[0]+1, dtype=np.float64)
        else:
            y = np.array(y, np.float64).ravel()

        if A.shape[:2] != (y.size-1, x.size-1):
            raise ValueError(
                "Axes don't match array shape. Got %s, expected %s." %
                (A.shape[:2], (y.size - 1, x.size - 1)))
        if A.ndim not in [2, 3]:
            raise ValueError("A must be 2D or 3D")
        if A.ndim == 3 and A.shape[2] == 1:
            A.shape = A.shape[:2]
        self.is_grayscale = False
        if A.ndim == 3:
            if A.shape[2] in [3, 4]:
                if ((A[:, :, 0] == A[:, :, 1]).all() and
                        (A[:, :, 0] == A[:, :, 2]).all()):
                    self.is_grayscale = True
            else:
                raise ValueError("3D arrays must have RGB or RGBA as last dim")

        # For efficient cursor readout, ensure x and y are increasing.
        if x[-1] < x[0]:
            x = x[::-1]
            A = A[:, ::-1]
        if y[-1] < y[0]:
            y = y[::-1]
            A = A[::-1]

        self._A = A
        self._Ax = x
        self._Ay = y
        self._rgbacache = None
        self.stale = True
Exemple #15
0
    def set_data(self, x, y, A):
        """
        Set the grid for the pixel centers, and the pixel values.

          *x* and *y* are 1-D ndarrays of lengths N and M, respectively,
             specifying pixel centers

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.
        """
        x = np.asarray(x, np.float32)
        y = np.asarray(y, np.float32)
        A = cbook.safe_masked_invalid(A)
        if len(x.shape) != 1 or len(y.shape) != 1\
           or A.shape[0:2] != (y.shape[0], x.shape[0]):
            raise TypeError("Axes don't match array shape")
        if len(A.shape) not in [2, 3]:
            raise TypeError("Can only plot 2D or 3D data")
        if len(A.shape) == 3 and A.shape[2] not in [1, 3, 4]:
            raise TypeError(
                "3D arrays must have three (RGB) or four (RGBA) color components"
            )
        if len(A.shape) == 3 and A.shape[2] == 1:
            A.shape = A.shape[0:2]
        if len(A.shape) == 2:
            if A.dtype != np.uint8:
                A = (self.cmap(self.norm(A)) * 255).astype(np.uint8)
                self.is_grayscale = self.cmap.is_gray()
            else:
                A = np.repeat(A[:, :, np.newaxis], 4, 2)
                A[:, :, 3] = 255
                self.is_grayscale = True
        else:
            if A.dtype != np.uint8:
                A = (255 * A).astype(np.uint8)
            if A.shape[2] == 3:
                B = zeros(tuple(list(A.shape[0:2]) + [4]), np.uint8)
                B[:, :, 0:3] = A
                B[:, :, 3] = 255
                A = B
            self.is_grayscale = False
        self._A = A
        self._Ax = x
        self._Ay = y
        self._imcache = None

        # I am adding this in accor with _AxesImageBase.set_data --
        # examples/pylab_examples/image_nonuniform.py was breaking on
        # the call to _get_unsampled_image when the oldxslice attr was
        # accessed - JDH 3/3/2010
        self._oldxslice = None
        self._oldyslice = None
Exemple #16
0
    def _scale_to_res(self):
        """
        Change self._A and _extent to render an image whose resolution is
        matched to the eventual rendering.
        """

        # Find out how we need to slice the array to make sure we match the
        # resolution of the display. We pass self._world2pixel which matters
        # for cases where the extent has been set.
        x0, x1, sx, y0, y1, sy = extract_matched_slices(
            axes=self.axes,
            shape=self._full_res.shape,
            transform=self._world2pixel)

        # Check whether we've already calculated what we need, and if so just
        # return without doing anything further.
        if (self._bounds is not None and sx >= self._sx and sy >= self._sy
                and x0 >= self._bounds[0] and x1 <= self._bounds[1]
                and y0 >= self._bounds[2] and y1 <= self._bounds[3]):
            return

        # Slice the array using the slices determined previously to optimally
        # match the display
        self._A = self._full_res[y0:y1:sy, x0:x1:sx]
        self._A = cbook.safe_masked_invalid(self._A)

        # We now determine the extent of the subset of the image, by determining
        # it first in pixel space, and converting it to the 'world' coordinates.

        # See https://github.com/matplotlib/matplotlib/issues/8693 for a
        # demonstration of why origin='upper' and extent=None needs to be
        # special-cased.

        if self.origin == 'upper' and self._full_extent is None:
            xmin, xmax, ymin, ymax = x0 - .5, x1 - .5, y1 - .5, y0 - .5
        else:
            xmin, xmax, ymin, ymax = x0 - .5, x1 - .5, y0 - .5, y1 - .5

        xmin, ymin, xmax, ymax = self._pixel2world.transform([(xmin, ymin),
                                                              (xmax, ymax)
                                                              ]).ravel()

        mi.AxesImage.set_extent(self, [xmin, xmax, ymin, ymax])
        # self.set_extent([xmin, xmax, ymin, ymax])

        # Finally, we cache the current settings to avoid re-computing similar
        # arrays in future.
        self._sx = sx
        self._sy = sy
        self._bounds = (x0, x1, y0, y1)

        self.changed()
Exemple #17
0
    def set_data(self, x, y, A):
        """
        Set the grid for the pixel centers, and the pixel values.

          *x* and *y* are 1-D ndarrays of lengths N and M, respectively,
             specifying pixel centers

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.
        """
        x = np.asarray(x,np.float32)
        y = np.asarray(y,np.float32)
        A = cbook.safe_masked_invalid(A)
        if len(x.shape) != 1 or len(y.shape) != 1\
           or A.shape[0:2] != (y.shape[0], x.shape[0]):
            raise TypeError("Axes don't match array shape")
        if len(A.shape) not in [2, 3]:
            raise TypeError("Can only plot 2D or 3D data")
        if len(A.shape) == 3 and A.shape[2] not in [1, 3, 4]:
            raise TypeError("3D arrays must have three (RGB) or four (RGBA) color components")
        if len(A.shape) == 3 and A.shape[2] == 1:
            A.shape = A.shape[0:2]
        if len(A.shape) == 2:
            if A.dtype != np.uint8:
                A = self.to_rgba(A, alpha=self._alpha, bytes=True)
                self.is_grayscale = self.cmap.is_gray()
            else:
                A = np.repeat(A[:,:,np.newaxis], 4, 2)
                A[:,:,3] = 255
                self.is_grayscale = True
        else:
            if A.dtype != np.uint8:
                A = (255*A).astype(np.uint8)
            if A.shape[2] == 3:
                B = zeros(tuple(list(A.shape[0:2]) + [4]), np.uint8)
                B[:,:,0:3] = A
                B[:,:,3] = 255
                A = B
            self.is_grayscale = False
        self._A = A
        self._Ax = x
        self._Ay = y
        self._imcache = None

        # I am adding this in accor with _AxesImageBase.set_data --
        # examples/pylab_examples/image_nonuniform.py was breaking on
        # the call to _get_unsampled_image when the oldxslice attr was
        # accessed - JDH 3/3/2010
        self._oldxslice = None
        self._oldyslice = None
Exemple #18
0
    def _scale_to_res(self):
        """
        Change self._A and _extent to render an image whose resolution is
        matched to the eventual rendering.
        """

        # Find out how we need to slice the array to make sure we match the
        # resolution of the display. We pass self._world2pixel which matters
        # for cases where the extent has been set.
        x0, x1, sx, y0, y1, sy = extract_matched_slices(axes=self.axes,
                                                        shape=self._full_res.shape,
                                                        transform=self._world2pixel)

        # Check whether we've already calculated what we need, and if so just
        # return without doing anything further.
        if (self._bounds is not None and
                sx >= self._sx and sy >= self._sy and
                x0 >= self._bounds[0] and x1 <= self._bounds[1] and
                y0 >= self._bounds[2] and y1 <= self._bounds[3]):
            return

        # Slice the array using the slices determined previously to optimally
        # match the display
        self._A = self._full_res[y0:y1:sy, x0:x1:sx]
        self._A = cbook.safe_masked_invalid(self._A)

        # We now determine the extent of the subset of the image, by determining
        # it first in pixel space, and converting it to the 'world' coordinates.

        # See https://github.com/matplotlib/matplotlib/issues/8693 for a
        # demonstration of why origin='upper' and extent=None needs to be
        # special-cased.

        if self.origin == 'upper' and self._full_extent is None:
            xmin, xmax, ymin, ymax = x0 - .5, x1 - .5, y1 - .5, y0 - .5
        else:
            xmin, xmax, ymin, ymax = x0 - .5, x1 - .5, y0 - .5, y1 - .5

        xmin, ymin, xmax, ymax = self._pixel2world.transform([(xmin, ymin), (xmax, ymax)]).ravel()

        mi.AxesImage.set_extent(self, [xmin, xmax, ymin, ymax])
        # self.set_extent([xmin, xmax, ymin, ymax])

        # Finally, we cache the current settings to avoid re-computing similar
        # arrays in future.
        self._sx = sx
        self._sy = sy
        self._bounds = (x0, x1, y0, y1)

        self.changed()
Exemple #19
0
def hexplot2(m, n, step, C, **kwargs):
    assert len(C) == m // 2 * (2 * n - 1) + m % 2 * n

    x, y = np.meshgrid(
        np.arange(-1, 2 * n) * step / 2,
        np.arange(-.5, m) * step / 2 * np.sqrt(3))

    s = step / 12 * np.sqrt(3)
    y[::2, ::2] += s
    y[::2, 1::2] -= s
    y[1::2, ::2] -= s
    y[1::2, 1::2] += s

    s = m // 2 * (2 * n - 1)
    end = C[s:]
    C = C[:s].reshape(m // 2, 2 * n - 1)
    even = C[:, :n]
    odd = C[:, n:]

    c = np.zeros((m, 2 * n))
    if m % 2:
        c[:-1:2, ::2] = c[:-1:2, 1::2] = even
        c[-1, ::2] = c[-1, 1::2] = end
    else:
        c[::2, ::2] = c[::2, 1::2] = even

    c[1::2, 0] = c[1::2, -1] = np.nan
    c[1::2, 1:-1:2] = c[1::2, 2:-1:2] = odd

    pos = np.column_stack([x.ravel(), y.ravel()])

    corners = [pos.min(axis=(0)), pos.max(axis=(0))]

    #kwargs.setdefault('shading', 'flat')
    kwargs.setdefault('edgecolors', 'none')
    kwargs.setdefault('antialiased', False)
    kwargs.setdefault('linewidths', 0)

    from matplotlib.collections import QuadMesh
    from matplotlib.cbook import safe_masked_invalid  # needed !
    return add_collection(QuadMesh,
                          2 * n,
                          m,
                          pos,
                          C=safe_masked_invalid(c).ravel(),
                          corners=corners,
                          **kwargs)
Exemple #20
0
    def set_data(self, A):
        """
        Set the image array

        ACCEPTS: numpy/PIL Image A
        """
        self._full_res = A
        self._A = cbook.safe_masked_invalid(A)

        if self._A.dtype != np.uint8 and not np.can_cast(self._A.dtype,
                                                         float):
            raise TypeError("Image data can not convert to float")

        if self._A.ndim not in (2, 3) or (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4)):
            raise TypeError("Invalid dimensions for image data")

        self.invalidate_cache()
Exemple #21
0
    def set_array(self, A):
        """
        Set the image array from array-like *A*.

        Parameters
        ----------
        A : array-like or None
        """
        if A is None:
            self._A = None
            return

        A = cbook.safe_masked_invalid(A, copy=True)
        if not np.can_cast(A.dtype, float, "same_kind"):
            raise TypeError(f"Image data of dtype {A.dtype} cannot be "
                            "converted to float")

        self._A = A
Exemple #22
0
    def get_array_clipped_to_bounds(self):
        # Get the extents of the axes and transform to pixel coordinates
        xlim, ylim = self.axes.get_xlim(), self.axes.get_ylim()
        transform=self._world2pixel
        ind0 = transform.transform([min(xlim), min(ylim)])
        ind1 = transform.transform([max(xlim), max(ylim)])

        # Add 0.5 to get the edge of the pixel. Also add 1 to the max values which need to be one past the end
        # for when we slice.
        y0 = max(int(np.floor(ind0[1] + 0.5)), 0)
        y1 = max(int(np.floor(ind1[1] + 0.5)) + 1, 0)
        x0 = max(int(np.floor(ind0[0] + 0.5)), 0)
        x1 = max(int(np.floor(ind1[0] + 0.5)) + 1, 0)

        # Clip the data to the extents
        data = self._full_res[y0:y1, x0:x1]
        data = cbook.safe_masked_invalid(data)
        return data
Exemple #23
0
    def set_data(self, x, y, A):
        """
        Set the grid for the pixel centers, and the pixel values.

          *x* and *y* are 1-D ndarrays of lengths N and M, respectively,
             specifying pixel centers

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.
        """
        x = np.asarray(x,np.float32)
        y = np.asarray(y,np.float32)
        A = cbook.safe_masked_invalid(A)
        if len(x.shape) != 1 or len(y.shape) != 1\
           or A.shape[0:2] != (y.shape[0], x.shape[0]):
            raise TypeError("Axes don't match array shape")
        if len(A.shape) not in [2, 3]:
            raise TypeError("Can only plot 2D or 3D data")
        if len(A.shape) == 3 and A.shape[2] not in [1, 3, 4]:
            raise TypeError("3D arrays must have three (RGB) or four (RGBA) color components")
        if len(A.shape) == 3 and A.shape[2] == 1:
            A.shape = A.shape[0:2]
        if len(A.shape) == 2:
            if A.dtype != np.uint8:
                A = (self.cmap(self.norm(A))*255).astype(np.uint8)
                self.is_grayscale = self.cmap.is_gray()
            else:
                A = np.repeat(A[:,:,np.newaxis], 4, 2)
                A[:,:,3] = 255
                self.is_grayscale = True
        else:
            if A.dtype != np.uint8:
                A = (255*A).astype(np.uint8)
            if A.shape[2] == 3:
                B = zeros(tuple(list(A.shape[0:2]) + [4]), np.uint8)
                B[:,:,0:3] = A
                B[:,:,3] = 255
                A = B
            self.is_grayscale = False
        self._A = A
        self._Ax = x
        self._Ay = y
        self._imcache = None
Exemple #24
0
    def visualize(self):
        data = self.data
        min_ = np.min(data)
        max_ = np.max(data)
        print('min, nax', min_, max_)
        images = interp1d([min_, max_], [0., 1.])(data)
        shape = (self.h, self.w) if self.c == 1 else (self.h, self.w, self.c)
        print('shape', shape)
        for i, ax_img in enumerate(self.all_ax_img):
            if len(images.shape) != 1: image = images[i].reshape(shape)
            else: image = images.reshape(shape)

            ax_img._A = cbook.safe_masked_invalid(image, copy=False)

        if self.plot_only:
            plt.pause(0.00000000000000001)
            self.fig.canvas.draw()
            self.fig.canvas.flush_events()

        self.fig.savefig(f'{self.filename}.pdf')
Exemple #25
0
    def _scale_to_res(self):
        """ Change self._A and _extent to render an image whose
        resolution is matched to the eventual rendering."""

        ax = self.axes
        shp = self._full_res.shape
        x0, x1, sx, y0, y1, sy = extract_matched_slices(ax, shp)
        # have we already calculated what we need?
        if sx >= self._sx and sy >= self._sy and \
            x0 >= self._bounds[0] and x1 <= self._bounds[1] and \
                y0 >= self._bounds[2] and y1 <= self._bounds[3]:
            return
        self._A = self._full_res[y0:y1:sy, x0:x1:sx]
        self._A = cbook.safe_masked_invalid(self._A)
        if self.origin == 'upper':
            self.set_extent([x0 - .5, x1 - .5, y1 - .5, y0 - .5])
        else:
            self.set_extent([x0 - .5, x1 - .5, y0 - .5, y1 - .5])
        self._sx = sx
        self._sy = sy
        self._bounds = (x0, x1, y0, y1)
        self.changed()
Exemple #26
0
    def set_array(self, A):
        """
        Set the value array from array-like *A*.

        Parameters
        ----------
        A : array-like or None
            The values that are mapped to colors.

            The base class `.ScalarMappable` does not make any assumptions on
            the dimensionality and shape of the value array *A*.
        """
        if A is None:
            self._A = None
            return

        A = cbook.safe_masked_invalid(A, copy=True)
        if not np.can_cast(A.dtype, float, "same_kind"):
            raise TypeError(f"Image data of dtype {A.dtype} cannot be "
                            "converted to float")

        self._A = A
Exemple #27
0
    def get_array_clipped_to_bounds(self) -> np.ndarray:
        """
        Get the color data for the subset of the array within the axes limits. This is necessary for autoscaling of the
        clim to work when plotting MDHisto workspaces in nonorthognonal view in sliceviewer
        :return: masked array of color data clipped to axes limits (will be empty container if no data within limits)
        """
        xlim, ylim = self.axes.get_xlim(), self.axes.get_ylim()  # limits for data transformed into orthogonal basis

        # reshape color data array
        nedges_y, nedges_x = self._mesh._coordinates.shape[0:2]
        arr = self._mesh.get_array().reshape((nedges_y - 1, nedges_x - 1))

        # y-axis is parallel to axes box so can determine ylimit as so
        ydata = self._mesh._coordinates[:-1, 0, 1]  # bin edges - excl. last edge as pcolor puts bin center bottom left
        dy = ydata[1] - ydata[0]  # ybin width
        iy_rows = np.logical_and(ydata >= ylim[0] - dy, ydata < ylim[1])  # include bins to bottom left of axes limits
        if any(iy_rows):
            # unlike ydata need whole 2D array for xdata as x-extent of data (in orthogonal basis) depends on y value
            xdata = self._mesh._coordinates[:-1, :-1, 0][iy_rows, :]
            dx = xdata[0][1] - xdata[0][0]  # xbin width
            xmask = np.logical_and(xdata >= xlim[0] - dx, xdata < xlim[1])
            return safe_masked_invalid(arr[iy_rows, :][xmask])
        else:
            return np.array([], dtype=float)
Exemple #28
0
 def set_data(self, A):
     """Set the image array."""
     cm.ScalarMappable.set_array(self,
                                 cbook.safe_masked_invalid(A, copy=True))
     self.stale = True
Exemple #29
0
    def set_data(self, A):
        """
        Set the image array

        """
        cm.ScalarMappable.set_array(self, cbook.safe_masked_invalid(A))
Exemple #30
0
 def set_data(self, A):
     """Set the image array."""
     cm.ScalarMappable.set_array(self,
                                 cbook.safe_masked_invalid(A, copy=True))
     self.stale = True