reconstructFace.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # Import necessary packages
  2. import os
  3. import sys
  4. import cv2
  5. import numpy as np
  6. '''
  7. Display result
  8. Left = Original Image
  9. Right = Reconstructed Face
  10. '''
  11. def displayResult(left, right) :
  12. output = np.hstack((left,right))
  13. output = cv2.resize(output, (0,0), fx=4, fy=4)
  14. cv2.imshow("Result", output)
  15. # Recontruct face using mean face and EigenFaces
  16. def reconstructFace(*args):
  17. # Start with the mean / average face
  18. output = averageFace
  19. for i in range(0,args[0]):
  20. '''
  21. The weight is the dot product of the mean subtracted
  22. image vector with the EigenVector
  23. '''
  24. weight = np.dot(imVector, eigenVectors[i])
  25. output = output + eigenFaces[i] * weight
  26. displayResult(im, output)
  27. if __name__ == '__main__':
  28. # Read model file
  29. modelFile = "pcaParams.yml"
  30. print("Reading model file " + modelFile, end=" ... ", flush=True)
  31. file = cv2.FileStorage(modelFile, cv2.FILE_STORAGE_READ)
  32. # Extract mean vector
  33. mean = file.getNode("mean").mat()
  34. # Extract Eigen Vectors
  35. eigenVectors = file.getNode("eigenVectors").mat()
  36. # Extract size of the images used in training.
  37. sz = file.getNode("size").mat()
  38. sz = (int(sz[0,0]), int(sz[1,0]), int(sz[2,0]))
  39. '''
  40. Extract maximum number of EigenVectors.
  41. This is the max(numImagesUsedInTraining, w * h * 3)
  42. where w = width, h = height of the training images.
  43. '''
  44. numEigenFaces = eigenVectors.shape[0]
  45. print("DONE")
  46. # Extract mean vector and reshape it to obtain average face
  47. averageFace = mean.reshape(sz)
  48. # Reshape Eigenvectors to obtain EigenFaces
  49. eigenFaces = []
  50. for eigenVector in eigenVectors:
  51. eigenFace = eigenVector.reshape(sz)
  52. eigenFaces.append(eigenFace)
  53. # Read new test image. This image was not used in traning.
  54. imageFilename = "test/satya2.jpg"
  55. print("Read image " + imageFilename + " and vectorize ", end=" ... ");
  56. im = cv2.imread(imageFilename)
  57. im = np.float32(im)/255.0
  58. # Reshape image to one long vector and subtract the mean vector
  59. imVector = im.flatten() - mean;
  60. print("Done");
  61. # Show mean face first
  62. output = averageFace
  63. # Create window for displaying result
  64. cv2.namedWindow("Result", cv2.WINDOW_AUTOSIZE)
  65. # Changing the slider value changes the number of EigenVectors
  66. # used in reconstructFace.
  67. cv2.createTrackbar( "No. of EigenFaces", "Result", 0, numEigenFaces, reconstructFace)
  68. # Display original image and the reconstructed image size by side
  69. displayResult(im, output)
  70. cv2.waitKey(0)
  71. cv2.destroyAllWindows()