Homework 27
Module mash.py
- Supports the creation a new image that is a mash up of two existing images —
bg
andfg
. The new image hasbg
as its background. The pixels infg
that are dissimilar to the back screen color are copied on top of the background.
Primary function
combine( bg, fg, sx, sy, back_screen )
- Returns mash up of background image
bg
and foreground imagefg
, where the pixels infg
that are dissimilar toback_screen
are copied on top of the background.
- The mash up uses location
(sx, sy)
as the spot in the background to start the lay over offg
.
Convenience functions
similar( p1, p2, max_allowable=THRESHOLD )
- Returns whether the distance between pixels
p1
andp2
is less than the max allowable threshold.
is_background( p, back_screen )
- Returns whether
p
is similar to theback_screen
color.
inbounds( spot, img )
- Returns whether
spot
lies onimg
.
colorable( spot, img, p, back_screen )
- Returns whether both
spot
is a location onimg
and colorp
is not similar to colorback_screen
.
|
|
|
from PIL import Image
helpful constants
THRESHOLD = 85 # default max allowable distance to be similar
GREEN = ( 0, 255, 0 ) # back screen color
def similar( p1, p2, max_allowable=THRESHOLD ) :
''' Returns whether pixels p1 and p2 have RGB differences less than the
max allowable
'''
import color
pass
def is_background( p, back_screen ) :
''' Returns whether p is similar to the back_screen color
'''
pass
def inbounds( spot, img ) :
''' Returns whether spot lies on img
'''
pass
def colorable( spot, img, p, back_screen ) :
''' Returns whether both spot is a location on img and color p is not
similar to color back_screen
'''
pass
def combine( bg, fg, sx, sy, back_screen ) :
''' Returns a new image that is a mash up of images bg and fg. The new
image has bg as its background. The pixels in fg that are dissimilar
to back_screen are copied on top of the background. The copy uses
(sx, sy) as the spot in the background as the location to start the
lay over of fg.
'''
bw, bh = bg.size
fw, fh = fg.size
new_image = bg.copy().convert( 'RGB' )
for fx in range( 0, fw ) :
for fy in range( 0, fh ):
fspot = ( fx, fy )
fpixel = fg.getpixel( fspot )
bx = sx + fx
by = sy + fy
bspot = ( bx, by )
if ( colorable( bspot, bg, fpixel, back_screen ) ) :
new_image.putpixel( bspot, fpixel )
return new_image
def clean_up( original, back_screen ) :
''' Returns a copy of original where pixels similar to the back_screen are set
to the back_screen
'''
new_image = original.copy().convert( 'RGB' )
nw, nh = new_image.size
for nx in range( 0, nw ) :
for ny in range( 0, nh ) :
nspot = ( nx, ny )
npixel = new_image.getpixel( nspot )
if ( similar( npixel, back_screen ) ) :
new_image.putpixel( nspot, back_screen )
return new_image
if ( name == 'main' ) :
import smashing
smashing.test_with_dino()
smashing.test_with_beyonce()
smashing.test_with_ww()
© 2019 Jim Cohoon | Resources from previous semesters are available. |