Created
July 11, 2016 05:59
-
-
Save nutanc/219bc2ffd8bdfde4311f1a9f0a4c54ba to your computer and use it in GitHub Desktop.
Face Replace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# face_replace.py | |
# Usage: python face_replace.py <image_file> [face index] | |
import sys | |
import cv2 | |
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(): | |
inputfile = sys.argv[1] | |
print inputfile | |
replacefile = sys.argv[2] | |
image = cv2.imread(inputfile) | |
replaceimage = cv2.imread(replacefile) | |
print "Detecting faces..." | |
faceboxes = detectObjects(image) | |
print len(faceboxes), "faces found" | |
print "Detecting replace faces..." | |
replacefaceboxes = detectObjects(replaceimage) | |
print len(replacefaceboxes), "replace faces found" | |
mask = cv2.imread("circlemask.png") | |
replacebox=replacefaceboxes[0] | |
newreplaceimage=replaceimage[replacebox[1]:replacebox[3], replacebox[0]:replacebox[2]] | |
#cv2.imshow("Output1",newreplaceimage) | |
#cv2.waitKey(0) | |
box=faceboxes[1] | |
size = (box[2] - box[0], box[3] - box[1]) | |
scalednewface = cv2.resize(newreplaceimage,size, interpolation = cv2.INTER_CUBIC) | |
scaledmask = cv2.resize(mask,size, interpolation = cv2.INTER_CUBIC) | |
op=cv2.seamlessClone(scalednewface,image, 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