def generate_depth_image(inputDir, prn): depth_images = [] # os.environ['CUDA_VISIBLE_DEVICES'] = "-1" # only cpu for now # prn = PRN(is_dlib = True) types = ('*.jpg', '*.png') image_path_list= [] for files in types: image_path_list.extend(glob(os.path.join(inputDir, files))) total_num = len(image_path_list) for i, image_path in enumerate(image_path_list): name = image_path.strip().split('/')[-1][:-4] # read image image = imread(image_path) [h, w, c] = image.shape if c>3: image = image[:,:,:3] # the core: regress position map max_size = max(image.shape[0], image.shape[1]) if max_size> 1000: image = rescale(image, 1000./max_size) image = (image*255).astype(np.uint8) pos = prn.process(image) # use dlib to detect face image = image/255. if pos is None: continue vertices = prn.get_vertices(pos) save_vertices = frontalize(vertices) save_vertices[:,1] = h - 1 - save_vertices[:,1] depth = get_depth_image(vertices, prn.triangles, h, w) # save_depth_image(depth) depth_images.append(depth) return depth exit(1) print(len(depth_images)) return depth_images[0]
def main(args): if args.isShow or args.isTexture: import cv2 from utils.cv_plot import plot_kpt, plot_vertices, plot_pose_box # ---- init PRN os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu # GPU number, -1 for CPU prn = PRN(is_dlib=args.isDlib) # ------------- load data image_folder = args.inputDir save_folder = args.outputDir if not os.path.exists(save_folder): os.mkdir(save_folder) types = ('*.jpg', '*.png') image_path_list = [] if os.path.isfile(image_folder): image_path_list.append(image_folder) for files in types: image_path_list.extend(glob(os.path.join(image_folder, files))) total_num = len(image_path_list) for i, image_path in enumerate(image_path_list): name = image_path.strip().split('/')[-1][:-4] # read image image = imread(image_path) [h, w, _] = image.shape # the core: regress position map if args.isDlib: max_size = max(image.shape[0], image.shape[1]) if max_size > 1000: image = rescale(image, 1000. / max_size) image = (image * 255).astype(np.uint8) pos, crop_image = prn.process(image) # use dlib to detect face else: if image.shape[1] == image.shape[2]: image = resize(image, (256, 256)) pos = prn.net_forward( image / 255.) # input image has been cropped to 256x256 crop_image = None else: box = np.array([0, image.shape[1] - 1, 0, image.shape[0] - 1 ]) # cropped with bounding box pos, crop_image = prn.process(image, box) image = image / 255. if pos is None: continue if args.is3d or args.isMat or args.isPose or args.isShow: # 3D vertices vertices = prn.get_vertices(pos) if args.isFront: save_vertices = frontalize(vertices) else: save_vertices = vertices.copy() save_vertices[:, 1] = h - 1 - save_vertices[:, 1] if args.isImage and crop_image is not None: imsave(os.path.join(save_folder, name + '_crop.jpg'), crop_image) imsave(os.path.join(save_folder, name + '_orig.jpg'), image) if args.is3d: # corresponding colors colors = prn.get_colors(image, vertices) if args.isTexture: texture = cv2.remap(image, pos[:, :, :2].astype(np.float32), None, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, borderValue=(0)) if args.isMask: vertices_vis = get_visibility(vertices, prn.triangles, h, w) uv_mask = get_uv_mask(vertices_vis, prn.triangles, prn.uv_coords, h, w, prn.resolution_op) texture = texture * uv_mask[:, :, np.newaxis] write_obj_with_texture( os.path.join(save_folder, name + '.obj'), save_vertices, colors, prn.triangles, texture, prn.uv_coords / prn.resolution_op ) #save 3d face with texture(can open with meshlab) else: write_obj(os.path.join(save_folder, name + '.obj'), save_vertices, colors, prn.triangles) #save 3d face(can open with meshlab) if args.isDepth: depth_image = get_depth_image(vertices, prn.triangles, h, w, True) depth = get_depth_image(vertices, prn.triangles, h, w) imsave(os.path.join(save_folder, name + '_depth.jpg'), depth_image) sio.savemat(os.path.join(save_folder, name + '_depth.mat'), {'depth': depth}) if args.isMat: sio.savemat(os.path.join(save_folder, name + '_mesh.mat'), { 'vertices': vertices, 'colors': colors, 'triangles': prn.triangles }) if args.isKpt or args.isShow: # get landmarks kpt = prn.get_landmarks(pos) np.savetxt(os.path.join(save_folder, name + '_kpt.txt'), kpt) if args.isPose or args.isShow: # estimate pose camera_matrix, pose = estimate_pose(vertices) np.savetxt(os.path.join(save_folder, name + '_pose.txt'), pose) np.savetxt(os.path.join(save_folder, name + '_camera_matrix.txt'), camera_matrix) np.savetxt(os.path.join(save_folder, name + '_pose.txt'), pose) if args.isShow: # ---------- Plot image_pose = plot_pose_box(image, camera_matrix, kpt) cv2.imshow('sparse alignment', plot_kpt(image, kpt)) cv2.imshow('dense alignment', plot_vertices(image, vertices)) cv2.imshow('pose', plot_pose_box(image, camera_matrix, kpt)) if crop_image is not None: cv2.imshow('crop', crop_image) cv2.waitKey(0)
pos_interpolated = resize(pos, (args.texture_size, args.texture_size), preserve_range = True) else: pos_interpolated = pos.copy() texture = cv2.remap(image, pos_interpolated[:,:,:2].astype(np.float32), None, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT,borderValue=(0)) if args.isMask: vertices_vis = get_visibility(vertices, prn.triangles, h, w) uv_mask = get_uv_mask(vertices_vis, prn.triangles, prn.uv_coords, h, w, prn.resolution_op) uv_mask = resize(uv_mask, (args.texture_size, args.texture_size), preserve_range = True) texture = texture*uv_mask[:,:,np.newaxis] # write_obj_with_texture(os.path.join(save_folder, name + '.obj'), save_vertices, prn.triangles, texture, prn.uv_coords/prn.resolution_op)#save 3d face with texture(can open with meshlab) else: # write_obj_with_colors(os.path.join(save_folder, name + '.obj'), save_vertices, prn.triangles, colors) #save 3d face(can open with meshlab) pass if args.isDepth: depth_image = get_depth_image(vertices, prn.triangles, h, w, True) depth = get_depth_image(vertices, prn.triangles, h, w) # imsave(os.path.join(save_folder, name + '_depth.jpg'), depth_image) # sio.savemat(os.path.join(save_folder, name + '_depth.mat'), {'depth':depth}) if args.isMat: # sio.savemat(os.path.join(save_folder, name + '_mesh.mat'), {'vertices': vertices, 'colors': colors, 'triangles': prn.triangles}) pass if args.isKpt or args.isShow: # get landmarks kpt = prn.get_landmarks(pos) # np.savetxt(os.path.join(save_folder, name + '_kpt.txt'), kpt) if args.isPose or args.isShow: # estimate pose
def main(args): if args.isShow or args.isTexture: import cv2 from utils.cv_plot import plot_kpt, plot_vertices, plot_pose_box # ---- init PRN os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu # GPU number, -1 for CPU prn = PRN(is_dlib=args.isDlib, is_faceboxes=args.isFaceBoxes) # ---- load data image_folder = args.inputDir save_folder = args.outputDir if not os.path.exists(save_folder): os.mkdir(save_folder) types = ('*.jpg', '*.png') image_path_list = [] for files in types: image_path_list.extend(glob(os.path.join(image_folder, files))) total_num = len(image_path_list) for i, image_path in enumerate(image_path_list): name = image_path.strip().split('/')[-1][:-4] # read image image = imread(image_path) [h, w, c] = image.shape if c > 3: image = image[:, :, :3] # RGBA图中,去除A通道 # the core: regress position map if args.isDlib: max_size = max(image.shape[0], image.shape[1]) if max_size > 1000: image = rescale(image, 1000. / max_size) image = (image * 255).astype(np.uint8) pos = prn.process(image) # use dlib to detect face elif args.isFaceBoxes: pos, cropped_img = prn.process( image) # use faceboxes to detect face else: if image.shape[0] == image.shape[1]: image = resize(image, (256, 256)) pos = prn.net_forward( image / 255.) # input image has been cropped to 256x256 else: box = np.array([0, image.shape[1] - 1, 0, image.shape[0] - 1 ]) # cropped with bounding box pos = prn.process(image, box) image = image / 255. if pos is None: continue if args.is3d or args.isMat or args.isPose or args.isShow: # 3D vertices vertices = prn.get_vertices(pos) if args.isFront: save_vertices = frontalize(vertices) else: save_vertices = vertices.copy() save_vertices[:, 1] = h - 1 - save_vertices[:, 1] # 三维人脸旋转对齐方法 # if args.isImage: # vertices = prn.get_vertices(pos) # scale_init = 180 / (np.max(vertices[:, 1]) - np.min(vertices[:, 1])) # colors = prn.get_colors(image, vertices) # triangles = prn.triangles # camera_matrix, pose = estimate_pose(vertices) # yaw, pitch, roll = pos * ANGULAR # vertices1 = vertices - np.mean(vertices, 0)[np.newaxis, :] # # obj = {'s': scale_init, 'angles': [-pitch, yaw, -roll + 180], 't': [0, 0, 0]} # camera = {'eye':[0, 0, 256], 'proj_type':'perspective', 'at':[0, 0, 0], # 'near': 1000, 'far':-100, 'fovy':30, 'up':[0,1,0]} # # image1 = transform_test(vertices1, obj, camera, triangles, colors, h=256, w=256) * 255 # image1 = image1.astype(np.uint8) # imsave(os.path.join(save_folder, name + '.jpg'), image1) if args.is3d: # corresponding colors colors = prn.get_colors(image, vertices) if args.isTexture: if args.texture_size != 256: pos_interpolated = resize( pos, (args.texture_size, args.texture_size), preserve_range=True) else: pos_interpolated = pos.copy() texture = cv2.remap(image, pos_interpolated[:, :, :2].astype( np.float32), None, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0)) if args.isMask: vertices_vis = get_visibility(vertices, prn.triangles, h, w) uv_mask = get_uv_mask(vertices_vis, prn.triangles, prn.uv_coords, h, w, prn.resolution_op) uv_mask = resize(uv_mask, (args.texture_size, args.texture_size), preserve_range=True) texture = texture * uv_mask[:, :, np.newaxis] write_obj_with_texture( os.path.join(save_folder, name + '.obj'), save_vertices, prn.triangles, texture, prn.uv_coords / prn.resolution_op ) #save 3d face with texture(can open with meshlab) else: write_obj_with_colors( os.path.join(save_folder, name + '.obj'), save_vertices, prn.triangles, colors) #save 3d face(can open with meshlab) if args.isDepth: depth_image = get_depth_image(vertices, prn.triangles, h, w, True) depth = get_depth_image(vertices, prn.triangles, h, w) imsave(os.path.join(save_folder, name + '_depth.jpg'), depth_image) sio.savemat(os.path.join(save_folder, name + '_depth.mat'), {'depth': depth}) if args.isMat: sio.savemat(os.path.join(save_folder, name + '_mesh.mat'), { 'vertices': vertices, 'colors': colors, 'triangles': prn.triangles }) if args.isKpt: # get landmarks kpt = prn.get_landmarks(pos) np.savetxt(os.path.join(save_folder, name + '_kpt.txt'), kpt) if args.is2dKpt and args.is68Align: ori_kpt = prn.get_landmarks_2d(pos) dlib_aligner = DlibAlign() dst_img = dlib_aligner.dlib_68_align(image, ori_kpt, 256, 0.5) imsave(os.path.join(save_folder, name + '.jpg'), dst_img) if args.isPose: # estimate pose camera_matrix, pose, rot = estimate_pose(vertices) np.savetxt(os.path.join(save_folder, name + '_pose.txt'), np.array(pose) * ANGULAR) np.savetxt(os.path.join(save_folder, name + '_camera_matrix.txt'), camera_matrix) if args.isShow: kpt = prn.get_landmarks(pos) cv2.imshow('sparse alignment', plot_kpt(image, kpt)) # cv2.imshow('dense alignment', plot_vertices(image, vertices)) # cv2.imshow('pose', plot_pose_box(image, camera_matrix, kpt)) cv2.waitKey(1)
def main(args): if args.isShow or args.isTexture: import cv2 from utils.cv_plot import plot_kpt, plot_vertices, plot_pose_box # ---- init PRN os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu # GPU number, -1 for CPU prn = PRN(is_dlib = args.isDlib) # ------------- load data image_folder = args.inputDir save_folder = args.outputDir if not os.path.exists(save_folder): os.mkdir(save_folder) # types = ('*.jpg', '*.png') # image_path_list= [] # for files in types: # image_path_list.extend(glob(os.path.join(image_folder, files))) # total_num = len(image_path_list) for dir, dirs, files in sorted(os.walk(image_folder)): for file in files: image_path = os.path.join(dir, file) dir = dir.replace("\\", "/") new_dir = dir.replace(image_folder, save_folder) if not os.path.isdir(new_dir): os.mkdir(new_dir) name = image_path.replace(image_folder, save_folder) print('data path:', name) # read image image = imread(image_path) [h, w, c] = image.shape if c>3: image = image[:,:,:3] # the core: regress position map if args.isDlib: max_size = max(image.shape[0], image.shape[1]) if max_size> 1000: image = rescale(image, 1000./max_size) image = (image*255).astype(np.uint8) pos = prn.process(image) # use dlib to detect face else: # if image.shape[0] == image.shape[1]: # image = resize(image, (256,256)) # pos = prn.net_forward(image/255.) # input image has been cropped to 256x256 # else: box = np.array([0, image.shape[1]-1, 0, image.shape[0]-1]) # cropped with bounding box pos = prn.process(image, box) image = image/255. if pos is None: continue if args.is3d or args.isMat or args.isPose or args.isShow: # 3D vertices vertices = prn.get_vertices(pos) if args.isFront: save_vertices = frontalize(vertices) else: save_vertices = vertices.copy() save_vertices[:,1] = h - 1 - save_vertices[:,1] if args.isImage: imsave(name, image) if args.is3d: # corresponding colors colors = prn.get_colors(image, vertices) if args.isTexture: if args.texture_size != 256: pos_interpolated = resize(pos, (args.texture_size, args.texture_size), preserve_range = True) else: pos_interpolated = pos.copy() texture = cv2.remap(image, pos_interpolated[:,:,:2].astype(np.float32), None, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT,borderValue=(0)) if args.isMask: vertices_vis = get_visibility(vertices, prn.triangles, h, w) uv_mask = get_uv_mask(vertices_vis, prn.triangles, prn.uv_coords, h, w, prn.resolution_op) uv_mask = resize(uv_mask, (args.texture_size, args.texture_size), preserve_range = True) texture = texture*uv_mask[:,:,np.newaxis] write_obj_with_texture(name.replace('.jpg', '.obj'), save_vertices, prn.triangles, texture, prn.uv_coords/prn.resolution_op)#save 3d face with texture(can open with meshlab) else: write_obj_with_colors(name.replace('.jpg', '.obj'), save_vertices, prn.triangles, colors) #save 3d face(can open with meshlab) filepath = name.replace('.jpg', '.obj') filepath = filepath.replace("\\", "/") print('filepath:', filepath) new_dir = dir.replace(args.inputDir, args.renderDir) # print(new_dir + '/' + file) if not os.path.isdir(new_dir): os.mkdir(new_dir) color_image1, _ = render_scene(filepath, 4.0, 0.0, 3.0) color_image2, _ = render_scene(filepath, 4.0, np.pi / 18.0, 3.0) color_image3, _ = render_scene(filepath, 4.0, np.pi / 9.0, 3.0) if color_image1 is None or color_image2 is None: continue new_path = filepath.replace(args.outputDir, args.renderDir) # print('new_path:', new_path) save_image(new_path, '_40_', color_image1) save_image(new_path, '_50_', color_image2) save_image(new_path, '_60_', color_image3) os.remove(name.replace('.jpg', '.obj')) if args.isDepth: depth_image = get_depth_image(vertices, prn.triangles, h, w, True) depth = get_depth_image(vertices, prn.triangles, h, w) imsave(os.path.join(name.replace('.jpg', '_depth.jpg')), depth_image) sio.savemat(name.replace('.jpg', '_depth.mat'), {'depth': depth}) if args.isMat: sio.savemat(name.replace('.jpg', '_mesh.mat'), {'vertices': vertices, 'colors': colors, 'triangles': prn.triangles}) if args.isKpt or args.isShow: # get landmarks kpt = prn.get_landmarks(pos) np.savetxt(name.replace('.jpg', '_kpt.txt'), kpt) if args.isPose or args.isShow: # estimate pose camera_matrix, pose = estimate_pose(vertices) np.savetxt(name.replace('.jpg', '_pose.txt'), pose) np.savetxt(name.replace('.jpg', '_camera_matrix.txt'), camera_matrix) np.savetxt(name.replace('.jpg', '_pose.txt'), pose) if args.isShow: # ---------- Plot image_pose = plot_pose_box(image, camera_matrix, kpt) cv2.imshow('sparse alignment', plot_kpt(image, kpt)) cv2.imshow('dense alignment', plot_vertices(image, vertices)) cv2.imshow('pose', plot_pose_box(image, camera_matrix, kpt)) cv2.waitKey(0)
def main(args): if args.isShow or args.isTexture: import cv2 from utils.cv_plot import plot_kpt, plot_vertices, plot_pose_box # ---- init PRN os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu # GPU number, -1 for CPU prn = PRN(is_dlib = args.isDlib) # ------------- load data image_folder = args.inputDir save_folder = args.outputDir if not os.path.exists(save_folder): os.mkdir(save_folder) types = ('*.jpg', '*.png') image_path_list= [] for files in types: image_path_list.extend(glob(os.path.join(image_folder, files))) total_num = len(image_path_list) for i, image_path in enumerate(image_path_list): name = image_path.strip().split('/')[-1][:-4] # read image image = imread(image_path) [h, w, _] = image.shape # the core: regress position map if args.isDlib: max_size = max(image.shape[0], image.shape[1]) if max_size> 1000: image = rescale(image, 1000./max_size) pos = prn.process(image) # use dlib to detect face else: if image.shape[1] == image.shape[2]: image = resize(image, (256,256)) pos = prn.net_forward(image/255.) # input image has been cropped to 256x256 else: box = np.array([0, image.shape[1]-1, 0, image.shape[0]-1]) # cropped with bounding box pos = prn.process(image, box) image = image/255. if pos is None: continue if args.is3d or args.isMat or args.isPose or args.isShow: # 3D vertices vertices = prn.get_vertices(pos) if args.isFront: save_vertices = frontalize(vertices) else: save_vertices = vertices if args.isImage: imsave(os.path.join(save_folder, name + '.jpg'), image) if args.is3d: # corresponding colors colors = prn.get_colors(image, vertices) if args.isTexture: texture = cv2.remap(image, pos[:,:,:2].astype(np.float32), None, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT,borderValue=(0)) if args.isMask: vertices_vis = get_visibility(vertices, prn.triangles, h, w) uv_mask = get_uv_mask(vertices_vis, prn.triangles, prn.uv_coords, h, w, prn.resolution_op) texture = texture*uv_mask[:,:,np.newaxis] write_obj_with_texture(os.path.join(save_folder, name + '.obj'), save_vertices, colors, prn.triangles, texture, prn.uv_coords/prn.resolution_op)#save 3d face with texture(can open with meshlab) else: write_obj(os.path.join(save_folder, name + '.obj'), save_vertices, colors, prn.triangles) #save 3d face(can open with meshlab) if args.isDepth: depth_image = get_depth_image(vertices, prn.triangles, h, w) imsave(os.path.join(save_folder, name + '_depth.jpg'), depth_image) if args.isMat: sio.savemat(os.path.join(save_folder, name + '_mesh.mat'), {'vertices': save_vertices, 'colors': colors, 'triangles': prn.triangles}) if args.isKpt or args.isShow: # get landmarks kpt = prn.get_landmarks(pos) np.savetxt(os.path.join(save_folder, name + '_kpt.txt'), kpt) if args.isPose or args.isShow: # estimate pose camera_matrix, pose = estimate_pose(vertices) np.savetxt(os.path.join(save_folder, name + '_pose.txt'), pose) if args.isShow: # ---------- Plot image_pose = plot_pose_box(image, camera_matrix, kpt) cv2.imshow('sparse alignment', plot_kpt(image, kpt)) cv2.imshow('dense alignment', plot_vertices(image, vertices)) cv2.imshow('pose', plot_pose_box(image, camera_matrix, kpt)) cv2.waitKey(0)
for i, image_path in enumerate(image_path_list): # read image image = imread(image_path) # the core: regress position map if 'AFLW2000' in image_path: mat_path = image_path.replace('jpg', 'mat') info = sio.loadmat(mat_path) kpt = info['pt3d_68'] pos = prn.process( image, kpt ) # kpt information is only used for detecting face and cropping image else: pos = prn.process(image) # use dlib to detect face vertices = prn.get_vertices(pos) # get 3D vertices triangles = prn.triangles # get triangles depth_buffer, depth_map = get_depth_image( vertices, triangles, 500, 500) # get depth buffer and depth map with size (500,500) depth_buffer = np.array(depth_buffer) rmin, rmax, cmin, cmax = bbox2(depth_buffer) # centralize the depth map depth_buffer = depth_buffer[rmin:rmax, cmin:cmax] #depth_buffer = cv2.resize(depth_buffer,(32,32),interpolation=cv2.INTER_CUBIC) name = image_path.strip().split('/')[-1][:-4] imsave((os.path.join(save_folder, name + '.jpg')), depth_buffer) # save depth map np.savetxt(os.path.join(save_folder, name + '.txt'), depth_buffer) # save depth matrix
def main(args): if args.isShow or args.isTexture: import cv2 from utils.cv_plot import plot_kpt, plot_vertices, plot_pose_box # ---- init PRN os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu # GPU number, -1 for CPU prn = PRN(is_dlib = args.isDlib) # ------------- load data image_folder = args.inputDir print(image_folder) save_folder = args.outputDir print(save_folder) if not os.path.exists(save_folder): os.mkdir(save_folder) meta_save_folder = os.path.join(save_folder, 'meta') if not os.path.exists(meta_save_folder): os.mkdir(meta_save_folder) types = ('*.jpg', '*.png', '*,JPG') image_path_list= find_files(image_folder, ('.jpg', '.png', '.JPG')) total_num = len(image_path_list) print(image_path_list) for i, image_path in enumerate(image_path_list): name = image_path.strip().split('/')[-1][:-4] print(image_path) # read image image = imread(image_path) [h, w, c] = image.shape if c>3: image = image[:,:,:3] # the core: regress position map if args.isDlib: max_size = max(image.shape[0], image.shape[1]) if max_size> 1000: image = rescale(image, 1000./max_size) image = (image*255).astype(np.uint8) pos = prn.process(image) # use dlib to detect face else: if image.shape[1] == image.shape[2]: image = resize(image, (256,256)) pos = prn.net_forward(image/255.) # input image has been cropped to 256x256 else: box = np.array([0, image.shape[1]-1, 0, image.shape[0]-1]) # cropped with bounding box pos = prn.process(image, box) image = image/255. if pos is None: continue if args.is3d or args.isMat or args.isPose or args.isShow: # 3D vertices vertices = prn.get_vertices(pos) if args.isFront: save_vertices = frontalize(vertices) else: save_vertices = vertices.copy() save_vertices[:,1] = h - 1 - save_vertices[:,1] if args.isImage: imsave(os.path.join(save_folder, name + '.jpg'), image) if args.is3d: # corresponding colors colors = prn.get_colors(image, vertices) if args.isTexture: if args.texture_size != 256: pos_interpolated = resize(pos, (args.texture_size, args.texture_size), preserve_range = True) else: pos_interpolated = pos.copy() texture = cv2.remap(image, pos_interpolated[:,:,:2].astype(np.float32), None, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT,borderValue=(0)) if args.isMask: vertices_vis = get_visibility(vertices, prn.triangles, h, w) uv_mask = get_uv_mask(vertices_vis, prn.triangles, prn.uv_coords, h, w, prn.resolution_op) uv_mask = resize(uv_mask, (args.texture_size, args.texture_size), preserve_range = True) texture = texture*uv_mask[:,:,np.newaxis] write_obj_with_texture(os.path.join(save_folder, name + '.obj'), save_vertices, prn.triangles, texture, prn.uv_coords/prn.resolution_op)#save 3d face with texture(can open with meshlab) else: write_obj_with_colors(os.path.join(save_folder, name + '.obj'), save_vertices, prn.triangles, colors) #save 3d face(can open with meshlab) if args.isDepth: depth_image = get_depth_image(vertices, prn.triangles, h, w, True) depth = get_depth_image(vertices, prn.triangles, h, w) imsave(os.path.join(save_folder, name + '_depth.jpg'), depth_image) sio.savemat(os.path.join(meta_save_folder, name + '_depth.mat'), {'depth':depth}) if args.isMat: sio.savemat(os.path.join(meta_save_folder, name + '_mesh.mat'), {'vertices': vertices, 'colors': colors, 'triangles': prn.triangles}) if args.isKpt or args.isShow: # get landmarks kpt = prn.get_landmarks(pos) # pdb.set_trace() np.save(os.path.join(meta_save_folder, name + '_kpt.npy'), kpt) # cv2.imwrite(os.path.join(save_folder, name + '_skpt.jpg'), plot_kpt(image, kpt)) if args.isPose or args.isShow: # estimate pose camera_matrix, pose = estimate_pose(vertices) np.savetxt(os.path.join(meta_save_folder, name + '_pose.txt'), pose) np.savetxt(os.path.join(meta_save_folder, name + '_camera_matrix.txt'), camera_matrix) if args.isShow: # ---------- Plot image = imread(os.path.join(save_folder, name + '.jpg')) image_pose = plot_pose_box(image, camera_matrix, kpt) #cv2.imwrite(os.path.join(save_folder, name + '_pose.jpg'), plot_kpt(image, kpt)) #cv2.imwrite(os.path.join(save_folder, name + '_camera_matrix.jpg'), plot_vertices(image, vertices)) #cv2.imwrite(os.path.join(save_folder, name + '_pose.jpg'), plot_pose_box(image, camera_matrix, kpt)) image = imread(os.path.join(save_folder, name + '.jpg')) b, g, r = cv2.split(image) image = cv2.merge([r,g,b])
def main(args): if args.isShow or args.isTexture or args.isCamera: import cv2 from utils.cv_plot import plot_kpt, plot_vertices, plot_pose_box # ---- init PRN os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu # GPU number, -1 for CPU prn = PRN(is_dlib=args.isDlib) # ------------- load data image_folder = args.inputDir save_folder = args.outputDir if not os.path.exists(save_folder): os.mkdir(save_folder) types = ('*.jpg', '*.png') image_path_list = [] for files in types: image_path_list.extend(glob(os.path.join(image_folder, files))) total_num = len(image_path_list) if args.isCamera: # Create a VideoCapture object and read from input file # If the input is the camera, pass 0 instead of the video file name cap = cv2.VideoCapture(0) # Check if camera opened successfully if (cap.isOpened() == False): print("Error opening video stream or file") # Read until video is completed while (cap.isOpened()): # Capture frame-by-frame ret, frame = cap.read() if ret == True: if args.isDlib: max_size = max(frame.shape[0], frame.shape[1]) if max_size > 1000: frame = rescale(frame, 1000. / max_size) frame = (frame * 255).astype(np.uint8) pos = prn.process(frame) # use dlib to detect face else: if frame.shape[0] == frame.shape[1]: frame = resize(frame, (256, 256)) pos = prn.net_forward( frame / 255.) # input frame has been cropped to 256x256 else: box = np.array( [0, frame.shape[1] - 1, 0, frame.shape[0] - 1]) # cropped with bounding box pos = prn.process(frame, box) # Normalizing the frame and skiping if there was no one in the frame frame = frame / 255. if pos is None: continue # Get landmarks in frame kpt = prn.get_landmarks(pos) # Display the resulting frame cv2.imshow('sparse alignment', plot_kpt(frame, kpt)) # Press Q on keyboard to exit if cv2.waitKey(25) & 0xFF == ord('q'): break # Break the loop else: break # When everything done, release the video capture object cap.release() # Closes all the frames cv2.destroyAllWindows() else: for i, image_path in enumerate(image_path_list): name = image_path.strip().split('/')[-1][:-4] # read image image = imread(image_path) [h, w, c] = image.shape if c > 3: image = image[:, :, :3] # the core: regress position map if args.isDlib: max_size = max(image.shape[0], image.shape[1]) if max_size > 1000: image = rescale(image, 1000. / max_size) image = (image * 255).astype(np.uint8) pos = prn.process(image) # use dlib to detect face else: if image.shape[0] == image.shape[1]: image = resize(image, (256, 256)) pos = prn.net_forward( image / 255.) # input image has been cropped to 256x256 else: box = np.array( [0, image.shape[1] - 1, 0, image.shape[0] - 1]) # cropped with bounding box pos = prn.process(image, box) image = image / 255. if pos is None: continue if args.is3d or args.isMat or args.isPose or args.isShow: # 3D vertices vertices = prn.get_vertices(pos) if args.isFront: save_vertices = frontalize(vertices) else: save_vertices = vertices.copy() save_vertices[:, 1] = h - 1 - save_vertices[:, 1] if args.isImage: imsave(os.path.join(save_folder, name + '.jpg'), image) if args.is3d: # corresponding colors colors = prn.get_colors(image, vertices) if args.isTexture: if args.texture_size != 256: pos_interpolated = resize( pos, (args.texture_size, args.texture_size), preserve_range=True) else: pos_interpolated = pos.copy() texture = cv2.remap(image, pos_interpolated[:, :, :2].astype( np.float32), None, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0)) if args.isMask: vertices_vis = get_visibility(vertices, prn.triangles, h, w) uv_mask = get_uv_mask(vertices_vis, prn.triangles, prn.uv_coords, h, w, prn.resolution_op) uv_mask = resize( uv_mask, (args.texture_size, args.texture_size), preserve_range=True) texture = texture * uv_mask[:, :, np.newaxis] write_obj_with_texture( os.path.join(save_folder, name + '.obj'), save_vertices, prn.triangles, texture, prn.uv_coords / prn.resolution_op ) #save 3d face with texture(can open with meshlab) else: write_obj_with_colors( os.path.join(save_folder, name + '.obj'), save_vertices, prn.triangles, colors) #save 3d face(can open with meshlab) if args.isDepth: depth_image = get_depth_image(vertices, prn.triangles, h, w, True) depth = get_depth_image(vertices, prn.triangles, h, w) imsave(os.path.join(save_folder, name + '_depth.jpg'), depth_image) sio.savemat(os.path.join(save_folder, name + '_depth.mat'), {'depth': depth}) if args.isMat: sio.savemat( os.path.join(save_folder, name + '_mesh.mat'), { 'vertices': vertices, 'colors': colors, 'triangles': prn.triangles }) if args.isKpt or args.isShow: # get landmarks kpt = prn.get_landmarks(pos) np.savetxt(os.path.join(save_folder, name + '_kpt.txt'), kpt) if args.isPose or args.isShow: # estimate pose camera_matrix, pose = estimate_pose(vertices) np.savetxt(os.path.join(save_folder, name + '_pose.txt'), pose) np.savetxt( os.path.join(save_folder, name + '_camera_matrix.txt'), camera_matrix) np.savetxt(os.path.join(save_folder, name + '_pose.txt'), pose) if args.isShow: # ---------- Plot image_pose = plot_pose_box(image, camera_matrix, kpt) cv2.imshow( 'sparse alignment', cv2.cvtColor(np.float32(plot_kpt(image, kpt)), cv2.COLOR_RGB2BGR)) cv2.imshow( 'dense alignment', cv2.cvtColor(np.float32(plot_vertices(image, vertices)), cv2.COLOR_RGB2BGR)) cv2.imshow( 'pose', cv2.cvtColor( np.float32(plot_pose_box(image, camera_matrix, kpt)), cv2.COLOR_RGB2BGR)) cv2.waitKey(0)