I want to create functionality similar to PIL's Image.blend
, using a different blending algorithm. To do this would I need to: (1) directly modify the PIL modules and compile my own custom PIL or (2) write a python c module which imports and extends PIL?
I have unsuccessfully tried:
#include "_imaging.c"
I also was trying to just pull out the parts I need from the PIL source and put them in my own file. The farther I got in the more things I had to pull and it seems that is not the ideal solution.
UPDATE: edited to add the blending algorithm implemented in python (this emulates the overlay blending mode in Photoshop):
def overlay(upx, lpx):
return (2 * upx * lpx / 255 ) if lpx < 128 else ((255-2 * (255 - upx) * (255 - lpx) / 255))
def blend_images(upper = None, lower = None):
upixels = upper.load()
lpixels = lower.load()
width, height = upper.size
pixeldata = [0] * len(upixels[0, 0])
for x in range(width):
for y in range(height):
# the next for loop is to deal with images of any number of bands
for i in range(len(upixels[x,y])):
pixeldata[i] = overlay(upixels[x, y][i], lpixels[x, y][i])
upixels[x,y] = tuple(pixeldata)
return upper
I have also unsuccessfully tried implementing this using scipy's weave.inline
:
def blend_images(upper=None, lower=None):
upixels = numpy.array(upper)
lpixels = numpy.array(lower)
width, height = upper.size
nbands = len(upixels[0,0])
code = """
#line 120 "laplace.py" (This is only useful for debugging)
int upx, lpx;
for (int i = 0; i < width-1; ++i) {
for (int j=0; j<height-1; ++j) {
for (int k = 0; k < nbands-1; ++k){
upx = upixels[i,j][k];
lpx = lpixels[i,j][k];
upixels[i,j][k] = ((lpx < 128) ? (2 * upx * lpx / 255):(255 - 2 * (255 - upx) * (255 - lpx) / 255));
}
}
}
return_val = upixels;
"""
# compiler keyword only needed on windows with MSVC installed
upixels = weave.inline(code,
['upixels', 'lpixels', 'width', 'height', 'nbands'],
type_converters=converters.blitz,
compiler = 'gcc')
return Image.fromarray(upixels)
I'm doing something wrong with the upixel
and lpixel
arrays but I'm not sure how to fix them. I'm a bit confused about the type of upixels[i,j][k]
, and not sure what I could assign it to.