404

[ Avaa Bypassed ]




Upload:

Command:

botdev@3.14.135.249: ~ $
# A binary morphology add-on for the Python Imaging Library
#
# History:
#   2014-06-04 Initial version.
#
# Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>

import re

from . import Image, _imagingmorph

LUT_SIZE = 1 << 9

# fmt: off
ROTATION_MATRIX = [
    6, 3, 0,
    7, 4, 1,
    8, 5, 2,
]
MIRROR_MATRIX = [
    2, 1, 0,
    5, 4, 3,
    8, 7, 6,
]
# fmt: on


class LutBuilder:
    """A class for building a MorphLut from a descriptive language

    The input patterns is a list of a strings sequences like these::

        4:(...
           .1.
           111)->1

    (whitespaces including linebreaks are ignored). The option 4
    describes a series of symmetry operations (in this case a
    4-rotation), the pattern is described by:

    - . or X - Ignore
    - 1 - Pixel is on
    - 0 - Pixel is off

    The result of the operation is described after "->" string.

    The default is to return the current pixel value, which is
    returned if no other match is found.

    Operations:

    - 4 - 4 way rotation
    - N - Negate
    - 1 - Dummy op for no other operation (an op must always be given)
    - M - Mirroring

    Example::

        lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
        lut = lb.build_lut()

    """

    def __init__(self, patterns=None, op_name=None):
        if patterns is not None:
            self.patterns = patterns
        else:
            self.patterns = []
        self.lut = None
        if op_name is not None:
            known_patterns = {
                "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
                "dilation4": ["4:(... .0. .1.)->1"],
                "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
                "erosion4": ["4:(... .1. .0.)->0"],
                "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
                "edge": [
                    "1:(... ... ...)->0",
                    "4:(.0. .1. ...)->1",
                    "4:(01. .1. ...)->1",
                ],
            }
            if op_name not in known_patterns:
                raise Exception("Unknown pattern " + op_name + "!")

            self.patterns = known_patterns[op_name]

    def add_patterns(self, patterns):
        self.patterns += patterns

    def build_default_lut(self):
        symbols = [0, 1]
        m = 1 << 4  # pos of current pixel
        self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))

    def get_lut(self):
        return self.lut

    def _string_permute(self, pattern, permutation):
        """string_permute takes a pattern and a permutation and returns the
        string permuted according to the permutation list.
        """
        assert len(permutation) == 9
        return "".join(pattern[p] for p in permutation)

    def _pattern_permute(self, basic_pattern, options, basic_result):
        """pattern_permute takes a basic pattern and its result and clones
        the pattern according to the modifications described in the $options
        parameter. It returns a list of all cloned patterns."""
        patterns = [(basic_pattern, basic_result)]

        # rotations
        if "4" in options:
            res = patterns[-1][1]
            for i in range(4):
                patterns.append(
                    (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
                )
        # mirror
        if "M" in options:
            n = len(patterns)
            for pattern, res in patterns[0:n]:
                patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))

        # negate
        if "N" in options:
            n = len(patterns)
            for pattern, res in patterns[0:n]:
                # Swap 0 and 1
                pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
                res = 1 - int(res)
                patterns.append((pattern, res))

        return patterns

    def build_lut(self):
        """Compile all patterns into a morphology lut.

        TBD :Build based on (file) morphlut:modify_lut
        """
        self.build_default_lut()
        patterns = []

        # Parse and create symmetries of the patterns strings
        for p in self.patterns:
            m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
            if not m:
                raise Exception('Syntax error in pattern "' + p + '"')
            options = m.group(1)
            pattern = m.group(2)
            result = int(m.group(3))

            # Get rid of spaces
            pattern = pattern.replace(" ", "").replace("\n", "")

            patterns += self._pattern_permute(pattern, options, result)

        # compile the patterns into regular expressions for speed
        for i, pattern in enumerate(patterns):
            p = pattern[0].replace(".", "X").replace("X", "[01]")
            p = re.compile(p)
            patterns[i] = (p, pattern[1])

        # Step through table and find patterns that match.
        # Note that all the patterns are searched. The last one
        # caught overrides
        for i in range(LUT_SIZE):
            # Build the bit pattern
            bitpattern = bin(i)[2:]
            bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]

            for p, r in patterns:
                if p.match(bitpattern):
                    self.lut[i] = [0, 1][r]

        return self.lut


class MorphOp:
    """A class for binary morphological operators"""

    def __init__(self, lut=None, op_name=None, patterns=None):
        """Create a binary morphological operator"""
        self.lut = lut
        if op_name is not None:
            self.lut = LutBuilder(op_name=op_name).build_lut()
        elif patterns is not None:
            self.lut = LutBuilder(patterns=patterns).build_lut()

    def apply(self, image):
        """Run a single morphological operation on an image

        Returns a tuple of the number of changed pixels and the
        morphed image"""
        if self.lut is None:
            raise Exception("No operator loaded")

        if image.mode != "L":
            raise Exception("Image must be binary, meaning it must use mode L")
        outimage = Image.new(image.mode, image.size, None)
        count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)
        return count, outimage

    def match(self, image):
        """Get a list of coordinates matching the morphological operation on
        an image.

        Returns a list of tuples of (x,y) coordinates
        of all matching pixels. See :ref:`coordinate-system`."""
        if self.lut is None:
            raise Exception("No operator loaded")

        if image.mode != "L":
            raise Exception("Image must be binary, meaning it must use mode L")
        return _imagingmorph.match(bytes(self.lut), image.im.id)

    def get_on_pixels(self, image):
        """Get a list of all turned on pixels in a binary image

        Returns a list of tuples of (x,y) coordinates
        of all matching pixels. See :ref:`coordinate-system`."""

        if image.mode != "L":
            raise Exception("Image must be binary, meaning it must use mode L")
        return _imagingmorph.get_on_pixels(image.im.id)

    def load_lut(self, filename):
        """Load an operator from an mrl file"""
        with open(filename, "rb") as f:
            self.lut = bytearray(f.read())

        if len(self.lut) != LUT_SIZE:
            self.lut = None
            raise Exception("Wrong size operator file!")

    def save_lut(self, filename):
        """Save an operator to an mrl file"""
        if self.lut is None:
            raise Exception("No operator loaded")
        with open(filename, "wb") as f:
            f.write(self.lut)

    def set_lut(self, lut):
        """Set the lut from an external source"""
        self.lut = lut

Filemanager

Name Type Size Permission Actions
__pycache__ Folder 2755
BdfFontFile.py File 2.75 KB 0644
BlpImagePlugin.py File 14 KB 0644
BmpImagePlugin.py File 13.92 KB 0644
BufrStubImagePlugin.py File 1.48 KB 0644
ContainerIO.py File 2.82 KB 0644
CurImagePlugin.py File 1.68 KB 0644
DcxImagePlugin.py File 2.09 KB 0644
DdsImagePlugin.py File 5.34 KB 0644
EpsImagePlugin.py File 11.82 KB 0644
ExifTags.py File 8.8 KB 0644
FitsStubImagePlugin.py File 1.59 KB 0644
FliImagePlugin.py File 4.23 KB 0644
FontFile.py File 2.7 KB 0644
FpxImagePlugin.py File 6.53 KB 0644
FtexImagePlugin.py File 3.23 KB 0644
GbrImagePlugin.py File 2.73 KB 0644
GdImageFile.py File 2.47 KB 0644
GifImagePlugin.py File 28.25 KB 0644
GimpGradientFile.py File 3.27 KB 0644
GimpPaletteFile.py File 1.24 KB 0644
GribStubImagePlugin.py File 1.51 KB 0644
Hdf5StubImagePlugin.py File 1.48 KB 0644
IcnsImagePlugin.py File 11.44 KB 0644
IcoImagePlugin.py File 9.94 KB 0644
ImImagePlugin.py File 10.53 KB 0644
Image.py File 113.4 KB 0644
ImageChops.py File 7.13 KB 0644
ImageCms.py File 36.22 KB 0644
ImageColor.py File 8.44 KB 0644
ImageDraw.py File 29.94 KB 0644
ImageDraw2.py File 4.9 KB 0644
ImageEnhance.py File 3.12 KB 0644
ImageFile.py File 20.74 KB 0644
ImageFilter.py File 15.46 KB 0644
ImageFont.py File 43.49 KB 0644
ImageGrab.py File 3.54 KB 0644
ImageMath.py File 6.88 KB 0644
ImageMode.py File 1.6 KB 0644
ImageMorph.py File 7.67 KB 0644
ImageOps.py File 18.03 KB 0644
ImagePalette.py File 6.2 KB 0644
ImagePath.py File 336 B 0644
ImageQt.py File 5.67 KB 0644
ImageSequence.py File 1.81 KB 0644
ImageShow.py File 6.15 KB 0644
ImageStat.py File 3.81 KB 0644
ImageTk.py File 9.11 KB 0644
ImageTransform.py File 2.78 KB 0644
ImageWin.py File 7.02 KB 0644
ImtImagePlugin.py File 2.15 KB 0644
IptcImagePlugin.py File 5.6 KB 0644
Jpeg2KImagePlugin.py File 8.52 KB 0644
JpegImagePlugin.py File 27.16 KB 0644
JpegPresets.py File 12.41 KB 0644
McIdasImagePlugin.py File 1.71 KB 0644
MicImagePlugin.py File 2.54 KB 0644
MpegImagePlugin.py File 1.76 KB 0644
MpoImagePlugin.py File 4.14 KB 0644
MspImagePlugin.py File 5.43 KB 0644
PSDraw.py File 6.51 KB 0644
PaletteFile.py File 1.08 KB 0644
PalmImagePlugin.py File 8.89 KB 0644
PcdImagePlugin.py File 1.47 KB 0644
PcfFontFile.py File 6.2 KB 0644
PcxImagePlugin.py File 5.41 KB 0644
PdfImagePlugin.py File 7.49 KB 0644
PdfParser.py File 33.58 KB 0644
PixarImagePlugin.py File 1.61 KB 0644
PngImagePlugin.py File 42.79 KB 0644
PpmImagePlugin.py File 4.34 KB 0644
PsdImagePlugin.py File 7.56 KB 0644
PyAccess.py File 9.37 KB 0644
SgiImagePlugin.py File 5.96 KB 0644
SpiderImagePlugin.py File 9.31 KB 0644
SunImagePlugin.py File 4.2 KB 0644
TarIO.py File 1.41 KB 0644
TgaImagePlugin.py File 6.18 KB 0644
TiffImagePlugin.py File 66.86 KB 0644
TiffTags.py File 14.22 KB 0644
WalImageFile.py File 5.4 KB 0644
WebPImagePlugin.py File 10.54 KB 0644
WmfImagePlugin.py File 4.56 KB 0644
XVThumbImagePlugin.py File 1.9 KB 0644
XbmImagePlugin.py File 2.37 KB 0644
XpmImagePlugin.py File 3 KB 0644
__init__.py File 3.18 KB 0644
__main__.py File 41 B 0644
_binary.py File 1.75 KB 0644
_imaging.cpython-36m-x86_64-linux-gnu.so File 650.13 KB 0755
_imagingcms.cpython-36m-x86_64-linux-gnu.so File 38.05 KB 0755
_imagingft.cpython-36m-x86_64-linux-gnu.so File 41.98 KB 0755
_imagingmath.cpython-36m-x86_64-linux-gnu.so File 24.43 KB 0755
_imagingmorph.cpython-36m-x86_64-linux-gnu.so File 8.12 KB 0755
_imagingtk.cpython-36m-x86_64-linux-gnu.so File 9.37 KB 0755
_tkinter_finder.py File 224 B 0644
_util.py File 359 B 0644
_version.py File 50 B 0644
_webp.cpython-36m-x86_64-linux-gnu.so File 40.82 KB 0755
features.py File 8.8 KB 0644