Search code examples
pythonimagemagickpython-imaging-libraryimagemagick-convertpythonmagick

Polaroid Effect with Images in Python


I'm trying to take an image and add the following effect from imagemagick http://www.imagemagick.org/Usage/transform/#polaroid. I've searched for Python code examples and have been unsuccessful. I don't need to use imagemagick(wand, pythonmagick, etc.) this was just the only example of this I could find. I don't want to use the command line example like listed. I would love to be able to include it in my photo booth python code.


Solution

  • With , you will need to implement the C-API methods MagickPolaroidImage & MagickSetImageBorderColor

    import ctypes
    
    from wand.api import library
    from wand.color import Color
    from wand.drawing import Drawing
    from wand.image import Image
    
    # Tell Python about C library
    library.MagickPolaroidImage.argtypes = (ctypes.c_void_p,  # MagickWand *
                                            ctypes.c_void_p,  # DrawingWand *
                                            ctypes.c_double)  # Double
    
    library.MagickSetImageBorderColor.argtypes = (ctypes.c_void_p,  # MagickWand *
                                                  ctypes.c_void_p)  # PixelWand *
    
    
    # Define FX method. See MagickPolaroidImage in wand/magick-image.c
    def polaroid(wand, context, angle=0.0):
        if not isinstance(wand, Image):
            raise TypeError('wand must be instance of Image, not ' + repr(wand))
        if not isinstance(context, Drawing):
            raise TypeError('context must be instance of Drawing, not ' + repr(context))
        library.MagickPolaroidImage(wand.wand,
                                    context.resource,
                                    angle)
    
    # Example usage
    with Image(filename='rose:') as image:
        # Assigne border color
        with Color('white') as white:
            library.MagickSetImageBorderColor(image.wand, white.resource)
        with Drawing() as annotation:
            # ... Optional caption text here ...
            polaroid(image, annotation)
        image.save(filename='/tmp/out.png')
    

    Polaroid effect with Python & wand