Halloween Costume ideas 2015

PYTHON / Digging Dolf Veenvliet KULER Script

Blender is Kuler.
Today, I am doing something that is a little random (like usual), but slightly more random than usual.

GETTING ONLINE DATA
I was curious on how Python module (inside or outside Blender) can source data or information from the Internet and then using the data to create visualization. I think there is an enormous potential here. I am not quite sure how, but I want to dig this idea further, even with my limited Python knowledge.

Not quite sure where to start, but I choose a random topic: Adobe Kuler.

WHAT IS ADOBE KULER?
From the Wiki:
http://en.wikipedia.org/wiki/Adobe_Kuler

I remember Adobe Kuler from the time when I was just a graphic design student. From what I remember, this is a kind of experimental website from Adobe that allows user to explore color online.


Well, since Kuler is available online, why don't we use it?

You could always sample the color manually, but we like to do some bit of Python magic here to sample the color automatically via RSS.

By coincidence, I also stumbled into this:
http://i-create.org/2008/10/13/generative-art-with-kuler/
http://mos.futurenet.com/pdf/computerarts/ART145_tut_3.pdf

Interesting reads on using Adobe Kuler to create "generative art" and I think we can use the similar idea in Blender, right?

PYTHON KULER
I have a feeling that someone out there must have created a script that can SOURCE some data from Adobe Kuler. I am hoping for some kind of Python module that does exactly that.

So, like always, I start from Google Search: python adobe kuler.

A quick glance at the search result, I found out there are few Python module that kind of related to Kuler, but this one catches my eyes (because it leads to Blender directly):
https://code.google.com/p/macouno/source/browse/trunk/Blender/modules/macouno/colour.py?r=11

I checked that link and it comes to my surprise, this script is related to some kind of WIP project by Dolf Veenvliet.



ARTIST/DESIGNER: DOLF VEENVLIET

I don't know Dolf in person, but I remember his name from his Blender project "Entoforms".
http://www.entoforms.com/

You gotta check this video based on that "Entoforms":
https://www.youtube.com/watch?v=HqFQ4w8_4pM

All those randomly generated "DNA Creature" is created procedurally, using Python, I believe.

I read all about it when I first started using Blender few years ago. Dolf's website/blog: (also full of useful information):
http://www.macouno.com/

By coincident, I am actually waiting for his DVD on Blender 3D Printing:
http://www.blender3d.org/e-shop/product_info_n.php?products_id=160

I have big respect on this artist/developer, seems brilliant in both creative and technical ability and his works using Blender is kind of inspiring.

BACK TO KULER SCRIPT
Anyways, part of Dolf code that I am most interested in at the moment:



At first, I have no idea how to use the script. I actually asked Dolf via his Facebook, but I am not getting any reply. Maybe he is busy.... (see update below)

#------------------------------------------------------------------------------------------------#
UPDATE 2013.05.09:
Dolf did actually reply my message a bit later after I wrote this!

Here is what he said:

The way you linked the script into Blender. On the google page there is the "modules" folder that you found, but there is also an addons folder and a startup folder.
The way I use them is that somewhere on my computer I have a personal python scripts folder... and in there are all these folders... an addons folder, a modules folder and a startup folder. Exactly as those on the google page and those in the scripts folder of your blender installer. In the User preferences I have that personal scripts folder set as the "Scripts" folder... in my case that is: D:\Work\Python_scripts\Blender\
The result is... that everything in my personal modules folder is loaded as soon as blender starts, and can be used by all of the addons/scripts in the addons folder and startup folder.
The palletes function in the colour module was made to be used by the palettes.py script in the startup folder.
In your case... all you'd have to do to get it working how I have it is copy my palletes.py script to your startup folder (I think).
If you have it set up that way... a big button can be found at the bottom of the scene settings... it says "get palettes" and when you click it it retrieves the palettes just like you did from commandline. If you use that button...it also shows up in the tool shelf, and you can set how many days back you want to get the palettes from and how you want to filter them.
The data generated by the palettes function was used when generating he Entoforms. A random palette from kuler is always prettier than a random generated palette. As long as you use an entire palette, and not mix them.


#------------------------------------------------------------------------------------------------#


Before Dolf reply letter above, I decided to dig and "hack" into the code myself. I will take you through it, hopefully you can learn something here.

IMPORTING PACKAGE AND MODULE
This is kind of new for me. Thanks to David Vega, apparently we can import a Package or Bundle (folder) that is full of Python scripts.

