Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

migrate to python3 #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions apply_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,46 +121,46 @@ def assert_dir(dir_path):
potential_out_dir = "_".join( potential_out_dir.split("_")[:-1] ) + "_" + str(idx)
out_dir = potential_out_dir
os.mkdir(out_dir)
print "[+] Created " + out_dir + ". and will save output to that directory"
print("[+] Created " + out_dir + ". and will save output to that directory")
return out_dir

def apply_masks(input_paths, masks, output_paths, apply_unique_masks, is_video):

print "[+] Applying mask(s)"
print("[+] Applying mask(s)")
for j, path in enumerate(input_paths, 0):
print "\n\t[+] Opening", path
print("\n\t[+] Opening", path)
img = get_img(path)

# find all faces
faces = get_rects(img)
if len(faces) == 0:
print "\t[-] no faces found"
print("\t[-] no faces found")
if is_video == True:
temp_dir = "/".join( path.split("/")[:-1])
f = path.split("/")[-1]
temp_out = temp_dir + "_masked"
if not os.path.isdir(temp_out):
os.mkdir(temp_out)
output_path = os.path.join( temp_out, f)
print "\t[+] Saving as", output_path
print("\t[+] Saving as", output_path)
cv2.imwrite(output_path, img)
continue
print "\t[+] Found", len(faces), "faces"
print("\t[+] Found", len(faces), "faces")
out = img.copy()

#sort faces by size, start with the smallest
faces = sort_faces_by_size(faces)

masks_not_used = masks.copy()
for i, face in enumerate(faces, 0):
print "\t\t[face " + str(i+1) + "]",
print("\t\t[face " + str(i+1) + "]", end=' ')
# pick a random mask, check if unique mask was selected
mask_name, mask_front, mask_back, masks_not_used = get_random_mask(masks, masks_not_used, apply_unique_masks)
if mask_name == None:
print "already used all masks once (you specified '-u' unique mask use)"
print("already used all masks once (you specified '-u' unique mask use)")
continue

print "picked mask", mask_name
print("picked mask", mask_name)
mask_face = get_rects(mask_back)[0]

#get landmarks
Expand All @@ -176,12 +176,12 @@ def apply_masks(input_paths, masks, output_paths, apply_unique_masks, is_video):
try:
for c in range(0,3):
out[0:out.shape[0],0:out.shape[1], c] = aligned_mask[:,:,c] * (aligned_mask[:,:,3]/255.0) + out[0:out.shape[0], 0:out.shape[1], c] * (1.0 - aligned_mask[:,:,3]/255.0)
except Exception, e:
print e
except Exception as e:
print(e)
pass

if not is_video:
print "\t[+] Saving as", output_paths[j]
print("\t[+] Saving as", output_paths[j])
cv2.imwrite(output_paths[j], out)
else:
temp_dir = "/".join( path.split("/")[:-1])
Expand All @@ -190,20 +190,20 @@ def apply_masks(input_paths, masks, output_paths, apply_unique_masks, is_video):
if not os.path.isdir(temp_out):
os.mkdir(temp_out)
output_path = os.path.join( temp_out, f)
print "\t[+] Saving as", output_path
print("\t[+] Saving as", output_path)
cv2.imwrite(output_path, out)

if is_video == True:
temp_dir = "/".join( path.split("/")[:-1])
f = path.split("/")[-1]
temp_out = temp_dir + "_masked"

print "[+] Combining frames to video"
print """
print("[+] Combining frames to video")
print("""
This uses ffmpeg, which you hopefully have installed.
Also not sound supported yet.... would be a few changes in the ffmpeg commands,
but I thought it was fine for now.
"""
""")
fps = '25'
if os.path.isfile( os.path.join(temp_dir, "fps.txt")):
fps = open( os.path.join( temp_dir, "fps.txt")).read().strip()
Expand All @@ -215,11 +215,11 @@ def apply_masks(input_paths, masks, output_paths, apply_unique_masks, is_video):
subprocess.call(["ffmpeg", "-i", os.path.join(temp_out,"video.mp4"), "-i", os.path.join(temp_dir, "sound.aac"), "-c:v", "copy", "-c:a", "aac", "-strict", "experimental", "-r", fps, output_paths[0] ])
else:
shutil.move( os.path.join(temp_out, "video.mp4"), output_paths[0])
print "\t[+] Cleaning up after myself"
print("\t[+] Cleaning up after myself")

shutil.rmtree(temp_dir)
shutil.rmtree(temp_out)
print "\t[+] Saving as", output_paths[0]
print("\t[+] Saving as", output_paths[0])



Expand Down
26 changes: 13 additions & 13 deletions create_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ def add_margin_to_image(img, factor=1):


def get_img(path):
print "[+] Opened image from:", path
print("[+] Opened image from:", path)
return cv2.imread(path)

def get_rects(img):
rects = detector(img)
print "\t[+] Number of faces found:", len(rects)
print("\t[+] Number of faces found:", len(rects))
return rects

def assert_dir(dir_path):
Expand All @@ -39,7 +39,7 @@ def assert_dir(dir_path):
potential_out_dir = "_".join( potential_out_dir.split("_")[:-1] ) + "_" + str(idx)
out_dir = potential_out_dir
os.mkdir(out_dir)
print "[+] Created " + out_dir + ". and will save output to that directory"
print("[+] Created " + out_dir + ". and will save output to that directory")
return out_dir

