Skip to content

Instantly share code, notes, and snippets.

@nutanc
Last active July 11, 2016 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nutanc/af36d24eca259b0b761ff459c6392510 to your computer and use it in GitHub Desktop.
Save nutanc/af36d24eca259b0b761ff459c6392510 to your computer and use it in GitHub Desktop.
Overlay one image over another
import sys
import cv2
import argparse
def detectObjects(image):
"""Converts an image to grayscale and returns the locations of any faces found"""
grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cascade = cv2.CascadeClassifier(
'haarcascade_frontalface_alt2.xml')
scalefactor = 1.09 # How much to increase window size each pass
minNeighbours = 5 # Smallest face to detect. Up this if you have small falsepositives
faces = cascade.detectMultiScale(grayscale, scalefactor, minNeighbours)
return [(x, y, x + w, y + h) for (x,y,w,h) in faces]
def main()
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--data", help = "story,face,x,y,w,h")
args = vars(ap.parse_args())
data=args["data"].split(",")
#read the selfie image for processing
face = cv2.imread(data[1])
#read the mask. Make sure this is available in the path
mask = cv2.imread("circlemask.png")
#detecting faces in the selfie image
faceboxes = detectObjects(face)
#get the face box co ordinates
replacebox=faceboxes[0]
#crop just the face from the full selfie
newface = face[replacebox[1]:replacebox[3], replacebox[0]:replacebox[2]]
#read the story page. We will be replacing face in this image
story = cv2.imread(data[0])
#get the box to be replaced based on co ordinates given in parameters
box1=(int(data[2]),int(data[3]),int(data[2])+int(data[4]),int(data[3])+int(data[5]))
size = (box1[2] - box1[0], box1[3] - box1[1])
#scaling selfie and mask to fit the co ordinates given in the new image.
scalednewface = cv2.resize(newface,size, interpolation = cv2.INTER_CUBIC)
scaledmask = cv2.resize(mask,size, interpolation = cv2.INTER_CUBIC)
#seamlessly merge the two images
op=cv2.seamlessClone(scalednewface,story, scaledmask, (box[0]+(size[0]/2), box[1]+(size[1]/2)),cv2.NORMAL_CLONE)
cv2.imshow("Output",op)
cv2.waitKey(0)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment