Exemplo n.º 1
1
def init_color_profiles():
	global COLOR_PROFILES
	
	COLOR_PROFILES['srgb'] = ImageCms.createProfile('sRGB')
	
	#COLOR_PROFILES['argb'] = ImageCms.getOpenProfile(r'AdobeRGB.icc')
	COLOR_PROFILES['argb'] = ImageCms.getOpenProfile(os.path.join(ICC_DATA_DIR, 'AdobeRGB.icc'))
Exemplo n.º 2
0
def add_profile():
    in_file_list = [
        "./picture/r.png", "./picture/o.png", "./picture/g.png",
        "./picture/b.png", "./picture/w.png", "./picture/saturation.png"
    ]
    out_file_list = [
        "./picture/r_dci.png", "./picture/o_dci.png", "./picture/g_dci.png",
        "./picture/b_dci.png", "./picture/w_dci.png",
        "./picture/saturation_dci.png"
    ]
    out_file_list2 = [
        "./picture/r_sRGB.png", "./picture/o_sRGB.png", "./picture/g_sRGB_png",
        "./picture/b_sRGB.png", "./picture/w_sRGB.png",
        "./picture/saturation_sRGB.png"
    ]

    dci_profile_name = "./picture/DCI-P3_modify.icc"
    dci_profile = ImageCms.getOpenProfile(dci_profile_name)
    sRGB_profile = ImageCms.getOpenProfile(dci_profile_name)
    sRGB_profile_ref = ImageCms.createProfile('sRGB')
    sRGB_profile.profile = sRGB_profile_ref

    for idx, in_file in enumerate(in_file_list):
        img = Image.open(in_file)
        img.save(out_file_list[idx], icc_profile=dci_profile.tobytes())
        img.save(out_file_list2[idx], icc_profile=sRGB_profile.tobytes())
Exemplo n.º 3
0
def test_profile_tobytes():
    with Image.open("Tests/images/rgb.jpg") as i:
        p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))

    p2 = ImageCms.getOpenProfile(BytesIO(p.tobytes()))

    # not the same bytes as the original icc_profile, but it does roundtrip
    assert p.tobytes() == p2.tobytes()
    assert ImageCms.getProfileName(p) == ImageCms.getProfileName(p2)
    assert ImageCms.getProfileDescription(p) == ImageCms.getProfileDescription(p2)
Exemplo n.º 4
0
    def test_profile_tobytes(self):
        i = Image.open("Tests/images/rgb.jpg")
        p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))

        p2 = ImageCms.getOpenProfile(BytesIO(p.tobytes()))

        # not the same bytes as the original icc_profile,
        # but it does roundtrip
        self.assertEqual(p.tobytes(), p2.tobytes())
        self.assertEqual(ImageCms.getProfileName(p),
                         ImageCms.getProfileName(p2))
        self.assertEqual(ImageCms.getProfileDescription(p),
                         ImageCms.getProfileDescription(p2))
    def test_profile_tobytes(self):
        i = Image.open("Tests/images/rgb.jpg")
        p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))

        p2 = ImageCms.getOpenProfile(BytesIO(p.tobytes()))

        # not the same bytes as the original icc_profile,
        # but it does roundtrip
        self.assertEqual(p.tobytes(), p2.tobytes())
        self.assertEqual(ImageCms.getProfileName(p),
                         ImageCms.getProfileName(p2))
        self.assertEqual(ImageCms.getProfileDescription(p),
                         ImageCms.getProfileDescription(p2))
Exemplo n.º 6
0
def test_sanity():

    # basic smoke test.
    # this mostly follows the cms_test outline.

    v = ImageCms.versions() # should return four strings
    assert_equal(v[0], '1.0.0 pil')
    assert_equal(list(map(type, v)), [str, str, str, str])

    # internal version number
    assert_match(ImageCms.core.littlecms_version, "\d+\.\d+$")

    i = ImageCms.profileToProfile(lena(), SRGB, SRGB)
    assert_image(i, "RGB", (128, 128))

    t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
    i = ImageCms.applyTransform(lena(), t)
    assert_image(i, "RGB", (128, 128))

    p = ImageCms.createProfile("sRGB")
    o = ImageCms.getOpenProfile(SRGB)
    t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
    i = ImageCms.applyTransform(lena(), t)
    assert_image(i, "RGB", (128, 128))

    t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
    assert_equal(t.inputMode, "RGB")
    assert_equal(t.outputMode, "RGB")
    i = ImageCms.applyTransform(lena(), t)
    assert_image(i, "RGB", (128, 128))

    # test PointTransform convenience API
    im = lena().point(t)
Exemplo n.º 7
0
def test_extensions():
    # extensions

    with Image.open("Tests/images/rgb.jpg") as i:
        p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
    assert (ImageCms.getProfileName(p).strip() ==
            "IEC 61966-2.1 Default RGB colour space - sRGB")
Exemplo n.º 8
0
    def test_deprecations(self):
        self.skip_missing()
        o = ImageCms.getOpenProfile(SRGB)
        p = o.profile

        def helper_deprecated(attr, expected):
            result = self.assert_warning(DeprecationWarning, getattr, p, attr)
            self.assertEqual(result, expected)

        # p.color_space
        helper_deprecated("color_space", "RGB")

        # p.pcs
        helper_deprecated("pcs", "XYZ")

        # p.product_copyright
        helper_deprecated(
            "product_copyright", "Copyright International Color Consortium, 2009"
        )

        # p.product_desc
        helper_deprecated("product_desc", "sRGB IEC61966-2-1 black scaled")

        # p.product_description
        helper_deprecated("product_description", "sRGB IEC61966-2-1 black scaled")

        # p.product_manufacturer
        helper_deprecated("product_manufacturer", "")

        # p.product_model
        helper_deprecated(
            "product_model", "IEC 61966-2-1 Default RGB Colour Space - sRGB"
        )
Exemplo n.º 9
0
    def test_deprecations(self):
        self.skip_missing()
        o = ImageCms.getOpenProfile(SRGB)
        p = o.profile

        def helper_deprecated(attr, expected):
            result = self.assert_warning(DeprecationWarning, getattr, p, attr)
            self.assertEqual(result, expected)

        # p.color_space
        helper_deprecated("color_space", "RGB")

        # p.pcs
        helper_deprecated("pcs", "XYZ")

        # p.product_copyright
        helper_deprecated("product_copyright",
                          "Copyright International Color Consortium, 2009")

        # p.product_desc
        helper_deprecated("product_desc", "sRGB IEC61966-2-1 black scaled")

        # p.product_description
        helper_deprecated("product_description",
                          "sRGB IEC61966-2-1 black scaled")

        # p.product_manufacturer
        helper_deprecated("product_manufacturer", "")

        # p.product_model
        helper_deprecated("product_model",
                          "IEC 61966-2-1 Default RGB Colour Space - sRGB")
Exemplo n.º 10
0
def test_read_file_icc_color_profile():
    for fn in glob.glob('tests/images/*.heic'):
        heif_file = pyheif.read_heif(fn)
        if heif_file.color_profile and heif_file.color_profile['type'] in [
                'prof', 'rICC'
        ]:
            profile = io.BytesIO(heif_file.color_profile['data'])
            cms = ImageCms.getOpenProfile(profile)
Exemplo n.º 11
0
    def test_extensions(self):
        # extensions

        i = Image.open("Tests/images/rgb.jpg")
        p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
        self.assertEqual(
            ImageCms.getProfileName(p).strip(),
            'IEC 61966-2.1 Default RGB colour space - sRGB')
    def test_extensions(self):
        # extensions

        i = Image.open("Tests/images/rgb.jpg")
        p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
        self.assertEqual(
            ImageCms.getProfileName(p).strip(),
            'IEC 61966-2.1 Default RGB colour space - sRGB')
Exemplo n.º 13
0
def init_color_profiles():
    global COLOR_PROFILES

    COLOR_PROFILES['srgb'] = ImageCms.createProfile('sRGB')

    #COLOR_PROFILES['argb'] = ImageCms.getOpenProfile(r'AdobeRGB.icc')
    COLOR_PROFILES['argb'] = ImageCms.getOpenProfile(
        os.path.join(ICC_DATA_DIR, 'AdobeRGB.icc'))
Exemplo n.º 14
0
def bgr2cmyk(img):
    rgb = img[:, :, ::-1]
    p_rgb = Image.fromarray(rgb)

    srgb_path = '/usr/share/color/icc/colord/sRGB.icc'
    cmyk_path = '/usr/share/color/icc/krita/cmyk.icm'
    ImageCms.getOpenProfile(srgb_path)
    ImageCms.getOpenProfile(cmyk_path)
    p_cmyk = ImageCms.profileToProfile(
        p_rgb,
        srgb_path,
        cmyk_path,
        # 'USWebCoatedSWOP.icc',
        renderingIntent=0,
        outputMode='CMYK')
    cmyk = np.array(p_cmyk)
    return cmyk
Exemplo n.º 15
0
def test_read_icc_color_profile():
    for fn in Path().glob("tests/images/**/*.heic"):
        heif_file = pyheif.read(fn)
        if heif_file.color_profile and heif_file.color_profile["type"] in [
                "prof",
                "rICC",
        ]:
            profile = io.BytesIO(heif_file.color_profile["data"])
            cms = ImageCms.getOpenProfile(profile)
Exemplo n.º 16
0
    def test_extended_information(self):
        self.skip_missing()
        o = ImageCms.getOpenProfile(SRGB)
        p = o.profile

        self.assertEqual(p.attributes, 4294967296)
        self.assertEqual(p.blue_colorant, ((0.14306640625, 0.06060791015625, 0.7140960693359375), (0.1558847490315394, 0.06603820639433387, 0.06060791015625)))
        self.assertEqual(p.blue_primary, ((0.14306641366715667, 0.06060790921083026, 0.7140960805782015), (0.15588475410450106, 0.06603820408959558, 0.06060790921083026)))
        self.assertEqual(p.chromatic_adaptation, (((1.04791259765625, 0.0229339599609375, -0.050201416015625), (0.02960205078125, 0.9904632568359375, -0.0170745849609375), (-0.009246826171875, 0.0150604248046875, 0.7517852783203125)), ((1.0267159024652783, 0.022470062342089134, 0.0229339599609375), (0.02951378324103937, 0.9875098886387147, 0.9904632568359375), (-0.012205438066465256, 0.01987915407854985, 0.0150604248046875))))
        self.assertEqual(p.chromaticity, None)
        self.assertEqual(p.clut, {0: (False, False, True), 1: (False, False, True), 2: (False, False, True), 3: (False, False, True)})
        self.assertEqual(p.color_space, 'RGB')
        self.assertEqual(p.colorant_table, None)
        self.assertEqual(p.colorant_table_out, None)
        self.assertEqual(p.colorimetric_intent, None)
        self.assertEqual(p.connection_space, 'XYZ ')
        self.assertEqual(p.copyright, 'Copyright International Color Consortium, 2009')
        self.assertEqual(p.creation_date, datetime.datetime(2009, 2, 27, 21, 36, 31))
        self.assertEqual(p.device_class, 'mntr')
        self.assertEqual(p.green_colorant, ((0.3851470947265625, 0.7168731689453125, 0.097076416015625), (0.32119769927720654, 0.5978443449048152, 0.7168731689453125)))
        self.assertEqual(p.green_primary, ((0.3851470888162112, 0.7168731974161346, 0.09707641738998518), (0.32119768793686687, 0.5978443567149709, 0.7168731974161346)))
        self.assertEqual(p.header_flags, 0)
        self.assertEqual(p.header_manufacturer, '\x00\x00\x00\x00')
        self.assertEqual(p.header_model, '\x00\x00\x00\x00')
        self.assertEqual(p.icc_measurement_condition, {'backing': (0.0, 0.0, 0.0), 'flare': 0.0, 'geo': 'unknown', 'observer': 1, 'illuminant_type': 'D65'})
        self.assertEqual(p.icc_version, 33554432)
        self.assertEqual(p.icc_viewing_condition, None)
        self.assertEqual(p.intent_supported, {0: (True, True, True), 1: (True, True, True), 2: (True, True, True), 3: (True, True, True)})
        self.assertEqual(p.is_matrix_shaper, True)
        self.assertEqual(p.luminance, ((0.0, 80.0, 0.0), (0.0, 1.0, 80.0)))
        self.assertEqual(p.manufacturer, None)
        self.assertEqual(p.media_black_point, ((0.012054443359375, 0.0124969482421875, 0.01031494140625), (0.34573304157549234, 0.35842450765864337, 0.0124969482421875)))
        self.assertEqual(p.media_white_point, ((0.964202880859375, 1.0, 0.8249053955078125), (0.3457029219802284, 0.3585375327567059, 1.0)))
        self.assertEqual(p.media_white_point_temperature, 5000.722328847392)
        self.assertEqual(p.model, 'IEC 61966-2-1 Default RGB Colour Space - sRGB')
        self.assertEqual(p.pcs, 'XYZ')
        self.assertEqual(p.perceptual_rendering_intent_gamut, None)
        self.assertEqual(p.product_copyright, 'Copyright International Color Consortium, 2009')
        self.assertEqual(p.product_desc, 'sRGB IEC61966-2-1 black scaled')
        self.assertEqual(p.product_description, 'sRGB IEC61966-2-1 black scaled')
        self.assertEqual(p.product_manufacturer, '')
        self.assertEqual(p.product_model, 'IEC 61966-2-1 Default RGB Colour Space - sRGB')
        self.assertEqual(p.profile_description, 'sRGB IEC61966-2-1 black scaled')
        self.assertEqual(p.profile_id, b')\xf8=\xde\xaf\xf2U\xaexB\xfa\xe4\xca\x839\r')
        self.assertEqual(p.red_colorant, ((0.436065673828125, 0.2224884033203125, 0.013916015625), (0.6484536316398539, 0.3308524880306778, 0.2224884033203125)))
        self.assertEqual(p.red_primary, ((0.43606566581047446, 0.22248840582960838, 0.013916015621759925), (0.6484536250319214, 0.3308524944738204, 0.22248840582960838)))
        self.assertEqual(p.rendering_intent, 0)
        self.assertEqual(p.saturation_rendering_intent_gamut, None)
        self.assertEqual(p.screening_description, None)
        self.assertEqual(p.target, None)
        self.assertEqual(p.technology, 'CRT ')
        self.assertEqual(p.version, 2.0)
        self.assertEqual(p.viewing_condition, 'Reference Viewing Condition in IEC 61966-2-1')
        self.assertEqual(p.xcolor_space, 'RGB ')
Exemplo n.º 17
0
def test_non_ascii_path(tmp_path):
    skip_missing()
    tempfile = str(tmp_path / ("temp_" + chr(128) + ".icc"))
    try:
        shutil.copy(SRGB, tempfile)
    except UnicodeEncodeError:
        pytest.skip("Non-ASCII path could not be created")

    o = ImageCms.getOpenProfile(tempfile)
    p = o.profile
    assert p.model == "IEC 61966-2-1 Default RGB Colour Space - sRGB"
    def test_sanity(self):

        # basic smoke test.
        # this mostly follows the cms_test outline.

        v = ImageCms.versions()  # should return four strings
        self.assertEqual(v[0], '1.0.0 pil')
        self.assertEqual(list(map(type, v)), [str, str, str, str])

        # internal version number
        self.assertRegexpMatches(ImageCms.core.littlecms_version, r"\d+\.\d+$")

        self.skip_missing()
        i = ImageCms.profileToProfile(hopper(), SRGB, SRGB)
        self.assert_image(i, "RGB", (128, 128))

        i = hopper()
        ImageCms.profileToProfile(i, SRGB, SRGB, inPlace=True)
        self.assert_image(i, "RGB", (128, 128))

        t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
        i = ImageCms.applyTransform(hopper(), t)
        self.assert_image(i, "RGB", (128, 128))

        i = hopper()
        t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
        ImageCms.applyTransform(hopper(), t, inPlace=True)
        self.assert_image(i, "RGB", (128, 128))

        p = ImageCms.createProfile("sRGB")
        o = ImageCms.getOpenProfile(SRGB)
        t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
        i = ImageCms.applyTransform(hopper(), t)
        self.assert_image(i, "RGB", (128, 128))

        t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
        self.assertEqual(t.inputMode, "RGB")
        self.assertEqual(t.outputMode, "RGB")
        i = ImageCms.applyTransform(hopper(), t)
        self.assert_image(i, "RGB", (128, 128))

        # test PointTransform convenience API
        hopper().point(t)
Exemplo n.º 19
0
    def convert_icc_profile(self,
                            image_filepath,
                            output_filepath,
                            icc_profile_filepath,
                            new_colour_mode=None):
        """
        Convert the image to a new icc profile. This is lossy, so should only be done when necessary (e.g. if jp2 doesn't support the colour profile)
        Doesn't support 16bit images due to limitations of Pillow

        Uses the perceptual rendering intent, as it's the recommended one for general photographic purposes, and loses less information on out-of-gamut colours than relative colormetric
        However, if we're converting to a matrix profile like AdobeRGB, this will use relative colormetric instead, as perceptual intents are only supported by lookup table colour profiles
        In practise, we should be converting to a wide gamut profile, so out-of-gamut colours will be limited anyway
        :param image_filepath:
        :param output_filepath:
        :param icc_profile_filepath:
        :param new_colour_mode:
        :return:
        """
        with Image.open(image_filepath) as input_pil:
            # BitsPerSample is 258 (see PIL.TiffTags.TAGS_V2). tag_v2 is populated when opening an image, but not when saving
            orig_bit_depths = input_pil.tag_v2[258]

            if orig_bit_depths not in [(8, 8, 8, 8), (8, 8, 8), (8, ), (1, )]:
                raise ImageProcessingError(
                    "ICC profile conversion was unsuccessful for {0}: unsupported bit depth {1} "
                    "Note: Pillow does not support 16 bit image profile conversion."
                    .format(image_filepath, orig_bit_depths))

            input_icc_obj = input_pil.info.get('icc_profile')

            if input_icc_obj is None:
                raise ImageProcessingError("Image doesn't have a profile")

            input_profile = ImageCms.getOpenProfile(io.BytesIO(input_icc_obj))
            output_pil = ImageCms.profileToProfile(
                input_pil,
                input_profile,
                icc_profile_filepath,
                renderingIntent=ImageCms.INTENT_PERCEPTUAL,
                outputMode=new_colour_mode,
                inPlace=0)
            output_pil.save(output_filepath)
        self.copy_over_embedded_metadata(image_filepath, output_filepath)
