예제 #1
0
    def assert_compare_images(self, a, b, max_average_diff, max_diff=255):
        self.assertEqual(a.mode, b.mode,
                         "got mode %r, expected %r" % (a.mode, b.mode))
        self.assertEqual(a.size, b.size,
                         "got size %r, expected %r" % (a.size, b.size))

        a, b = convert_to_comparable(a, b)

        bands = ImageMode.getmode(a.mode).bands
        for band, ach, bch in zip(bands, a.split(), b.split()):
            ch_diff = ImageMath.eval("convert(abs(a - b), 'L')", a=ach, b=bch)
            ch_hist = ch_diff.histogram()

            average_diff = sum(i * num
                               for i, num in enumerate(ch_hist)) / float(
                                   a.size[0] * a.size[1])
            self.assertGreaterEqual(
                max_average_diff,
                average_diff,
                ("average pixel value difference {:.4f} > expected {:.4f} "
                 "for '{}' band").format(average_diff, max_average_diff, band),
            )

            last_diff = [i for i, num in enumerate(ch_hist) if num > 0][-1]
            self.assertGreaterEqual(
                max_diff,
                last_diff,
                "max pixel value difference {} > expected {} for '{}' band".
                format(last_diff, max_diff, band),
            )
예제 #2
0
        def create_test_image():
            # set up test image with something interesting in the tested aux
            # channel.
            nine_grid_deltas = [
                (-1, -1), (-1, 0), (-1, 1),
                ( 0, -1), ( 0, 0), ( 0, 1),
                ( 1, -1), ( 1, 0), ( 1, 1),
            ]
            chans = []
            bands = ImageMode.getmode(mode).bands
            for band_ndx in range(len(bands)):
                channel_type = 'L'  # 8-bit unorm
                channel_pattern = hopper(channel_type)

                # paste pattern with varying offsets to avoid correlation
                # potentially hiding some bugs (like channels getting mixed).
                paste_offset = (
                    int(band_ndx / float(len(bands)) * channel_pattern.size[0]),
                    int(band_ndx / float(len(bands) * 2) * channel_pattern.size[1])
                )
                channel_data = Image.new(channel_type, channel_pattern.size)
                for delta in nine_grid_deltas:
                    channel_data.paste(channel_pattern, tuple(paste_offset[c] + delta[c]*channel_pattern.size[c] for c in range(2)))
                chans.append(channel_data)
            return Image.merge(mode, chans)
        def create_test_image():
            # set up test image with something interesting in the tested aux
            # channel.
            nine_grid_deltas = [
                (-1, -1),
                (-1, 0),
                (-1, 1),
                (0, -1),
                (0, 0),
                (0, 1),
                (1, -1),
                (1, 0),
                (1, 1),
            ]
            chans = []
            bands = ImageMode.getmode(mode).bands
            for band_ndx in range(len(bands)):
                channel_type = 'L'  # 8-bit unorm
                channel_pattern = hopper(channel_type)

                # paste pattern with varying offsets to avoid correlation
                # potentially hiding some bugs (like channels getting mixed).
                paste_offset = (int(band_ndx / float(len(bands)) *
                                    channel_pattern.size[0]),
                                int(band_ndx / float(len(bands) * 2) *
                                    channel_pattern.size[1]))
                channel_data = Image.new(channel_type, channel_pattern.size)
                for delta in nine_grid_deltas:
                    channel_data.paste(
                        channel_pattern,
                        tuple(paste_offset[c] +
                              delta[c] * channel_pattern.size[c]
                              for c in range(2)))
                chans.append(channel_data)
            return Image.merge(mode, chans)
예제 #4
0
def color_count(image):
    """ Return the number of color values in the input image --
        this is the number of pixels times the band count
        of the image.
    """
    mode_descriptor = ImageMode.getmode(image.mode)
    width, height = image.size
    return width * height * len(mode_descriptor.bands)
예제 #5
0
    def __init__(self, default_factory, *args, **kwargs):
        if default_factory is None:
            default_factory = NOOp
        if not callable(default_factory):
            raise AttributeError(
                "ChannelFork() requires a callable default_factory.")

        self.channels = ImageMode.getmode(kwargs.pop('mode',
                                                     self.default_mode))

        super(ChannelFork, self).__init__(default_factory, *args, **kwargs)
예제 #6
0
 def __init__(self, default_factory, *args, **kwargs):
     if default_factory is None:
         default_factory = NOOp
     if not callable(default_factory):
         raise AttributeError(
             "ChannelFork() requires a callable default_factory.")
     
     self.channels = ImageMode.getmode(
         kwargs.pop('mode', self.default_mode))
     
     super(ChannelFork, self).__init__(default_factory, *args, **kwargs)
예제 #7
0
def get_image(mode):
    mode_info = ImageMode.getmode(mode)
    if mode_info.basetype == "L":
        bands = [gradients_image]
        for _ in mode_info.bands[1:]:
            # rotate previous image
            band = bands[-1].transpose(Image.ROTATE_90)
            bands.append(band)
        # Correct alpha channel by transforming completely transparent pixels.
        # Low alpha values also emphasize error after alpha multiplication.
        if mode.endswith("A"):
            bands[-1] = bands[-1].point(lambda x: int(85 + x / 1.5))
        im = Image.merge(mode, bands)
    else:
        assert len(mode_info.bands) == 1
        im = gradients_image.convert(mode)
    # change the height to make a not-square image
    return im.crop((0, 0, im.width, im.height - 5))
예제 #8
0
def assert_compare_images(a, b, max_average_diff, max_diff=255):
    assert a.mode == b.mode, f"got mode {repr(a.mode)}, expected {repr(b.mode)}"
    assert a.size == b.size, f"got size {repr(a.size)}, expected {repr(b.size)}"

    a, b = convert_to_comparable(a, b)

    bands = ImageMode.getmode(a.mode).bands
    for band, ach, bch in zip(bands, a.split(), b.split()):
        ch_diff = ImageMath.eval("convert(abs(a - b), 'L')", a=ach, b=bch)
        ch_hist = ch_diff.histogram()

        average_diff = sum(
            i * num for i, num in enumerate(ch_hist)) / (a.size[0] * a.size[1])
        msg = (f"average pixel value difference {average_diff:.4f} > "
               f"expected {max_average_diff:.4f} for '{band}' band")
        assert max_average_diff >= average_diff, msg

        last_diff = [i for i, num in enumerate(ch_hist) if num > 0][-1]
        assert max_diff >= last_diff, (
            f"max pixel value difference {last_diff} > expected {max_diff} "
            f"for '{band}' band")
예제 #9
0
def assert_compare_images(a, b, max_average_diff, max_diff=255):
    assert a.mode == b.mode, "got mode %r, expected %r" % (a.mode, b.mode)
    assert a.size == b.size, "got size %r, expected %r" % (a.size, b.size)

    a, b = convert_to_comparable(a, b)

    bands = ImageMode.getmode(a.mode).bands
    for band, ach, bch in zip(bands, a.split(), b.split()):
        ch_diff = ImageMath.eval("convert(abs(a - b), 'L')", a=ach, b=bch)
        ch_hist = ch_diff.histogram()

        average_diff = sum(
            i * num for i, num in enumerate(ch_hist)) / (a.size[0] * a.size[1])
        msg = ("average pixel value difference {:.4f} > expected {:.4f} "
               "for '{}' band".format(average_diff, max_average_diff, band))
        assert max_average_diff >= average_diff, msg

        last_diff = [i for i, num in enumerate(ch_hist) if num > 0][-1]
        assert (
            max_diff >= last_diff
        ), "max pixel value difference {} > expected {} for '{}' band".format(
            last_diff, max_diff, band)
