Unsharp Mask with PIL and PythonMagick

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# we need PythonMagick for its unsharp mask functions
#

from PIL import Image
from PythonMagick import Image as PMImage #distinguish between PIL and PythonMagick 'Image' object
from PythonMagick import Blob 

#Convert Magick image to PIL (Python Imageing Library) image
#taken from ftp://ftp.imagemagick.net/pub/ImageMagick/python/README.txt (which contains an error:
#Image.data does not exist
#see Magick++ documentation for the PythonMagick functions

def convertMGtoPIL(magickimage):
    'works with grayscale and color'
    img = PMImage(magickimage)  # make copy
    img.depth = 8        #  this takes 0.04 sec. for 640x480 image
    img.magick = "RGB"
    w, h = img.columns(), img.rows()
    blb=Blob()
    img.write(blb)
    data = blb.data
    
    # convert string array to an RGB Pil image
    pilimage = Image.fromstring('RGB', (w, h), data)
    return pilimage

#Convert PIL image to Magick image

def convertPILtoMG(pilimage):
    'returns RGB image'
    if pilimage == None:
        return None
    if pilimage.mode == 'L':
        pilimage = pilimage.convert("RGB")
    size = "%sx%s" % (pilimage.size[0], pilimage.size[1])
    data = pilimage.tostring('raw','RGB')
    mdata = Blob(data)
    img = PMImage(mdata, size, 8, 'RGB')
    return img

#unsharp mask function, see ImageMagick docs for explanation of radius, sigma, amount and threshold
def usm(pilimage,radius,sigma,amount,threshold):
	img=convertPILtoMG(pilimage)
	img.unsharpmask(radius,sigma,amount,threshold)
	pilimage=convertMGtoPIL(img)
	return pilimage

More like this

  1. Image resize on demand by VidJa 5 years, 3 months ago
  2. Resize image on save by David 6 years ago
  3. Captcha without Freetype or the Python Imaging Library (PIL) by gregb 4 years, 10 months ago
  4. Function to create resized versions of an image from a URL and saving it to a local path by obeattie 7 years, 1 month ago
  5. Mathematical Captcha by dogada 6 years, 4 months ago

Comments

dc (on December 29, 2008):

Why break a butterfly on the wheel when you can write own PIL filter or use builtin ImageFilter.SHARPEN?

#

(Forgotten your password?)