Beispiel #1
0
def as_vtkimagedata(x, ndim=None):
    """Convert **x** to a vtkImageData.

    **x** can be any of the following:

    - A vtkImageData.
    - A 2D or 3D numpy array.
    - A file or filename to be read.
    - A Pillow image.

    Some VTK methods require a greyscale image. Using ``ndim=2`` will convert to
    greyscale.

    """
    assert (ndim is None) or (2 <= ndim <= 3)

    # From file.
    if nuts_and_bolts.isinstance_PathLike(x):
        x = str(x)
    if nuts_and_bolts.isinstance_PathLike(x, allow_buffers=True):
        try:
            from matplotlib.pylab import imread
            x = imread(x)
        except Exception:
            x = read(x)

    # From PILLOW.
    if nuts_and_bolts.isinstance_no_import(x, "PIL.Image", "Image"):
        x = np.array(x)

    # From array.
    if isinstance(x, np.ndarray):
        if x.ndim == 2 and ndim == 3:
            x = x[:, :, np.newaxis]
        elif x.ndim == 3 and ndim == 2:
            x = x.mean(-1).astype(x.dtype)
        x = vtkimagedata_from_array(x)

    # From vtk.
    if isinstance(x, vtk.vtkImageData):
        return x

    raise TypeError("Unable to convert type {} to vtkImageData".format(
        type(x)))
Beispiel #2
0
    def __init__(self, array, interpolate=False):
        from vtkplotlib.nuts_and_bolts import isinstance_PathLike
        if isinstance_PathLike(array):
            array = str(array)
        if isinstance(array, str):
            path = array
            from vtkplotlib.image_io import read
            array = read(path)
            if array is NotImplemented:
                try:
                    from matplotlib.pylab import imread
                    array = imread(path)
                except Exception as ex:
                    _future_utils.raise_from(
                        NotImplementedError(
                            "Could not find a suitable VTKImageReader for \"{}\" "
                            "and matplotlib's search failed with the following:"
                        ), ex)

            array = np.swapaxes(array, 0, 1)[:, ::-1]
        from vtkplotlib.nuts_and_bolts import isinstance_no_import
        if isinstance_no_import(array, "PIL.Image", "Image"):
            array = np.array(array)
            array = np.swapaxes(array, 0, 1)[:, ::-1]

        ex = lambda x: TypeError("`array` must be an np.ndarray with shape"
                                 " (m, n, 3) or (m, n, 4). Got {} {}".format(
                                     x, repr(array)))
        if not isinstance(array, np.ndarray):
            raise ex(type(array))
        if len(array.shape) != 3:
            raise ex(array.shape)
        if not (3 <= array.shape[2] <= 4):
            raise ex(array.shape)

        if array.dtype.kind in "ui":
            array = array / ((1 << (8 * array.dtype.itemsize)) - 1)

        self.array = array
        self.interpolate = interpolate

        self.shape = np.array(self.array.shape[:2])
Beispiel #3
0
def as_qicon(obj):
    pixmap = None

    if isinstance(obj, QtGui.QIcon):
        return obj

    from vtkplotlib.nuts_and_bolts import isinstance_PathLike, isinstance_no_import
    if isinstance_PathLike(obj):
        pixmap = QtGui.QPixmap(str(obj))

    if isinstance_no_import(obj, "PIL.Image", "Image"):
        pixmap = obj.toqpixmap()

    if pixmap is not None:
        return QtGui.QIcon(pixmap)
    else:
        raise TypeError("""Icons can be created from any of the following:
    - str
    - os.Pathlike
    - QtGui.QIcon
    - PIL.Image.Image
Received {}""".format(type(obj)))
Beispiel #4
0
def as_rgb_a(color=None, opacity=None):
    """This method converts all the different ways a single color and opacity
    can be specified into the form ``(np.array([red, green, blue]), opacity)``.

    The **color** argument can be:

    #. A string named color such as "r" or "red". This uses matplotlib's
       named color libraries. For a full list of available colors see the dicts
       `BASE_COLORS`, `CSS4_COLORS` and `XKCD_COLORS` from `matplotlib.colors` or
       `vtkplotlib.colors.mpl_colors.keys()`.

    #. A tuple or list of `3` or `4` scalars representing (r, g, b) or
       (r, g, b, alpha). r, g, b, alpha can be from `0` to `1` or from `0` to
       `255` (inclusive).

    #. An html hex string in the form "#RRGGBB" or "#RRGGBBAA" where ``"RR"``,
       ``"GG"``, ``"BB"`` and ``"AA"`` are hexadecimal numbers from `00` to `FF`.

    #. A ``PyQt5.QtGui.QColor()``.

    The **opacity** argument should be a scalar like those for the (r, g, b)
    from form 2 above values.

    If an opacity if specified in both arguments then **opacity** argument
    overrides alpha values in **color**.

    .. note::

        Conventionally the values if they are from 0.0 to 1.0 they should be
        floats and if they are from 0 to 255 they should be ints. But this is so
        often not the case that this rule is unusable. This function divides by
        255 if the scalars are integers and it sees anything greater than 1.
"""

    color_out = None
    opacity_out = None

    if color is not None:
        if isinstance(color, _future_utils.string_types):
            if _future_utils.PY2 and isinstance(color, unicode):
                color = color.encode()

            if color[0] == "#":
                return as_rgb_a(_hex_to_rgba(color), opacity)

            return as_rgb_a(_named_matplotlib_color(color), opacity)

        # QColors
        from vtkplotlib.nuts_and_bolts import isinstance_no_import
        if isinstance_no_import(color, "PyQt5.QtGui", "QColor"):
            return as_rgb_a(color.getRgbF(), opacity)

        color = np.asarray(color)
        if color.dtype.kind in "ui" and color.max() > 1:
            # convert 0 <= x < 256 colors to 0 <= x <= 1
            color = color / 255.
            if opacity is not None:
                opacity /= 255

        if len(color) == 4:
            opacity_out = color[3]
            color = np.array(color[:3])

        color_out = color

    if opacity is not None:
        opacity_out = opacity

    return color_out, opacity_out
Beispiel #5
0
def as_rgb_a(color=None, opacity=None):
    """This method converts all the different ways a single color and opacity
    can be specified into the form ``(np.array([red, green, blue]), opacity)``.

    The **color** argument can be:

    #. A string named color such as "r" or "red". This uses matplotlib's
       named color libraries. For a full list of available colors see the dicts
       `BASE_COLORS`, `CSS4_COLORS` and `XKCD_COLORS` from `matplotlib.colors` or
       `vtkplotlib.colors.mpl_colors.keys()`.

    #. A tuple or list of `3` or `4` scalars representing (r, g, b) or
       (r, g, b, alpha). r, g, b, alpha can be from `0` to `1` or from `0` to
       `255` (inclusive).

    #. An html hex string in the form "#RRGGBB" or "#RRGGBBAA" where ``"RR"``,
       ``"GG"``, ``"BB"`` and ``"AA"`` are hexadecimal numbers from `00` to `FF`.

    #. A ``PyQt5.QtGui.QColor()``.

    The **opacity** argument should be a scalar like those for the (r, g, b)
    from form 2 above values.

    If an opacity if specified in both arguments then **opacity** argument
    overrides alpha values in **color**.

    .. note::

        Conventionally the values if they are from 0.0 to 1.0 they should be
        floats and if they are from 0 to 255 they should be ints. But this is so
        often not the case that this rule is unusable. This function divides by
        255 if the scalars are integers and it sees anything greater than 1.
"""

    color_out = None
    opacity_out = None

    if color is not None:
        if isinstance(color, _future_utils.string_types):
            if _future_utils.PY2 and isinstance(color, unicode):
                color = color.encode()

            if color[0] == "#":
                if len(color) not in (7, 9):
                    raise ValueError(
                        "HTML Hex string color \"{}\" is not a valid length.".
                        format(color))
                # allow #RRGGBB hex colors
                # mpl's hex2rgb doesn't allow opacity. Otherwise I'd just use that
                return as_rgb_a(tuple(int(color[i:2 + i], 16)
                                      for i in range(1, len(color), 2)),
                                opacity) # yapf: disable
            else:
                # use matplotlib's color library
                if color in mpl_colors:
                    color = mpl_colors[color]
                else:
                    # If not in mpl's library try to correct user input and try again
                    corrected = color.lower().replace("_", " ").replace(
                        "-", " ")
                    import warnings

                    if corrected in mpl_colors:
                        warnings.warn(
                            "Auto-correcting color {!r} to {!r}.\nMatplotlib "
                            "colors are all lowercase and use spaces instead of"
                            " underscores.".format(color, corrected),
                            UserWarning
                        ) # yapf: disable
                        color = mpl_colors[corrected]

                    else:
                        # If still not found then cancel the whole operation
                        # (including opacity)
                        warnings.warn(
                            "Color {!r} not found. Skipping color assignment. "
                            "See vtkplotlib.colors.mpl_colors.keys() for a list"
                            " of available colors.".format(color),
                            UserWarning
                        ) # yapf: disable
                        return None, None

        # QColors
        from vtkplotlib.nuts_and_bolts import isinstance_no_import
        if isinstance_no_import(color, "PyQt5.QtGui", "QColor"):
            return as_rgb_a(color.getRgbF(), opacity)

        color = np.asarray(color)
        if color.dtype.kind in "ui" and color.max() > 1:
            # convert 0 <= x < 256 colors to 0 <= x <= 1
            color = color / 255.
            if opacity is not None:
                opacity /= 255

        if len(color) == 4:
            opacity_out = color[3]
            color = np.array(color[:3])

        color_out = color

    if opacity is not None:
        opacity_out = opacity

    return color_out, opacity_out