Skip to content

Instantly share code, notes, and snippets.

@cameronbarker
Created July 16, 2014 16:33
Show Gist options
  • Save cameronbarker/f8e48dca8f497177b5f4 to your computer and use it in GitHub Desktop.
Save cameronbarker/f8e48dca8f497177b5f4 to your computer and use it in GitHub Desktop.
Lyst image background removal
#http://developers.lyst.com/data/images/2014/02/13/background-removal/
import pgmagick as pg
def trans_mask_sobel(img):
""" Generate a transparency mask for a given image """
image = pg.Image(img)
# Find object
image.negate()
image.edge()
image.blur(1)
image.threshold(24)
image.adaptiveThreshold(5, 5, 5)
# Fill background
image.fillColor('magenta')
w, h = image.size().width(), image.size().height()
image.floodFillColor('0x0', 'magenta')
image.floodFillColor('0x0+%s+0' % (w-1), 'magenta')
image.floodFillColor('0x0+0+%s' % (h-1), 'magenta')
image.floodFillColor('0x0+%s+%s' % (w-1, h-1), 'magenta')
image.transparent('magenta')
return image
end
def alpha_composite(image, mask):
""" Composite two images together by overriding one opacity channel """
compos = pg.Image(mask)
compos.composite(
image,
image.size(),
pg.CompositeOperator.CopyOpacityCompositeOp
)
return compos
end
def remove_background(filename):
""" Remove the background of the image in 'filename' """
img = pg.Image(filename)
transmask = trans_mask_sobel(img)
img = alphacomposite(transmask, img)
img.trim()
img.write('out.png')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment