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)
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)
# 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") print("buildTransformFromOpenProfiles test completed successfully.") # and, to clean up a bit, delete the transform
import sys sys.path.insert(0, ".") from PIL import Image from PIL import ImageCms try: filename = sys.argv[1] except IndexError: filename = "../pil-archive/cmyk.jpg" i = Image.open(filename) print i.format print i.mode print i.size print i.tile p = ImageCms.getMemoryProfile(i.info["icc_profile"]) print repr(p.product_name) print repr(p.product_info) o = ImageCms.createProfile("sRGB") t = ImageCms.buildTransformFromOpenProfiles(p, o, i.mode, "RGB") i = ImageCms.applyTransform(i, t) i.show()
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())
import os from PIL import Image as Im from PIL import ImageCms as ImCms from PIL import ImageFilter slash = "\\" if os.name == 'nt' else "/" radius_count = 0 radius_sum = 0 # Profiles srgb_p = ImCms.createProfile("sRGB") lab_p = ImCms.createProfile("LAB") # Conversion Profiles rgb2lab = ImCms.buildTransformFromOpenProfiles(srgb_p, lab_p, "RGB", "LAB") lab2rgb = ImCms.buildTransformFromOpenProfiles(lab_p, srgb_p, "LAB", "RGB") def check_file_count(input_folder): file_count = 0 for root, dirs, files in os.walk(input_folder): for file in files: file_count += 1 return file_count def process(input_folder): file_count = check_file_count(input_folder) index = 1 failed_index = 0
from PIL import Image, ImageMath, ImageColor, ImageCms, ImageDraw, ImageFont, ImageFilter from colormath.color_objects import LabColor, sRGBColor from colormath.color_conversions import convert_color import math srgb_profile = ImageCms.createProfile('sRGB') lab_profile = ImageCms.createProfile('LAB') rgb2lab_transform = ImageCms.buildTransformFromOpenProfiles( srgb_profile, lab_profile, 'RGB', 'LAB') lab2rgb_transform = ImageCms.buildTransformFromOpenProfiles( lab_profile, srgb_profile, 'LAB', 'RGB') GMK_LABELS = ('GMK', 'DCS', 'OEM') class Key(object): __slots__ = [ 'u', 'base_color', 'x', 'y', 'x2', 'y2', 'width', 'height', 'width2', 'height2', 'color', 'font_color', 'labels', 'align', 'font_size', 'font_size2', 'rotation_angle', 'rotation_x', 'rotation_y', 'profile', 'nub', 'ghost', 'stepped', 'decal' ] def __init__(self): self.u = 200 self.base_color = 0xE0 self.x = 0.0 self.y = 0.0 self.x2 = 0.0
""" Transformations in PIL. """ import numpy as np import random from PIL import Image as PilImage from PIL import ImageCms from kernelphysiology.utils import imutils rgb_p = ImageCms.createProfile('sRGB') lab_p = ImageCms.createProfile('LAB') rgb2lab = ImageCms.buildTransformFromOpenProfiles(rgb_p, lab_p, 'RGB', 'LAB') lab2rgb = ImageCms.buildTransformFromOpenProfiles(lab_p, rgb_p, 'LAB', 'RGB') class ColourTransformation(object): def __init__(self, colour_inds, colour_space='rgb'): self.colour_inds = colour_inds self.colour_space = colour_space def __call__(self, img): if self.colour_space == 'lab' or self.colour_inds is not None: img = ImageCms.applyTransform(img, rgb2lab) if self.colour_inds is not None: img = np.asarray(img).copy() # TODO: 0 contrast lightness means all to be 50
from PIL import Image, ImageCms import sys if len(sys.argv) < 2: print("Give the filename as an argument") filename = sys.argv[1] im = Image.open(filename) if im.mode != "RGB": im = im.convert("RGB") srgb_profile = ImageCms.createProfile("sRGB") lab_profile = ImageCms.createProfile("LAB") rgb2lab_transform = ImageCms.buildTransformFromOpenProfiles( srgb_profile, lab_profile, "RGB", "LAB") lab_im = ImageCms.applyTransform(im, rgb2lab_transform) lab_im.save('worker.tiff')
# 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") print "buildTransformFromOpenProfiles test completed successfully." # and, to clean up a bit, delete the transform
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())
def bepaalWaardenEnPasAan(dir, name): # Inlezen file im = Image.open(dir + "/" + name) if im.mode != "RGB": im = im.convert("RGB") srgb_profile = ImageCms.createProfile("sRGB") lab_profile = ImageCms.createProfile("LAB") rgb2lab_transform = ImageCms.buildTransformFromOpenProfiles(srgb_profile, lab_profile, "RGB", "LAB") lab_im = ImageCms.applyTransform(im, rgb2lab_transform) w, h = lab_im.size labColors = lab_im.getcolors(w * h) labColorsGereduceerd = {} for color in labColors: npColor = np.array([round(color[1][0], -1), round(color[1][1], -1), round(color[1][2], -1)]) colorHash = npColor[0] // 10 + npColor[1] * 30 + npColor[2] * 9000 aant = color[0] if colorHash in labColorsGereduceerd: labColorsGereduceerd[colorHash][0] = labColorsGereduceerd[colorHash][0] + aant else: labColorsGereduceerd[colorHash] = [aant, npColor] print(str(len(labColorsGereduceerd))) colorParametersList = [ColorParameters(origineel=colorGereduceerd[0], npColor=colorGereduceerd[1]) for colorGereduceerd in labColorsGereduceerd.values()] for eigen in colorParametersList: for buur in colorParametersList: afstand = np.linalg.norm(eigen.npColor - buur.npColor) # math.sqrt 60.234 if afstand > 0: eigen.waardeGecorrigeerd = eigen.waardeGecorrigeerd + buur.waardeOrigineel // afstand else: eigen.waardeGecorrigeerd = eigen.waardeGecorrigeerd + buur.waardeOrigineel wegstreeplijst = sorted(colorParametersList, key=lambda x: x.waardeGecorrigeerd, reverse=True) # belangrijkste kleuren hoofdkleurenLijst = [] while len(wegstreeplijst) > 0: hoofdKleur = wegstreeplijst[0] wegstreeplijst.remove(hoofdKleur) for kleur in wegstreeplijst: if np.linalg.norm(hoofdKleur.npColor - kleur.npColor) < 70: kleur.vervangenDoor = hoofdKleur hoofdKleur.vervangt.append(kleur) wegstreeplijst.remove(kleur) else: kleur.afstand = kleur.waardeGecorrigeerd * afstand hoofdkleurenLijst.append(hoofdKleur) wegstreeplijst.sort(key=lambda x: x.afstand_kwadraad, reverse=True) print(len(wegstreeplijst)) print(len(hoofdkleurenLijst)) i = 1 # foto aanpassen op basis van de lijst pixOud = lab_im.load() lab2rgb_transform = ImageCms.buildTransformFromOpenProfiles(lab_profile, srgb_profile, "LAB", "RGB") vervangDict = {} for color in colorParametersList: vervangDict[(color.npColor, color.b)] = color.vervangenDoor now = datetime.datetime.now().strftime('%Y%m%d %H%M%S') imgNew = Image.new('LAB', (w, h), (255, 255, 255)) pixNew = imgNew.load() for x in range(w): for y in range(h): L, A, B = pixOud[x, y] vervangColor = vervangDict[(A, B)] pixNew[x, y] = (L, vervangColor.a, vervangColor.b) imgRGB = ImageCms.applyTransform(imgNew, lab2rgb_transform) imgRGB.save(dir + "/" + name + now + " vervangenVolgensMap.JPG")
def __init__(self): self.t = ImageCms.buildTransformFromOpenProfiles( srgb_profile, lab_profile, "RGB", "LAB")
def bepaalWaardenEnPasAan(dir, name): #Inlezen file im = Image.open(dir + "/" + name) if im.mode != "RGB": im = im.convert("RGB") srgb_profile = ImageCms.createProfile("sRGB") lab_profile = ImageCms.createProfile("LAB") rgb2lab_transform = ImageCms.buildTransformFromOpenProfiles(srgb_profile, lab_profile, "RGB", "LAB") lab_im = ImageCms.applyTransform(im, rgb2lab_transform) w, h = lab_im.size labColors = lab_im.getcolors(w*h) labColorsGeenLD = {} for color in labColors: col = (color[1][1],color[1][2]) aant = color[0] if col in labColorsGeenLD: labColorsGeenLD[col] = labColorsGeenLD[col] + aant else: labColorsGeenLD[col] = aant print(str(len(labColorsGeenLD))) colorParametersList = [] for (a,b) , aant in labColorsGeenLD.items(): colorParametersList.append(ColorParameters(a,b,aant)) wegstreeplijst = sorted(colorParametersList, key=lambda x: x.waardeGecorrigeerd, reverse=True) for eigen in wegstreeplijst: eigen.verdeeldNu = float(eigen.waardeOrigineel) for buur in colorParametersList: afstand = int(hypot((eigen.a - buur.a), (eigen.b - buur.b))) # math.sqrt 60.234 if afstand < 5: eigen.buren.append(buur) teller = 1 while len(wegstreeplijst) > 1: print("iteratie " + str(teller)) teller = teller + 1 for eigen in wegstreeplijst: if len(eigen.buren) == 0 or eigen.verdeeldNu < 50: for buur in eigen.buren: buur.buren.remove(eigen) wegstreeplijst.remove(eigen) else: vraag = 0 for buur in eigen.buren: vraag = vraag + buur.verdeeldNu bijdrage = eigen.verdeeldNu // (vraag * 2) for buur in eigen.buren: buur.verdeeldStraks = buur.verdeeldStraks + buur.verdeeldNu * bijdrage for eigen in wegstreeplijst: eigen.verdeeldNu = eigen.verdeeldStraks eigen.verdeeldStraks = eigen.verdeeldStraks // 2 #toekennen nevenkleuren aan hoofdkleur wegstreeplijst = sorted(colorParametersList, key=lambda x: x.verdeeldStraks, reverse=True) hoofdkleurenLijst = wegstreeplijst[:7] wegstreeplijst = wegstreeplijst[7:] for eigen in wegstreeplijst: minAfstand =10000000 for hoofdKleur in hoofdkleurenLijst: if minAfstand > int(hypot((eigen.a - hoofdKleur.a), (eigen.b - hoofdKleur.b))): minAfstand = int(hypot((eigen.a - hoofdKleur.a), (eigen.b - hoofdKleur.b))) eigen.vervangenDoor = hoofdKleur hoofdKleur.vervangt.append(eigen) #foto aanpassen op basis van de lijst pixOud = lab_im.load() lab2rgb_transform = ImageCms.buildTransformFromOpenProfiles(lab_profile, srgb_profile, "LAB", "RGB") vervangDict = {} for color in colorParametersList: vervangDict[(color.a, color.b)] = color.vervangenDoor now = datetime.datetime.now().strftime('%Y%m%d %H%M%S') imgNew = Image.new('LAB', (w, h), (255, 255, 255)) pixNew = imgNew.load() for x in range(w): for y in range(h): L,A,B = pixOud[x,y] vervangColor = vervangDict[(A,B)] pixNew[x,y] = (L, vervangColor.a, vervangColor.b) imgRGB = ImageCms.applyTransform(imgNew, lab2rgb_transform) imgRGB.save(dir + "/" + name + now + " vervangenVolgensMap.JPG")
def bepaalWaardenEnPasAan(dir, name, sampleSize): # Inlezen file im = Image.open(dir + "/" + name) if im.mode != "RGB": im = im.convert("RGB") srgb_profile = ImageCms.createProfile("sRGB") lab_profile = ImageCms.createProfile("LAB") rgb2lab_transform = ImageCms.buildTransformFromOpenProfiles( srgb_profile, lab_profile, "RGB", "LAB") lab_im = ImageCms.applyTransform(im, rgb2lab_transform) w, h = lab_im.size labColors = lab_im.getcolors(w * h) npImageOrig = np.array(lab_im) npImage = npImageOrig.reshape(w * h, 3) pdImage = pd.DataFrame(npImage, columns=['L', 'A', 'B']) kmeans = KMeans(n_clusters=aantalKleuren) kmeans.fit(pdImage) y_kmeans = kmeans.predict(pdImage) npCenters = kmeans.cluster_centers_.astype(int) if sampleSize > pdImage['L'].size: sampleSize = pdImage['L'].size selectie = random.sample(list(range(0, pdImage['L'].size)), sampleSize) L = pdImage.iloc[selectie, 0] A = pdImage.iloc[selectie, 1] B = pdImage.iloc[selectie, 2] C = y_kmeans[selectie] fig, ax = plt.subplots() ax.scatter(L, A, c=C, s=50, cmap='viridis') ax.set_xlabel('L') ax.set_ylabel('A') ax.scatter(npCenters[:, 0], npCenters[:, 1], c='black', s=200, alpha=0.5) plt.show() fig, ax = plt.subplots() ax.scatter(L, B, c=C, s=50, cmap='viridis') ax.set_xlabel('L') ax.set_ylabel('B') ax.scatter(npCenters[:, 0], npCenters[:, 2], c='black', s=200, alpha=0.5) plt.show() fig, ax = plt.subplots() ax.scatter(A, B, c=C, s=50, cmap='viridis') ax.set_xlabel('A') ax.set_ylabel('B') ax.scatter(npCenters[:, 1], npCenters[:, 2], c='black', s=200, alpha=0.5) plt.show() pdImage['groep'] = y_kmeans groepen = list(range(0, aantalKleuren)) pdCenters = pd.DataFrame(npCenters, columns=['Ln', 'An', 'Bn']) pdCenters['groep'] = groepen pdImageTransform = pdImage.join(pdCenters.set_index('groep'), on='groep') pdImageNieuw = pdImageTransform.iloc[:, 4:7] npImageNieuw = pdImageNieuw.to_numpy() npImageNieuw = npImageNieuw.reshape(h, w, 3, order="C") imageNiew = Image.fromarray(numpy.uint8(npImageNieuw), mode='LAB') lab2rgb_transform = ImageCms.buildTransformFromOpenProfiles( lab_profile, srgb_profile, "LAB", "RGB") imgRGB = ImageCms.applyTransform(imageNiew, lab2rgb_transform) now = datetime.datetime.now().strftime('%Y%m%d %H%M%S') imgRGB.save(dir + "/" + name + now + " vervangenVolgensMapC.JPG") # Exporteren van kleuren en tellingen npImageRGB = np.array(imgRGB) npImageRGB = npImageRGB.reshape(w * h, 3) pdImageRGB = pd.DataFrame(npImageRGB, columns=['R', 'G', 'B']) pdImageRGB['aantal'] = 1 export = pdImageRGB.groupby(['R', 'G', 'B'])['aantal'].count().reset_index() print(export) export.to_csv(name + now + '.csv')
def bepaalWaardenEnPasAan(dir, name): #Inlezen file im = Image.open(dir + "/" + name) if im.mode != "RGB": im = im.convert("RGB") srgb_profile = ImageCms.createProfile("sRGB") lab_profile = ImageCms.createProfile("LAB") rgb2lab_transform = ImageCms.buildTransformFromOpenProfiles( srgb_profile, lab_profile, "RGB", "LAB") lab_im = ImageCms.applyTransform(im, rgb2lab_transform) w, h = lab_im.size labColors = lab_im.getcolors(w * h) labColorsGeenLD = {} for color in labColors: col = (color[1][1], color[1][2]) aant = color[0] if col in labColorsGeenLD: labColorsGeenLD[col] = labColorsGeenLD[col] + aant else: labColorsGeenLD[col] = aant print(str(len(labColorsGeenLD))) colorParametersList = [] for (a, b), aant in labColorsGeenLD.items(): colorParametersList.append(ColorParameters(a, b, aant)) for eigen in colorParametersList: for buur in colorParametersList: afstand = int(hypot((eigen.a - buur.a), (eigen.b - buur.b))) # math.sqrt 60.234 if afstand > 0: eigen.waardeGecorrigeerd = eigen.waardeGecorrigeerd + buur.waardeOrigineel // afstand else: eigen.waardeGecorrigeerd = eigen.waardeGecorrigeerd + buur.waardeOrigineel wegstreeplijst = sorted(colorParametersList, key=lambda x: x.waardeGecorrigeerd, reverse=True) #belangrijkste kleuren hoofdkleurenLijst = [] while len(wegstreeplijst) > 0: hoofdKleur = wegstreeplijst[0] wegstreeplijst.remove(hoofdKleur) for kleur in wegstreeplijst: if int(hypot((hoofdKleur.a - kleur.a), (hoofdKleur.b - kleur.b))) < 70: kleur.vervangenDoor = hoofdKleur hoofdKleur.vervangt.append(kleur) wegstreeplijst.remove(kleur) else: kleur.afstand = kleur.waardeGecorrigeerd * afstand hoofdkleurenLijst.append(hoofdKleur) wegstreeplijst.sort(key=lambda x: x.afstand_kwadraad, reverse=True) print(len(wegstreeplijst)) print(len(hoofdkleurenLijst)) i = 1 #foto aanpassen op basis van de lijst pixOud = lab_im.load() lab2rgb_transform = ImageCms.buildTransformFromOpenProfiles( lab_profile, srgb_profile, "LAB", "RGB") vervangDict = {} for color in colorParametersList: vervangDict[(color.a, color.b)] = color.vervangenDoor now = datetime.datetime.now().strftime('%Y%m%d %H%M%S') imgNew = Image.new('LAB', (w, h), (255, 255, 255)) pixNew = imgNew.load() for x in range(w): for y in range(h): L, A, B = pixOud[x, y] vervangColor = vervangDict[(A, B)] pixNew[x, y] = (L, vervangColor.a, vervangColor.b) imgRGB = ImageCms.applyTransform(imgNew, lab2rgb_transform) imgRGB.save(dir + "/" + name + now + " vervangenVolgensMap.JPG")
import sys sys.path.insert(0, ".") from PIL import Image from PIL import ImageCms try: filename = sys.argv[1] except IndexError: filename = "../pil-archive/cmyk.jpg" i = Image.open(filename) print(i.format) print(i.mode) print(i.size) print(i.tile) p = ImageCms.getMemoryProfile(i.info["icc_profile"]) print(repr(p.product_name)) print(repr(p.product_info)) o = ImageCms.createProfile("sRGB") t = ImageCms.buildTransformFromOpenProfiles(p, o, i.mode, "RGB") i = ImageCms.applyTransform(i, t) i.show()
def __init__(self): srgb_profile = ImageCms.createProfile('sRGB') lab_profile = ImageCms.createProfile('LAB') self.rgbscale = ImageCms.buildTransformFromOpenProfiles( lab_profile, srgb_profile, 'LAB', 'RGB')