Exemplo n.º 20
0
def test_sanity():
    # basic smoke test.
    # this mostly follows the cms_test outline.

    v = ImageCms.versions()  # should return four strings
    assert v[0] == "1.0.0 pil"
    assert list(map(type, v)) == [str, str, str, str]

    # internal version number
    assert re.search(r"\d+\.\d+(\.\d+)?$",
                     features.version_module("littlecms2"))

    skip_missing()
    i = ImageCms.profileToProfile(hopper(), SRGB, SRGB)
    assert_image(i, "RGB", (128, 128))

    i = hopper()
    ImageCms.profileToProfile(i, SRGB, SRGB, inPlace=True)
    assert_image(i, "RGB", (128, 128))

    t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
    i = ImageCms.applyTransform(hopper(), t)
    assert_image(i, "RGB", (128, 128))

    with hopper() as i:
        t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
        ImageCms.applyTransform(hopper(), t, inPlace=True)
        assert_image(i, "RGB", (128, 128))

    p = ImageCms.createProfile("sRGB")
    o = ImageCms.getOpenProfile(SRGB)
    t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
    i = ImageCms.applyTransform(hopper(), t)
    assert_image(i, "RGB", (128, 128))

    t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
    assert t.inputMode == "RGB"
    assert t.outputMode == "RGB"
    i = ImageCms.applyTransform(hopper(), t)
    assert_image(i, "RGB", (128, 128))

    # test PointTransform convenience API
    hopper().point(t)
Exemplo n.º 21
0
    def test_sanity(self):

        # basic smoke test.
        # this mostly follows the cms_test outline.

        v = ImageCms.versions()  # should return four strings
        self.assertEqual(v[0], '1.0.0 pil')
        self.assertEqual(list(map(type, v)), [str, str, str, str])

        # internal version number
        self.assertRegexpMatches(ImageCms.core.littlecms_version, r"\d+\.\d+$")

        self.skip_missing()
        i = ImageCms.profileToProfile(hopper(), SRGB, SRGB)
        self.assert_image(i, "RGB", (128, 128))

        i = hopper()
        ImageCms.profileToProfile(i, SRGB, SRGB, inPlace=True)
        self.assert_image(i, "RGB", (128, 128))

        t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
        i = ImageCms.applyTransform(hopper(), t)
        self.assert_image(i, "RGB", (128, 128))

        i = hopper()
        t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
        ImageCms.applyTransform(hopper(), t, inPlace=True)
        self.assert_image(i, "RGB", (128, 128))

        p = ImageCms.createProfile("sRGB")
        o = ImageCms.getOpenProfile(SRGB)
        t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
        i = ImageCms.applyTransform(hopper(), t)
        self.assert_image(i, "RGB", (128, 128))

        t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
        self.assertEqual(t.inputMode, "RGB")
        self.assertEqual(t.outputMode, "RGB")
        i = ImageCms.applyTransform(hopper(), t)
        self.assert_image(i, "RGB", (128, 128))

        # test PointTransform convenience API
        hopper().point(t)
Exemplo n.º 22
0
    def __init__(self):
        # load the sRGB2014 ICC color profile
        iccpath = pathlib.Path(
            __file__).absolute().parent / "icc" / "sRGB2014.icc"
        srgb = ImageCms.getOpenProfile(str(iccpath))

        # construct the correct pdf dict. first the output profile
        # N=3 is required for RGB colorspaces
        op = pdfrw.IndirectPdfDict(N=3, Alternate=pdfrw.PdfName("DeviceRGB"))
        op.stream = srgb.tobytes().decode("latin-1")

        # then the outputintents array
        oi = pdfrw.IndirectPdfDict(
            Type=pdfrw.PdfName("OutputIntent"),
            S=pdfrw.PdfName("GTS_PDFA1"),
            OutputConditionIdentifier="sRGB",
            DestOutputProfile=op,
            Info=srgb.profile.profile_description,
            # I am not sure whether this is correct, but it doesn't fail
            RegistryName="http://color.org/srgbprofiles.xalter")
        self.output_intent = [oi]
Exemplo n.º 23
0
def _get_specific_monitor_primaries(filename="./icc_profile/gamut.icc"):
    """
    iccプロファイルからモニターのprimary情報を取得する

    Parameters
    ----------
    filename : string
        filename of the icc profile.

    Returns
    -------
    array_like
        prmaries. [[rx, ry], [gx, gy], [bx, by], [rx, ry]]

    """
    icc_profile = ImageCms.getOpenProfile(filename)
    r = icc_profile.profile.red_primary
    g = icc_profile.profile.green_primary
    b = icc_profile.profile.blue_primary
    primaries = [r[1][:-1], g[1][:-1], b[1][:-1], r[1][:-1]]

    return np.array(primaries)
Exemplo n.º 24
0
    print "buildTransform test completed successfully."

    # and, to clean up a bit, delete the transform
    # this should call the C destructor for the transform structure.
    # Python should also do this automatically when it goes out of scope.
    del (transform)

if TEST_buildTransformFromOpenProfiles == True:
    # we'll actually test a couple profile open/creation functions here too

    # first, get a handle to an input profile, in this case we'll create
    # an sRGB profile on the fly:
    inputProfile = ImageCms.createProfile("sRGB")

    # then, get a handle to the output profile
    outputProfile = ImageCms.getOpenProfile(OUTPUT_PROFILE)

    # make a transform from these
    transform = ImageCms.buildTransformFromOpenProfiles(inputProfile, \
                outputProfile, INMODE, OUTMODE)

    # now, use the trnsform to convert a couple images
    im = Image.open(IMAGE)

    # transform im normally
    im2 = ImageCms.applyTransform(im, transform)
    outputImage(im2, "buildTransformFromOpenProfiles")

    # then do it again using the same transform, this time in-place.
    result = ImageCms.applyTransform(im, transform, inPlace=True)
    outputImage(im, "buildTransformFromOpenProfiles_inPlace")
Exemplo n.º 25
0
def open_profile():
    filename = "./picture/DCI-P3.icc"
    profile = ImageCms.getOpenProfile(filename)
    print(profile.tobytes())
Exemplo n.º 26
0
def test_read_icc_color_profile(heif_file):
    if heif_file.color_profile and heif_file.color_profile["type"] in ["prof", "rICC"]:
        profile = io.BytesIO(heif_file.color_profile["data"])
        cms = ImageCms.getOpenProfile(profile)
Exemplo n.º 27
0
def inspect_static_image(image_path: Path) -> ImageMetadata:
    """Returns all information regarding a single static image

    Args:
        image_path (Path): Path to the image file

    Returns:
        Dict: Information of the static image file
    """
    # image_info = {}
    # im: Image = None
    try:
        # if image_path.__class__.__bases__[0] is ImageFile.ImageFile:
        #     im = image_path
        # else:
        #     im = Image.open(image)
        im = Image.open(image_path)
    except Exception as e:
        stdio.error(str(e).replace("\\\\", "/"))
        return
    fmt = im.format
    exif = ""
    if fmt.upper() != "GIF":
        exif_raw = im._getexif()
        if exif_raw:
            exif = {
                ExifTags.TAGS[k]: v
                for k, v in exif_raw.items() if k in ExifTags.TAGS
            }
    width, height = im.size
    filename = image_path.name
    base_fname = image_path.stem
    ext = image_path.suffix
    base_fname = imageutils.sequence_nameget(base_fname)
    fsize = image_path.stat().st_size
    # fsize_hr = read_filesize(fsize)
    color_mode = COLOR_MODE_FULL_NAME.get(im.mode) or im.mode
    has_transparency = im.info.get(
        "transparency") is not None or im.mode == "RGBA"
    # alpha = im.getchannel('A')
    comment = im.info.get("comment", "")
    icc = im.info.get("icc_profile")
    color_profile = ""
    if icc:
        f = io.BytesIO(icc)
        color_profile = ImageCms.getOpenProfile(f).profile
        # print(color_profile.profile_description)
        stdio.debug({
            "copyright": color_profile.copyright,
            "technology": color_profile.technology,
            "manufacturer": color_profile.manufacturer,
            "creation_date": '',
            "header_manufacturer": color_profile.header_manufacturer,
            "header_model": color_profile.header_model,
            "icc_version": color_profile.icc_version,
            "target": color_profile.target
        })
        color_profile = color_profile.profile_description
    # if palette:
    #     logger.debug(imageutils.reshape_palette(palette))
    #     color_counts = np.array(im.getcolors())
    #     logger.debug(color_counts)
    #     logger.debug(color_counts.sum(axis=0)[0])
    # imageutils.get_palette_image(im).show()
    creation_dt = filehandler.get_creation_time(image_path)
    modification_dt = filehandler.get_modification_time(image_path)
    checksum = filehandler.hash_sha1(image_path)
    # logger.debug({"im.info": im.info, "icc": icc, "palette": imageutils.reshape_palette(palette) if palette else None})
    stdio.debug(im.info)
    if im.mode == "P":
        stdio.debug(im.getpalette())
    im.close()
    metadata = ImageMetadata({
        "name":
        filename,
        "base_filename":
        base_fname,
        "width":
        width,
        "height":
        height,
        "format":
        fmt,
        "fsize":
        fsize,
        "creation_datetime":
        creation_dt.strftime("%Y-%m-%d %H:%M:%S"),
        "modification_datetime":
        modification_dt.strftime("%Y-%m-%d %H:%M:%S"),
        "hash_sha1":
        checksum,
        "absolute_url":
        str(image_path),
        "comments":
        str(comment),
        "color_mode":
        str(color_mode),
        "color_profile":
        color_profile,
        "bit_depth":
        COLOR_MODE_BIT_DEPTH.get(im.mode),
        "has_transparency":
        has_transparency,
        "is_animated":
        False,
        "exif":
        str(exif),
    })
    return metadata
Exemplo n.º 28
0
import numpy
from PIL import ImageCms, ImageDraw, Image, ImageFont, TiffImagePlugin

import io
from TT_sql import TT_sql

style_OK = "color: #cdd6e6;  font-size: 22px; font-family: Arial;"
style_not_OK = "color: #ff0000;  font-size: 22px; font-family: Arial;"
style_norm = "color: #cdd6e6;  font-size: 20px; font-family: Arial; background-color: rgba(55, 55, 68, " \
             "0.4); margin-bottom: 13px; margin-top: 13px; border: 1px solid; border-color: #516588; "
style_warning = "color: #cdd6e6;  font-size: 20px; font-family: Arial; background-color: rgba(55, 55, " \
                "68, 0.4); margin-bottom: 13px; margin-top: 13px; border: 4px solid; border-color: " \
                "#ff0000; "

euroscale_profile = ImageCms.getOpenProfile('icc/CMYK/EuroscaleCoated.icc')
screen_profile = ImageCms.getOpenProfile('icc/RGB/AppleRGB.icc')
image_tag_directory = TiffImagePlugin.ImageFileDirectory_v2()
image_tag_directory[305] = 'LayoutQC'
image_tag_directory[33432] = 'LayoutQC by Fedotov R.'


class Layout:

    def __init__(self, im):
        self.image = im
        self.compression = self.image.info.get('compression')
        # self.profile_ICC = self.image.info.get('icc_profile', '')
        self.resolution = self.image.info.get('dpi')[0]
        self.width_layout = round(self.image.size[0] / self.resolution * 25.4)
        self.height_layout = round(self.image.size[1] / self.resolution * 25.4)
Exemplo n.º 29
0
    def test_extended_information(self):
        self.skip_missing()
        o = ImageCms.getOpenProfile(SRGB)
        p = o.profile

        def assert_truncated_tuple_equal(tup1, tup2, digits=10):
            # Helper function to reduce precision of tuples of floats
            # recursively and then check equality.
            power = 10**digits

            def truncate_tuple(tuple_or_float):
                return tuple(
                    truncate_tuple(val) if isinstance(val, tuple
                                                      ) else int(val * power) /
                    power for val in tuple_or_float)

            self.assertEqual(truncate_tuple(tup1), truncate_tuple(tup2))

        self.assertEqual(p.attributes, 4294967296)
        assert_truncated_tuple_equal(
            p.blue_colorant,
            (
                (0.14306640625, 0.06060791015625, 0.7140960693359375),
                (0.1558847490315394, 0.06603820639433387, 0.06060791015625),
            ),
        )
        assert_truncated_tuple_equal(
            p.blue_primary,
            (
                (0.14306641366715667, 0.06060790921083026, 0.7140960805782015),
                (0.15588475410450106, 0.06603820408959558,
                 0.06060790921083026),
            ),
        )
        assert_truncated_tuple_equal(
            p.chromatic_adaptation,
            (
                (
                    (1.04791259765625, 0.0229339599609375, -0.050201416015625),
                    (0.02960205078125, 0.9904632568359375,
                     -0.0170745849609375),
                    (-0.009246826171875, 0.0150604248046875,
                     0.7517852783203125),
                ),
                (
                    (1.0267159024652783, 0.022470062342089134,
                     0.0229339599609375),
                    (0.02951378324103937, 0.9875098886387147,
                     0.9904632568359375),
                    (-0.012205438066465256, 0.01987915407854985,
                     0.0150604248046875),
                ),
            ),
        )
        self.assertIsNone(p.chromaticity)
        self.assertEqual(
            p.clut,
            {
                0: (False, False, True),
                1: (False, False, True),
                2: (False, False, True),
                3: (False, False, True),
            },
        )

        self.assertIsNone(p.colorant_table)
        self.assertIsNone(p.colorant_table_out)
        self.assertIsNone(p.colorimetric_intent)
        self.assertEqual(p.connection_space, "XYZ ")
        self.assertEqual(p.copyright,
                         "Copyright International Color Consortium, 2009")
        self.assertEqual(p.creation_date,
                         datetime.datetime(2009, 2, 27, 21, 36, 31))
        self.assertEqual(p.device_class, "mntr")
        assert_truncated_tuple_equal(
            p.green_colorant,
            (
                (0.3851470947265625, 0.7168731689453125, 0.097076416015625),
                (0.32119769927720654, 0.5978443449048152, 0.7168731689453125),
            ),
        )
        assert_truncated_tuple_equal(
            p.green_primary,
            (
                (0.3851470888162112, 0.7168731974161346, 0.09707641738998518),
                (0.32119768793686687, 0.5978443567149709, 0.7168731974161346),
            ),
        )
        self.assertEqual(p.header_flags, 0)
        self.assertEqual(p.header_manufacturer, "\x00\x00\x00\x00")
        self.assertEqual(p.header_model, "\x00\x00\x00\x00")
        self.assertEqual(
            p.icc_measurement_condition,
            {
                "backing": (0.0, 0.0, 0.0),
                "flare": 0.0,
                "geo": "unknown",
                "observer": 1,
                "illuminant_type": "D65",
            },
        )
        self.assertEqual(p.icc_version, 33554432)
        self.assertIsNone(p.icc_viewing_condition)
        self.assertEqual(
            p.intent_supported,
            {
                0: (True, True, True),
                1: (True, True, True),
                2: (True, True, True),
                3: (True, True, True),
            },
        )
        self.assertTrue(p.is_matrix_shaper)
        self.assertEqual(p.luminance, ((0.0, 80.0, 0.0), (0.0, 1.0, 80.0)))
        self.assertIsNone(p.manufacturer)
        assert_truncated_tuple_equal(
            p.media_black_point,
            (
                (0.012054443359375, 0.0124969482421875, 0.01031494140625),
                (0.34573304157549234, 0.35842450765864337, 0.0124969482421875),
            ),
        )
        assert_truncated_tuple_equal(
            p.media_white_point,
            (
                (0.964202880859375, 1.0, 0.8249053955078125),
                (0.3457029219802284, 0.3585375327567059, 1.0),
            ),
        )
        assert_truncated_tuple_equal((p.media_white_point_temperature, ),
                                     (5000.722328847392, ))
        self.assertEqual(p.model,
                         "IEC 61966-2-1 Default RGB Colour Space - sRGB")

        self.assertIsNone(p.perceptual_rendering_intent_gamut)

        self.assertEqual(p.profile_description,
                         "sRGB IEC61966-2-1 black scaled")
        self.assertEqual(p.profile_id,
                         b")\xf8=\xde\xaf\xf2U\xaexB\xfa\xe4\xca\x839\r")
        assert_truncated_tuple_equal(
            p.red_colorant,
            (
                (0.436065673828125, 0.2224884033203125, 0.013916015625),
                (0.6484536316398539, 0.3308524880306778, 0.2224884033203125),
            ),
        )
        assert_truncated_tuple_equal(
            p.red_primary,
            (
                (0.43606566581047446, 0.22248840582960838,
                 0.013916015621759925),
                (0.6484536250319214, 0.3308524944738204, 0.22248840582960838),
            ),
        )
        self.assertEqual(p.rendering_intent, 0)
        self.assertIsNone(p.saturation_rendering_intent_gamut)
        self.assertIsNone(p.screening_description)
        self.assertIsNone(p.target)
        self.assertEqual(p.technology, "CRT ")
        self.assertEqual(p.version, 2.0)
        self.assertEqual(p.viewing_condition,
                         "Reference Viewing Condition in IEC 61966-2-1")
        self.assertEqual(p.xcolor_space, "RGB ")
Exemplo n.º 30
0
                    help="don't convert K channels to halftones")
args = parser.parse_args()

# keep フラグの一括セット
if args.keep_all:
    args.keep_red = True
    args.keep_green = True
    args.keep_blue = True
    args.keep_cyan = True
    args.keep_magenta = True
    args.keep_yellow = True
    args.keep_key = True

# ICC プロファイルを読み込む
if args.gray_profile is None:
    gray_profile = ImageCms.getOpenProfile(filerelpath("profiles/sGray.icc"))
else:
    gray_profile = ImageCms.getOpenProfile(args.gray_profile)
if args.input_gray_profile is None:
    in_gray_profile = ImageCms.getOpenProfile(
        filerelpath("profiles/sGray.icc"))
else:
    in_gray_profile = ImageCms.getOpenProfile(args.input_gray_profile)
if args.rgb_profile is None:
    rgb_profile = ImageCms.getOpenProfile(filerelpath("profiles/sRGB.icc"))
else:
    rgb_profile = ImageCms.getOpenProfile(args.rgb_profile)
if args.input_rgb_profile is None:
    in_rgb_profile = ImageCms.getOpenProfile(filerelpath("profiles/sRGB.icc"))
else:
    in_rgb_profile = ImageCms.getOpenProfile(args.input_rgb_profile)
Exemplo n.º 31
0
    print("buildTransform test completed successfully.")

    # and, to clean up a bit, delete the transform
    # this should call the C destructor for the transform structure.
    # Python should also do this automatically when it goes out of scope.
    del(transform)

if TEST_buildTransformFromOpenProfiles == True:
    # we'll actually test a couple profile open/creation functions here too

    # first, get a handle to an input profile, in this case we'll create
    # an sRGB profile on the fly:
    inputProfile = ImageCms.createProfile("sRGB")

    # then, get a handle to the output profile
    outputProfile = ImageCms.getOpenProfile(OUTPUT_PROFILE)

    # make a transform from these
    transform = ImageCms.buildTransformFromOpenProfiles(inputProfile, \
                outputProfile, INMODE, OUTMODE)

    # now, use the trnsform to convert a couple images
    im = Image.open(IMAGE)

    # transform im normally
    im2 = ImageCms.applyTransform(im, transform)
    outputImage(im2, "buildTransformFromOpenProfiles")

    # then do it again using the same transform, this time in-place.
    result = ImageCms.applyTransform(im, transform, inPlace = True)
    outputImage(im, "buildTransformFromOpenProfiles_inPlace")    
Exemplo n.º 32
0
def test_sanity():

    # basic smoke test.
    # this mostly follows the cms_test outline.

    v = ImageCms.versions()  # should return four strings
    assert_equal(v[0], '0.1.0 pil')
    assert_equal(map(type, v), [str, str, str, str])

    # internal version number
    assert_match(ImageCms.core.littlecms_version, "\d+\.\d+$")

    i = ImageCms.profileToProfile(lena(), SRGB, SRGB)
    assert_image(i, "RGB", (128, 128))

    t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
    i = ImageCms.applyTransform(lena(), t)
    assert_image(i, "RGB", (128, 128))

    p = ImageCms.createProfile("sRGB")
    o = ImageCms.getOpenProfile(SRGB)
    t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
    i = ImageCms.applyTransform(lena(), t)
    assert_image(i, "RGB", (128, 128))

    t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
    assert_equal(t.inputMode, "RGB")
    assert_equal(t.outputMode, "RGB")
    i = ImageCms.applyTransform(lena(), t)
    assert_image(i, "RGB", (128, 128))

    # get profile information for file
    assert_equal(
        ImageCms.getProfileName(SRGB).strip(),
        'IEC 61966-2.1 Default RGB colour space - sRGB')
    assert_equal(
        ImageCms.getProfileInfo(SRGB).splitlines(), [
            'sRGB IEC61966-2.1', '',
            'Copyright (c) 1998 Hewlett-Packard Company', '',
            'WhitePoint : D65 (daylight)', '', 'Tests/icc/sRGB.icm'
        ])
    assert_equal(ImageCms.getDefaultIntent(SRGB), 0)
    assert_equal(
        ImageCms.isIntentSupported(SRGB, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
                                   ImageCms.DIRECTION_INPUT), 1)

    # same, using profile object
    p = ImageCms.createProfile("sRGB")
    assert_equal(
        ImageCms.getProfileName(p).strip(), 'sRGB built-in - (lcms internal)')
    assert_equal(
        ImageCms.getProfileInfo(p).splitlines(),
        ['sRGB built-in', '', 'WhitePoint : D65 (daylight)', '', ''])
    assert_equal(ImageCms.getDefaultIntent(p), 0)
    assert_equal(
        ImageCms.isIntentSupported(p, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
                                   ImageCms.DIRECTION_INPUT), 1)

    # extensions
    i = Image.open("Tests/images/rgb.jpg")
    p = ImageCms.getOpenProfile(StringIO(i.info["icc_profile"]))
    assert_equal(
        ImageCms.getProfileName(p).strip(),
        'IEC 61966-2.1 Default RGB colour space - sRGB')

    # the procedural pyCMS API uses PyCMSError for all sorts of errors
    assert_exception(ImageCms.PyCMSError,
                     lambda: ImageCms.profileToProfile(lena(), "foo", "bar"))
    assert_exception(
        ImageCms.PyCMSError,
        lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB"))
    assert_exception(ImageCms.PyCMSError,
                     lambda: ImageCms.getProfileName(None))
    assert_exception(ImageCms.PyCMSError,
                     lambda: ImageCms.isIntentSupported(SRGB, None, None))

    # test PointTransform convenience API
    im = lena().point(t)

    # try fetching the profile for the current display device
    assert_no_exception(lambda: ImageCms.get_display_profile())
Exemplo n.º 33
0
 def Selected_ICC(self, icc):
     self.popUpModal.close()
     profile = ImageCms.getOpenProfile('icc/CMYK/' + icc)
     self.layout.Assign_Icc(profile)
     self.CheckLayOut()
Exemplo n.º 34
0
def test_sanity():

    # basic smoke test.
    # this mostly follows the cms_test outline.

    v = ImageCms.versions() # should return four strings
    assert_equal(v[0], '0.1.0 pil')
    assert_equal(list(map(type, v)), [str, str, str, str])

    # internal version number
    assert_match(ImageCms.core.littlecms_version, "\d+\.\d+$")

    i = ImageCms.profileToProfile(lena(), SRGB, SRGB)
    assert_image(i, "RGB", (128, 128))

    t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
    i = ImageCms.applyTransform(lena(), t)
    assert_image(i, "RGB", (128, 128))

    p = ImageCms.createProfile("sRGB")
    o = ImageCms.getOpenProfile(SRGB)
    t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
    i = ImageCms.applyTransform(lena(), t)
    assert_image(i, "RGB", (128, 128))

    t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
    assert_equal(t.inputMode, "RGB")
    assert_equal(t.outputMode, "RGB")
    i = ImageCms.applyTransform(lena(), t)
    assert_image(i, "RGB", (128, 128))

    # get profile information for file
    assert_equal(ImageCms.getProfileName(SRGB).strip(),
                 'IEC 61966-2.1 Default RGB colour space - sRGB')
    assert_equal(ImageCms.getProfileInfo(SRGB).splitlines(),
                 ['sRGB IEC61966-2.1', '',
                  'Copyright (c) 1998 Hewlett-Packard Company', '',
                  'WhitePoint : D65 (daylight)', '',
                  'Tests/icc/sRGB.icm'])
    assert_equal(ImageCms.getDefaultIntent(SRGB), 0)
    assert_equal(ImageCms.isIntentSupported(
            SRGB, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
            ImageCms.DIRECTION_INPUT), 1)

    # same, using profile object
    p = ImageCms.createProfile("sRGB")
    assert_equal(ImageCms.getProfileName(p).strip(),
                 'sRGB built-in - (lcms internal)')
    assert_equal(ImageCms.getProfileInfo(p).splitlines(),
                 ['sRGB built-in', '', 'WhitePoint : D65 (daylight)', '', ''])
    assert_equal(ImageCms.getDefaultIntent(p), 0)
    assert_equal(ImageCms.isIntentSupported(
            p, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
            ImageCms.DIRECTION_INPUT), 1)

    # extensions
    i = Image.open("Tests/images/rgb.jpg")
    p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
    assert_equal(ImageCms.getProfileName(p).strip(),
                 'IEC 61966-2.1 Default RGB colour space - sRGB')

    # the procedural pyCMS API uses PyCMSError for all sorts of errors
    assert_exception(ImageCms.PyCMSError, lambda: ImageCms.profileToProfile(lena(), "foo", "bar"))
    assert_exception(ImageCms.PyCMSError, lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB"))
    assert_exception(ImageCms.PyCMSError, lambda: ImageCms.getProfileName(None))
    assert_exception(ImageCms.PyCMSError, lambda: ImageCms.isIntentSupported(SRGB, None, None))

    # test PointTransform convenience API
    im = lena().point(t)

    # try fetching the profile for the current display device
    assert_no_exception(lambda: ImageCms.get_display_profile())
Exemplo n.º 35
0
    def load_pil(self, pil_img):
        """
        Load an already opened PIL image.

        Parameters
        ----------
        pil_img : :class:`PIL.Image.Image`
            The image.

        Returns
        -------
        A new :class:`Image`.

        Notes
        -----
        This function should be used instead of :meth:`Image.from_pil` because
        may postprocess the image in various ways, depending on the loader
        configuration.

        """
        # If we're cropping, do it.
        if self.crop is not None:
            upper = self.crop[0]
            right = pil_img.width - self.crop[1]
            lower = pil_img.height - self.crop[2]
            left = self.crop[3]

            # This operation can trigger PIL decompression-bomb aborts, so
            # avoid them in the standard, non-thread-safe, way.
            old_max = pil_image.MAX_IMAGE_PIXELS
            try:
                pil_image.MAX_IMAGE_PIXELS = None
                pil_img = pil_img.crop((left, upper, right, lower))
            finally:
                pil_image.MAX_IMAGE_PIXELS = old_max

        # If an unrecognized mode, try to standardize it. The weird PIL modes
        # don't generally support an alpha channel, so we convert to RGB.

        try:
            ImageMode(pil_img.mode)
        except ValueError:
            print(
                'warning: trying to convert image file to RGB from unexpected bitmode "%s"'
                % pil_img.mode)

            if self.black_to_transparent:
                # Avoid double-converting in the next filter.
                pil_img = pil_img.convert('RGBA')
            else:
                pil_img = pil_img.convert('RGB')

        # Convert pure black to transparent -- make sure to do this before any
        # colorspace processing.
        #
        # As far as I can tell, PIL has no good way to modify an image on a
        # pixel-by-pixel level in-place, which is really annoying. For now I'm
        # doing this processing in Numpy space, but for an image that almost
        # fills up memory we might have to use a different approach since this
        # one will involve holding two buffers at once.

        if self.black_to_transparent:
            if pil_img.mode != 'RGBA':
                pil_img = pil_img.convert('RGBA')
            a = np.asarray(pil_img)
            a = a.copy()  # read-only buffer => writeable

            for i in range(a.shape[0]):
                nonblack = (a[i, ..., 0] > 0)
                np.logical_or(nonblack, a[i, ..., 1] > 0, out=nonblack)
                np.logical_or(nonblack, a[i, ..., 2] > 0, out=nonblack)
                a[i, ..., 3] *= nonblack

            # This is my attempt to preserve the image metadata and other
            # attributes, swapping out the pixel data only. There is probably
            # a better way to do this
            new_img = pil_image.fromarray(a, mode=pil_img.mode)
            pil_img.im = new_img.im
            del a, new_img

        # Make sure that we end up in the right color space. From experience, some
        # EPO images have funky colorspaces and we need to convert to sRGB to get
        # the tiled versions to appear correctly.

        if self.colorspace_processing != 'none' and 'icc_profile' in pil_img.info:
            assert self.colorspace_processing == 'srgb'  # more modes, one day?

            try:
                from PIL import ImageCms
                # ImageCms doesn't raise import error if the implementation is unavailable
                # "for doc purposes". To see if it's available we need to actually try to
                # do something:
                out_prof = ImageCms.createProfile('sRGB')
            except ImportError:
                print(
                    '''warning: colorspace processing requested, but no `ImageCms` module found in PIL.
    Your installation of PIL probably does not have colorspace support.
    Colors will not be transformed to sRGB and therefore may not appear as intended.
    Compare toasty's output to your source image and decide if this is acceptable to you.
    Consider a different setting of the `--colorspace-processing` argument to avoid this warning.''',
                    file=sys.stderr)
            else:
                from io import BytesIO
                in_prof = ImageCms.getOpenProfile(
                    BytesIO(pil_img.info['icc_profile']))
                xform = ImageCms.buildTransform(in_prof, out_prof,
                                                pil_img.mode, pil_img.mode)
                ImageCms.applyTransform(pil_img, xform, inPlace=True)

        return Image.from_pil(pil_img)
Exemplo n.º 36
0
for i in images:
    gc.collect()
    im = Image.open(i)

    #~ new_height = 1200
    #~ new_width  = new_height * width / height

    #~ new_width  = 1200
    #~ new_height = new_width * height / width

    #~ height = im.size[0]
    #~ width = im.size[1]

    if im.mode is not 'RGB':
        print(i + ' is ' + im.mode)
        popa = ImageCms.getOpenProfile(SRGB_PROFILE)
        popa2 = ImageCms.getOpenProfile(CMYK_PROFILE)
        trans = ImageCms.buildTransform(popa2, popa, 'CMYK', 'RGB')
        convo = ImageCms.applyTransform(im, trans)
        #~ convo = convo.resize([new_height, new_width] , Image.ANTIALIAS)
        #~ cdata = list(convo.getdata())
        #~ nimage = Image.new('RGB',im.size)
        #~ nimage.putdata(cdata)
        #~ nimage.save('ready/'+i, 'JPEG', quality=95, dpi=(72,72))
        convo.save('ready/' + i, 'JPEG', quality=100, dpi=(72, 72))
        convo.close()
        #~ time.sleep(5)
    else:
        print(i + ' is ' + im.mode)
        #~ cdata = list(im.getdata())
        #~ nimage = Image.new('RGB',im.size)