I’m trying to add a new method to the Image class from Python Imaging Library. I want to have a new class called DilateImage which acts exactly as the original Image class, except it also includes a dilate() function which modifies the class instance when it is executed on one. Here’s my example code (that isn’t working):
import Image
def DilateImage(Image):
def dilate(self):
imnew = self.copy()
sourcepix = imnew.load()
destpix = self.load()
for y in range(self.size[1]):
for x in range(self.size[0]):
brightest = 255
for dy in range(-1,2):
for dx in range(-1,2):
try:
brightest = min(sourcepix[x+dx,y+dy], brightest)
except IndexError:
pass
destpix[x, y] = brightest
When I try to use this new class type to create an instance that uses the base class’ “open” function it fails:
>>> test = DilateImage.open("test.jpg")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'open'
There are two problems with your code. One of them has been already pointed out, when defining a class, you need to use the
classkeyword, sincedefkeyword defines a function or a method.The second problem is that the call
will import the module called Image into the
Imagenamespace, so thatImagein your code will refer to the module. It is not an object or class, sowill attempt to derive a new class from a module, which will fail.
The
Imagemodule contains a class calledImage. After importing the module into theImagenamespace, you would refer to this class asImage.Image. To extend this class, you could do for example this:To make this less confusing, you could also import the Image module into a different namespace:
The problem with all that is, the PIL does not seem to be designed to allow this kind of extension to the Image class. Its modules provide bunch of functions that take instances of Image as arguments and return new instances of Image. there are only few methods in the actual Image class. So what you probably want to do is write a function that will take an instance if Image and create a new instance of Image, rather than extending the Image class by a new method. For example, something like this: