createPCAModel.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import cv2
  5. import numpy as np
  6. # Create data matrix from a list of images
  7. def createDataMatrix(images):
  8. print("Creating data matrix",end=" ... ", flush=True)
  9. '''
  10. Allocate space for all images in one data matrix.
  11. The size of the data matrix is
  12. ( w * h * 3, numImages )
  13. where,
  14. w = width of an image in the dataset.
  15. h = height of an image in the dataset.
  16. 3 is for the 3 color channels.
  17. '''
  18. numImages = len(images)
  19. sz = images[0].shape
  20. data = np.zeros((numImages, sz[0] * sz[1] * sz[2]), dtype=np.float32)
  21. for i in range(0, numImages):
  22. image = images[i].flatten()
  23. data[i,:] = image
  24. print("DONE")
  25. return data
  26. # Read images from the directory
  27. def readImages(path):
  28. print("Reading images from " + path, end=" ... ", flush=True)
  29. # Create array of array of images.
  30. images = []
  31. # List all files in the directory and read points from text files one by one
  32. for filePath in sorted(os.listdir(path)):
  33. fileExt = os.path.splitext(filePath)[1]
  34. if fileExt in [".jpg", ".jpeg"]:
  35. # Add to array of images
  36. imagePath = os.path.join(path, filePath)
  37. im = cv2.imread(imagePath)
  38. if im is None :
  39. print("image:{} not read properly".format(imagePath))
  40. else :
  41. # Convert image to floating point
  42. im = np.float32(im)/255.0
  43. # Add image to list
  44. images.append(im)
  45. # Flip image
  46. imFlip = cv2.flip(im, 1);
  47. # Append flipped image
  48. images.append(imFlip)
  49. numImages = len(images) / 2
  50. # Exit if no image found
  51. if numImages == 0 :
  52. print("No images found")
  53. sys.exit(0)
  54. print(str(numImages) + " files read.")
  55. return images
  56. if __name__ == '__main__':
  57. # Directory containing images
  58. dirName = "images"
  59. # Read images
  60. images = readImages(dirName)
  61. # Size of images
  62. sz = images[0].shape
  63. # Create data matrix for PCA.
  64. data = createDataMatrix(images)
  65. # Compute the eigenvectors from the stack of images created
  66. print("Calculating PCA ", end=" ... ", flush=True)
  67. mean, eigenVectors = cv2.PCACompute(data, mean=None)
  68. print ("DONE")
  69. filename = "pcaParams.yml"
  70. print("Writing size, mean and eigenVectors to " + filename, end=" ... ", flush=True)
  71. file = cv2.FileStorage(filename, cv2.FILE_STORAGE_WRITE)
  72. file.write("mean", mean)
  73. file.write("eigenVectors", eigenVectors)
  74. file.write("size", sz)
  75. file.release()
  76. print("DONE")