$ cd image $ mkdir e3 $ cd e3
# e301.py ... decompose color image to R,G,B channels
import Image
img = Image.open('sample.ppm')
width, height = img.size
imgR = Image.new('L', (width, height))
imgG = Image.new('L', (width, height))
imgB = Image.new('L', (width, height))
for j in range(height):
for i in range(width):
r, g, b = img.getpixel((i, j))
imgR.putpixel((i, j), r)
imgG.putpixel((i, j), g)
imgB.putpixel((i, j), b)
imgR.save('r.pgm')
imgG.save('g.pgm')
imgB.save('b.pgm')
# e302.py ... split into YUV components
import Image
img = Image.open('sample.ppm')
width, height = img.size
imgY = Image.new('L', (width, height))
imgU = Image.new('L', (width, height))
imgV = Image.new('L', (width, height))
for j in range(height):
for i in range(width):
r, g, b = img.getpixel((i, j))
y = 0.299 * r + 0.587 * g + 0.114 * b
u = (-0.14713 * r - 0.28886 * g + 0.436 * b)+128
v = ( 0.615 * r - 0.51499 * g - 0.10001 * b)+128
imgY.putpixel((i, j), y)
imgU.putpixel((i, j), u)
imgV.putpixel((i, j), v)
imgY.save('y.pgm')
imgU.save('u.pgm')
imgV.save('v.pgm')
# e303.py ... compose RGB color image from YUV
import Image
imgY = Image.open('y.pgm')
imgU = Image.open('u.pgm')
imgV = Image.open('v.pgm')
width, height = imgY.size
img = Image.new('RGB', (width, height))
for j in range(height):
for i in range(width):
y = imgY.getpixel((i, j))
u = imgU.getpixel((i, j)) - 128
v = imgV.getpixel((i, j)) - 128
r = y + 1.13983 * v
g = y - 0.39465 * u - 0.58060 * v
b = y + 2.03211 * u
img.putpixel((i, j), (r, g, b))
img.show()
# shrink and expand to reduce information
imgU = imgU.resize((width/2, height/2), Image.ANTIALIAS
).resize((width, height))
imgV = imgV.resize((width/2, height/2), Image.ANTIALIAS
).resize((width, height))
# e305.py
import Image
from math import cos, sin, pi
def hue(t, u, v):
x = cos(t) * u - sin(t) * v
y = sin(t) * u + cos(t) * v
return x, y
imgY = Image.open('y.pgm')
imgU = Image.open('u.pgm')
imgV = Image.open('v.pgm')
width, height = imgY.size
img = Image.new('RGB', (width, height))
for j in range(height):
for i in range(width):
y = imgY.getpixel((i, j))
u = imgU.getpixel((i, j)) - 128
v = imgV.getpixel((i, j)) - 128
u, v = hue(pi/6, u, v)
r = y + 1.13983 * v
g = y - 0.39465 * u - 0.58060 * v
b = y + 2.03211 * u
img.putpixel((i, j), (r, g, b))
img.show()