So, from that Google Source Code of Dolf, I first download the whole directory with all the scripts:
Dolf's Macouno Module
I download it into a folder, name the folder Macouno and put it under Blender addon directory. I am using Blender 2.67 which I just installed earlier this morning:

IMPORT MACOUNO IN BLENDER
Now, we are ready to further explore this inside Blender.

When doing this exploration in Python, I usually use this Python Console to test single liner code:


If the module is not loaded properly, you can do this below:
import macouno.colour()

Now we know it is working we can explore that one script we interested in: get_palettes()


I read the code a little bit. So I kind of know the get_palettes() has default arguments, so we can simply call this function and see what happened.

I tried running the function in Python Console.

Interesting enough, it seems to collect something (from Internet!) and return something. I don't know what it is, so I read the code again, and found this part:

Interesting... apparently this script attaches something into bpy.context.scene, something called 'palettes'.

I am guessing it is a type of DICTIONARY. I did not know we can easily attach data like that into Blender scene context. I guess, we learn more things already.

Next, I am digging into this 'palettes' DICTIONARY data:

A bit about DICTIONARY in Python:
From my understanding, Dictionary is a type of data which contains a list or collection of KEYS and VALUES pair (called ITEMS). KEYS and VALUES can be anything: String, Float, Integer, List, or even another Dictionary (nested Dictionary inside Dictionary).

So, Dictionary is great that it can act like a mini database.

For example:
my_color_dict = {'ocean':'blue', 'fire':'red', 'sun': 'yellow'}
my_farm_dict = {'chicken':4, 'pig':2, 'cow': 4}
my_friend_data = {'bob':{'job':'teacher', 'location':'Sydney'}, 'joanna':{'job':'artist', 'location':'Melbourne'}}




The Kuler Dictionary created by using Dolf get_palettes() in fact looks like below:

bpy.ops.wm.properties_edit(data_path="scene", property="palettes", value="{'p': {'swatches': [['1.0', '0.94004', '0.050797'], ['0.7975', '0.91', '0.046225'], ['0.569211', '1.0', '0.100797'], ['0.0414', '1.0', '0.178867'], ['0.194867', '0.91', '0.046225']], 'id': '2433915', 'author': 'tkthathsara888', 'title': 'Green 2 Yellow', 'hexes': ['FFF00D', 'CBE80C', '91FF1A', '0BFF2E', '32E80C']}, 'q': {'swatches': [['0.094118', '0.290196', '0.54902'], ['0.094118', '0.337255', '0.54902'], ['0.635294', '0.65098', '0.266667'], ['0.94902', '0.886275', '0.019608'], ['0.94902', '0.796078', '0.019608']], 'id': '2433913', 'author': 'gal3rielol', 'title': 'EU in China', 'hexes': ['184A8C', '18568C', 'A2A644', 'F2E205', 'F2CB05']}, 'r': {'swatches': [['0.91', '0.255261', '0.153506'], ['1.0', '0.485695', '0.171846'], ['1.0', '0.118688', '0.450941'], ['0.821215', '0.153506', '0.91'], ['0.522373', '0.168688', '1.0']], 'id': '2433910', 'author': 'tkthathsara888', 'title': 'Base Colour', 'hexes': ['E84127', 'FF7C2C', 'FF1E73', 'D127E8', '852BFF']}, 's': {'swatches': [['0.49829', '0.75', '0.061756'], ['0.9", min=-1e+009, max=1e+009, description="")

Now we know the contents of the Dictionary:

There are 20 Kuler data slots in total (a-o).

Each contains information below:
1. author --> creator of Kuler
2. hexes --> 3 color in hexes
3. id --> kuler ID
4. swatches --> RGB version
5. title --> name of Kuler


SNIPPET: HEX TO RGB 
http://stackoverflow.com/questions/4296249/how-do-i-convert-a-hex-triplet-to-an-rgb-tuple-and-back

USING THE KULER DICTIONARY DATA
Ok, now we are ready to actually use the Kuler data.

Before doing that, we will summarize what we have so far into a STARTER CODE:


NOTE: Somewhat I need to do that above in Console before I can run the script below, every time Blender is run from scratch.

Maybe the setup is not 100% correct. Anyways, it will work fine if you do the module imports above, and then you can copy paste the script below to test.

import bpy
import macouno as dolf

# Run this once, enough to collect Kuler color data of the day
if not ('palettes' in bpy.context.scene):
    dolf.colour.get_palettes()

Easy and simple enough. The next step is to simply use the data. It is the fun part.

