III Funky ColorsPython For this part of the lab we are going
III. Funky Colors(Python)
For this part of the lab we are going to start with a picture of someone (you can use the one I
have provided with this lab – it works well given the background used in the picture) and make
some specific color changes to it. We are going to write a function that:
? Turns the teeth to a color of your choice
? Turns the eyes to a color of your choice
? Turns the hair to a color of your choice
Remember that there is a list of predefined colors in JES. You can find the list in your textbook,
Chapter 5. You can also make up your own colors by using the makeColor (r, g, b)
function.
A couple of things to keep in mind:
? The example in the book uses the value 165 as a threshold in the if statement that decides
whether the color of the pixel will be changed or not. This value may not work in your
function and you most likely will have to test a few values until you find a threshold that
works well.
? You should use the JES’ explorer tool to find the approximate color (or RGB values) for the
eyes, hair and teeth in the original picture. Then you need to use these colors when you write
the if statement that checks to see if a color change is needed. For example, I used this in
my solution:
if (distance(hairColor, pxColor) < hairDistance) :
setColor(px, blue)
where hairColor is a parameter that receives a color I created in the command area based on
the average hair color of the subject in the picture (which I found by using the explorer).
To test your function, you will need the explorer tool to figure out the coordinates for the areas
that define the eyes, hair and teeth – like we did in class.
Test your new function and when you are happy with the result use the writePictureTo
Solution
Here I am providing the code you can simply change the whatever color you want with your new color in your image
import glob
from PIL import Image
old_color = 255, 255, 255, 255 #for teeth simply replace the white color with whatever color you want
new_color = 255, 0, 0, 0
for path in glob.glob(\"*.jpg\"):
if \"__out\" in path:
print \"skipping on\", path
continue
print \"working on\", path
im = Image.open(path)
im = im.convert(\"RGBA\")
width, height = im.size
colortuples = im.getcolors()
pix = im.load()
for x in xrange(0, width):
for y in xrange(0, height):
if pix[x,y] == old_color:
im.putpixel((x, y), new_color)
im.save(path+\"__out.jpg\")
Don`t forget to follow the indentation