def cut_face_with_margin(img, rect, margin_factor=0):
Expand All @@ -51,7 +51,7 @@ def cut_face_with_margin(img, rect, margin_factor=0):
return img[y:y+h,x:x+w]

def make_masks(input_paths, output_info):
print "[+] Creating masks"
print("[+] Creating masks")
# for each image, get all faces
mask_count = 0
for img_path in input_paths:
Expand All @@ -61,7 +61,7 @@ def make_masks(input_paths, output_info):
# find all faces
faces = get_rects(img)
if len(faces) == 0:
print "no faces found"
print("no faces found")
return

output_paths = list()
Expand Down Expand Up @@ -108,18 +108,18 @@ def make_masks(input_paths, output_info):
mask = make_mask.make_mask(face_img)

if str(type(mask)) != "<type 'numpy.ndarray'>":
print "\t\t[-] Trouble with finding a mask for face", str(i), "unfortunately"
print "\t\t\tFYI, this is because I am using two different face detection algorithms....."
print("\t\t[-] Trouble with finding a mask for face", str(i), "unfortunately")
print("\t\t\tFYI, this is because I am using two different face detection algorithms.....")
else:
cv2.imwrite( output_paths[i]["back"], face_img)
cv2.imwrite( output_paths[i]["front"], mask)
print "\t\t[+] Saved mask files for face", str(i)
except Exception, e:
print "error with image:", img_path, "\nerror:", e
print("\t\t[+] Saved mask files for face", str(i))
except Exception as e:
print("error with image:", img_path, "\nerror:", e)
pass


print "\n\n[+] Saved new masks to:", output_info["base"]
print("\n\n[+] Saved new masks to:", output_info["base"])



Expand All @@ -135,8 +135,8 @@ def make_masks(input_paths, output_info):
args = parser.parse_args()

input_paths, output_info = validate_create_mask_input.run(args)
print "input_paths", input_paths
print "output_info", output_info
print("input_paths", input_paths)
print("output_info", output_info)

make_masks(input_paths, output_info)

2 changes: 1 addition & 1 deletion mask_generator/aligner.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""
Align face and image sizes
"""
from __future__ import division

import cv2
import numpy as np

Expand Down
8 changes: 4 additions & 4 deletions mask_generator/locator.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ def face_points(img, add_boundary_points=True):
stasm_platform = SUPPORTED_PLATFORMS.get(sys.platform)
cv_major = cvver.major()
if stasm_platform is None:
print(sys.platform + ' version of stasm_util is currently not supported.')
print('You can try building `stasm_util_{0}_cv{1}` and add to `bin`'.format(
sys.platform, cv_major))
print((sys.platform + ' version of stasm_util is currently not supported.'))
print(('You can try building `stasm_util_{0}_cv{1}` and add to `bin`'.format(
sys.platform, cv_major)))
sys.exit()

stasm_path = path.join(
Expand Down Expand Up @@ -93,4 +93,4 @@ def weighted_average_points(start_points, end_points, percent=0.5):
return np.asarray(start_points*percent + end_points*(1-percent), np.int32)

if __name__ == "__main__":
print(face_points(sys.argv[1]))
print((face_points(sys.argv[1])))
32 changes: 16 additions & 16 deletions tools/validate_create_mask_input.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
def run(args):
# deal with input
print "[+] Inspecting input"
print("[+] Inspecting input")
input_paths = list()
in_arg = args.input
img_extensions = set([".jpg", ".jpeg", ".tif", ".png", ".tiff", ".gif"])
Expand All @@ -10,50 +10,50 @@ def run(args):
if ext in img_extensions:
input_paths.append(in_arg)
else:
print "[-] Exiting program"
print """
print("[-] Exiting program")
print("""
Sorry, the extension of you input file is not recognised.
This doesn't mean your file isn't valid, but that you have to
change either the file extension or the source code to test it.
Currently support image extensions: """ + str(list(img_extensions)) + """
"""
""")
sys.exit()
elif os.path.isdir(in_arg):
for f in os.listdir(in_arg):
ext = "." + f.split(".")[-1]
if ext in img_extensions:
input_paths.append( os.path.join(in_arg, f) )
if len(input_paths) < 1:
print "[-] Exiting program"
print """
print("[-] Exiting program")
print("""
No images found in """ + in_arg + """
Right now not supporting more than one video at once, can be
changed in the source code though.
"""
""")
sys.exit()
else:
print "[-] Exiting program"
print """
print("[-] Exiting program")
print("""
Cannot find your input: """ + in_arg + """
"""
""")
sys.exit()

print "[+] Inspecting input: Done."
print("[+] Inspecting input: Done.")

# deal with output path
print "[+] Preparing output paths"
print("[+] Preparing output paths")
output_info = dict()
out_arg = args.output

if os.path.isfile(out_arg):
print "[-] Exiting program"
print """
print("[-] Exiting program")
print("""
Your output path is a file that already exists: """ + in_arg + """
It should be a directory that either already exists or not,
but in no case a filename. This is beacuse this script actually
creates two files for each mask. If you want to give them a name,
use the '-n' flag.
"""
""")
sys.exit()
else:
if not os.path.isdir(out_arg):
Expand All @@ -62,7 +62,7 @@ def run(args):
output_info["base"] = out_arg
output_info["name"] = args.name

print "[+] Preparing output paths. Done."
print("[+] Preparing output paths. Done.")
return input_paths, output_info


Expand Down
Loading