I will just keep it simple, just to write codes that does this:
1. Create 5 Materials to be recycled, of which each Diffuse Color is applied with Kuler 5 colors. Run this code one time only.

def createFiveKulerMaterials():        
    # Create 5 Materials:
    for i in range(5):
        mat = bpy.data.materials.new('kuler.{i}'.format(i=i))
        
createFiveKulerMaterials()

# 5 materials created, named kuler.0, kuler.1, kuler.2, kuler.3, kuler.4.


2. Next, apply Kuler colors into the 5 Materials based on the dictionary slot. With the code below you can run as many time as you pleased. You just need to supply an argument (alphabet).


def applyKuler(alphabet='a'):
    # Apply the 5 Kuler colors into the Material Diffuse Color
     
    myColorList = bpy.context.scene['palettes'][alphabet]['swatches']
    
    for num, color in enumerate(myColorList):
        #mat = bpy.data.materials.new('kuler{num}'.format(num=num))
        mat = bpy.data.materials['kuler.{num}'.format(num=num)]
        print(color)
        mat.diffuse_color = float(color[0]), float(color[1]), float(color[2])
        
applyKuler('c')
applyKuler('a')
applyKuler('j')

3. Assign Kuler Materials manually
The next step, simply manually assign the 5 Kuler Materials into 3D model that you have in the scene. This of course can be automated with Python, if you like.
Now you can see the resulting Kuler colors, everytime you tell Blender to check in Kuler dictionary.




Unlike total random of RGB color or HSV color, the (random) Kuler colors we have here is more like a limited Palette of 5 colors, but has been carefully chosen by artists/designers out there. They are supposedly more pleasing to eyes, well it all depends on the context and your mood or what you like to apply the color into. This kind of thing is applicable to graphic design, interior design, etc.

Testing flat Kuler color Material with FREESTYLE Strokes.
4. More Code Snippet: Text to Display Name of the Swatch

# Display Title of Kuler
myKulerTitleList = bpy.context.scene['palettes'][alphabet]['title']
bpy.data.objects["Title"].data.body = myKulerTitleList

# SOURCE: http://www.blender.org/forum/viewtopic.php?t=22407&sid=abb1d235e26746b57ac1077e7da9f825







CREATE GUI?
I have not studied Blender GUI yet (maybe something to look into next).

What would be nice is to create GUI where user can randomly get Kuler color when a button is clicked. Or maybe goes cycling over the range of Kuler colors we have inside Dictionary.

CONCLUSION
Hopefully this one is also useful for you: artists without programming or computer science background. The idea can be expanded further.

Dolf's Kuler script has input arguments that can give you more Kuler colors based on your specification.

So basically, as long we are able to source data from Internet and turn it into some kind of nice and tidy Dictionary format like what Dolf done with Kuler thing, you can then simply use the data further to create visualization in Blender.

The Art of Data Visualization | Off Book | PBS
http://www.youtube.com/watch?v=AdSZJzb-aX8&feature=player_embedded

There are still heaps of things to learn and discover in Blender, Python and Computer Graphics as a whole. Reading someone else's Python scripts is actually can be as fun as reading a good comic books or interactive story, as long you understand or figuring what the code is doing.

Thanks to Dolf, Suzanne is KULER-ed!

UPDATE 2013.06.29 / Importing Adobe Kuler ASE (Adobe Swatch Exchange) using Python into Blender

Between Adobe Kuler and its Adobe applications (Photoshop, Illustrator, InDesign, etc), Adobe is using ASE file format to exchange the Swatches.

I was curious this morning on whether we can use Python to parse ASE file. If you have iPhone app "Adobe Kuler", you can quickly scan anything via the iPhone camera and sample 5 colors, then save the result into Adobe Kuler cloud account and then download the ASE file.

Quick Google Search landed me in few website that is pointing that GIMP can import ASE, and then Python can also parse ASE. With some lucks, I found this "Swatch Parser" Python script by Marcos A Ojeda http://generic.cx/

NOTE:

Unfortunately the ASE Swatch Parse script seems to only works with Blender with Python 2x, not Python 3x. So the following steps only explain how you may install external Python Package into Blender. However, you can follow further steps and see how you may load the parser script using Python standalone.

******************************************************************************
As someone who is a self-taught in programming, it is always useful to take note and share this kind of information. Previously I have no idea how to do this and sometimes Google searching around for such information is not always easy.
******************************************************************************

UPDATE 2013.06.30


