Numpy works very well for generalized fast and specific pixel manipulation. Here's an example:
import Image
import numpy as np
import matplotlib.pyplot as plt
im = Image.open("python.jpg")
a = np.asarray(im)
b = np.where(np.all(((a>[240, 40, 20]) * (a<=[255, 255, 150])), axis=2, keepdims=True), [80,0,0], [0,0,90])
plt.figure()
plt.subplot(1,2,1)
plt.imshow(a)
plt.subplot(1,2,2)
plt.imshow(b)
plt.show()
Here I converted a range of pixel values rather than a single value. To do a single value, remove the use ==
rather than >
, and only use one condition. Also, I used matplotlib for an easy way to show the output and input together, but you could also convert back to an image using Image.fromarray(b.astype(np.uint8))
.
Staying in pure PIL will work fine if you want to apply some simple standard filters, or use local getpixel
operations, but for most numerical work with images, numpy or an image processing package is the way to go.