예제 #10
0
import contextlib
import numpy
import os

from PIL import Image, ImageMode
from enum import auto, unique

from clu.constants.consts import DEBUG, ENCODING
from clu.enums import alias, AliasingEnum
from clu.naming import split_abbreviations
from clu.predicates import attr, getpyattr, isclasstype, or_none
from clu.typespace.namespace import Namespace
from clu.typology import string_types

junkdrawer = Namespace()
junkdrawer.imode = lambda image: ImageMode.getmode(image.mode)

ImageMode.getmode('RGB')  # one call must be made to getmode()
# to properly initialize ImageMode._modes:

junkdrawer.modes = ImageMode._modes
junkdrawer.types = Image._MODE_CONV
junkdrawer.ismap = Image._MAPMODES

mode_strings = tuple(junkdrawer.modes.keys())
dtypes_for_modes = {k: v[0] for k, v in junkdrawer.types.items()}

junkdrawer.idxmode = lambda idx: ImageMode.getmode(mode_strings[idx])
junkdrawer.is_mapped = lambda mode: mode in junkdrawer.ismap

예제 #11
0
파일: mode.py 프로젝트: fish2000/instakit
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function

import contextlib
import numpy
import os

from PIL import Image, ImageMode
from enum import auto, unique

from instakit.abc import Enum
from instakit.utils import misc

junkdrawer = misc.Namespace()
junkdrawer.imode = lambda image: ImageMode.getmode(image.mode)

def split_abbreviations(s):
    """ Split a string into a tuple of its unique constituents,
        based on its internal capitalization -- to wit:
        
        >>> split_abbreviations('RGB')
        ('R', 'G', 'B')
        >>> split_abbreviations('CMYK')
        ('C', 'M', 'Y', 'K')
        >>> split_abbreviations('YCbCr')
        ('Y', 'Cb', 'Cr')
        >>> split_abbreviations('sRGB')
        ('R', 'G', 'B')
        >>> split_abbreviations('XYZZ')
        ('X', 'Y', 'Z')
예제 #12
0
from tester import *

from PIL import Image
from PIL import ImageMode

ImageMode.getmode("1")
ImageMode.getmode("L")
ImageMode.getmode("P")
ImageMode.getmode("RGB")
ImageMode.getmode("I")
ImageMode.getmode("F")

m = ImageMode.getmode("1")
assert_equal(m.mode, "1")
assert_equal(m.bands, ("1",))
assert_equal(m.basemode, "L")
assert_equal(m.basetype, "L")

m = ImageMode.getmode("RGB")
assert_equal(m.mode, "RGB")
assert_equal(m.bands, ("R", "G", "B"))
assert_equal(m.basemode, "RGB")
assert_equal(m.basetype, "L")
예제 #13
0
    def test_sanity(self):

        im = hopper()
        im.mode

        from PIL import ImageMode

        ImageMode.getmode("1")
        ImageMode.getmode("L")
        ImageMode.getmode("P")
        ImageMode.getmode("RGB")
        ImageMode.getmode("I")
        ImageMode.getmode("F")

        m = ImageMode.getmode("1")
        self.assertEqual(m.mode, "1")
        self.assertEqual(m.bands, ("1",))
        self.assertEqual(m.basemode, "L")
        self.assertEqual(m.basetype, "L")

        m = ImageMode.getmode("RGB")
        self.assertEqual(m.mode, "RGB")
        self.assertEqual(m.bands, ("R", "G", "B"))
        self.assertEqual(m.basemode, "RGB")
        self.assertEqual(m.basetype, "L")
예제 #14
0
def test_sanity():

    with hopper() as im:
        im.mode

    ImageMode.getmode("1")
    ImageMode.getmode("L")
    ImageMode.getmode("P")
    ImageMode.getmode("RGB")
    ImageMode.getmode("I")
    ImageMode.getmode("F")

    m = ImageMode.getmode("1")
    assert m.mode == "1"
    assert str(m) == "1"
    assert m.bands == ("1",)
    assert m.basemode == "L"
    assert m.basetype == "L"

    for mode in (
        "I;16",
        "I;16S",
        "I;16L",
        "I;16LS",
        "I;16B",
        "I;16BS",
        "I;16N",
        "I;16NS",
    ):
        m = ImageMode.getmode(mode)
        assert m.mode == mode
        assert str(m) == mode
        assert m.bands == ("I",)
        assert m.basemode == "L"
        assert m.basetype == "L"

    m = ImageMode.getmode("RGB")
    assert m.mode == "RGB"
    assert str(m) == "RGB"
    assert m.bands == ("R", "G", "B")
    assert m.basemode == "RGB"
    assert m.basetype == "L"
예제 #15
0
    def test_sanity(self):
        ImageMode.getmode("1")
        ImageMode.getmode("L")
        ImageMode.getmode("P")
        ImageMode.getmode("RGB")
        ImageMode.getmode("I")
        ImageMode.getmode("F")

        m = ImageMode.getmode("1")
        self.assertEqual(m.mode, "1")
        self.assertEqual(m.bands, ("1",))
        self.assertEqual(m.basemode, "L")
        self.assertEqual(m.basetype, "L")

        m = ImageMode.getmode("RGB")
        self.assertEqual(m.mode, "RGB")
        self.assertEqual(m.bands, ("R", "G", "B"))
        self.assertEqual(m.basemode, "RGB")
        self.assertEqual(m.basetype, "L")
예제 #16
0
    def test_sanity(self):

        im = hopper()
        im.mode

        from PIL import ImageMode

        ImageMode.getmode("1")
        ImageMode.getmode("L")
        ImageMode.getmode("P")
        ImageMode.getmode("RGB")
        ImageMode.getmode("I")
        ImageMode.getmode("F")

        m = ImageMode.getmode("1")
        self.assertEqual(m.mode, "1")
        self.assertEqual(str(m), "1")
        self.assertEqual(m.bands, ("1", ))
        self.assertEqual(m.basemode, "L")
        self.assertEqual(m.basetype, "L")

        for mode in ("I;16", "I;16S", "I;16L", "I;16LS", "I;16B", "I;16BS",
                     "I;16N", "I;16NS"):
            m = ImageMode.getmode(mode)
            self.assertEqual(m.mode, mode)
            self.assertEqual(str(m), mode)
            self.assertEqual(m.bands, ("I", ))
            self.assertEqual(m.basemode, "L")
            self.assertEqual(m.basetype, "L")

        m = ImageMode.getmode("RGB")
        self.assertEqual(m.mode, "RGB")
        self.assertEqual(str(m), "RGB")
        self.assertEqual(m.bands, ("R", "G", "B"))
        self.assertEqual(m.basemode, "RGB")
        self.assertEqual(m.basetype, "L")
예제 #17
0
from tester import *

from PIL import Image
from PIL import ImageMode

ImageMode.getmode("1")
ImageMode.getmode("L")
ImageMode.getmode("P")
ImageMode.getmode("RGB")
ImageMode.getmode("I")
ImageMode.getmode("F")

m = ImageMode.getmode("1")
assert_equal(m.mode, "1")
assert_equal(m.bands, ("1", ))
assert_equal(m.basemode, "L")
assert_equal(m.basetype, "L")

m = ImageMode.getmode("RGB")
assert_equal(m.mode, "RGB")
assert_equal(m.bands, ("R", "G", "B"))
assert_equal(m.basemode, "RGB")
assert_equal(m.basetype, "L")
예제 #18
0
 def _set_mode(self, mode_string):
     self.channels = ImageMode.getmode(mode_string)
예제 #19
0
 def _set_mode(self, mode_string):
     self.channels = ImageMode.getmode(mode_string)