I contacted Marcos Ojeda the developer and writer of the ASE Swatch Parser Python script and he kindly looked at the script and update it for Python 3x!

Thanks so much Marcos!
https://github.com/nsfmc/swatch/tree/903d3a07e21eea3ec238ab5f7cc1dc138fc55a24


import bpy
import swatch

# point to the path where ASE file is located
filepath = "C:/washme.ase"


# load and parse ASE swatch file
mySwatch = swatch.parse(filepath)

# list the data inside the parsed data
list(mySwatch[0])

# print out name of Kuler swatch
print(mySwatch[0]['name'])

# print out all parsed data
print(mySwatch[0]['swatches'])

# how many color swatches 
len(mySwatch[0]['swatches'])

# now iterate every swatch and create Blender Materials

# the colors may come in format that is not RGB, such as LAB, CMYK, etc.
# if not in RGB format, you need to convert the color first


# below script assumes that the color value is in RGB
# easy to transfer that into Blender Diffuse Material Color

    
# Create Materials based on the number of Kuler color swatches
for i in range(len(mySwatch[0]['swatches'])):
    mat = bpy.data.materials.new('kuler.{i}'.format(i=i))    

# Quickly iterate each material and change the diffuse color
for num, color in enumerate(mySwatch[0]['swatches']):
    print(color['data']['values'])
    mat = bpy.data.materials['kuler.{num}'.format(num=num)]
    mat.diffuse_color = color['data']['values']



Suzanne using Kuler color and Blender Cycles SSS.
NOW, STEP BY STEP PROCESS... ONCE MORE.

1. Download ASE Swatch Parser (Python Package):
https://pypi.python.org/pypi/swatch/0.2.3

2. Copy the Swatch Parser Python Package in the right Blender directory.
Inside that Python Package Zip, there is a folder called "swatch". Copy the whole content of that folder into "site-package" directory of Blender.

Actually this took me a while to figure this out. I actually found out the answer at Maya Forum on "how to import Python package". In Maya, one needs to copy Python package here:
C:\Program Files\Autodesk\Maya2014\Python\Lib\site-packages

So... based on that knowledge, I supposed it will be the same with Blender. Anyways, I am using Blender 2.67 and I place the package inside this directory and it works:
C:\Program Files\Blender Foundation\Blender\2.67\python\lib\site-packages

3. Using Python Swatch Parser inside Blender
If we installed the package correctly, we can now simply call the Python parser for ASE inside Blender.

import swatch

ALAS... we seems to need Python 2x! :(  ---> SEE THE UPDATE ABOVE

Apparently  I need to actually use older Python and parse the data outside Blender. So, I run Python 2.7 console and then test it like below. Yes, that parser actually works.





We can then use that parser script using Python 2.7 and then export the value we need into Blender, maybe via CSV?

NOTE: The ASE parser script works with Maya 2014, because Maya is using Python 2x.

To summarize again what is really happening, just in case you are lost:
  1. I have Adobe ASE (Adobe Swatch Exchange) file that was originated from Adobe Kuler, which contains Swatches data. This ASE file format is common between Adobe applications. I believe ASE is also can be imported to many graphic applications.
  2. I would like to be able to read the ASE data and import the RGB swatch values into Blender. So I searched around for Python Library Package that does the data parsing.
  3. I did find one which is: https://pypi.python.org/pypi/swatch/0.2.3 but this is for Python 2.x it did not work with Blender that uses Python 3.x. --- UPDATE: Now we have one that is working for Python 3.x, this really makes our life easier as we can run the script from inside Blender and everything else is a breeze. We do not need to do the following steps outside Blender. Just do everything inside Blender using Python.
  4. I use the older default Python console to parse the ASE using the "Swatch Parser" script. From here on, it is up to us how to bring that data back into Blender.
  5. Theoritically, I think it is possible to use Python standalone to do the parsing and conversion, even turning that ASE file --> into BLEND file that already contains Materials with those Adobe Kuler colors. Let say, we could actually create external Python script that generate 3D objects in Blender. Well... as long the Python version matches. There are all sort of clever ways to do this.
  6. One thing still in question for me is whether somebody out there already wrote Swatch Library Script for Blender? Maybe. So if Blender has Swatch Library Script, we can simply port and create Kuler ASE Importer. That will be the best.
If you can find ASE Python Parser that works seamlessly with Blender Python 3x please let me know. For now, this is probably one way to CONVERT Swatch from ASE. Thanks!

Thanks again to Marcos Ojeda for his handy Python script that does the conversion of ASE file!

Post a Comment

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget