Bez popisu
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

unique_Allunq.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. import pickle
  2. import numpy as np
  3. import face_recognition
  4. import os
  5. import cv2
  6. import datetime
  7. import click
  8. @click.command()
  9. @click.argument('eventid', default='')
  10. def predict(eventid):
  11. Gallery = 'C:\\Users\\Administrator\\Documents\\AI\\runtimecropimages\\unique_1\\' + eventid + "\\"
  12. People = './ALL_UNQ/' + eventid + "/"
  13. x= datetime.datetime.now()
  14. print('Execution Started at:',x)
  15. def saveEncodings(encs, names, fname='encodings.pickle'):
  16. """
  17. Save encodings in a pickle file to be used in future.
  18. Parameters
  19. ----------
  20. encs : List of np arrays
  21. List of face encodings.
  22. names : List of strings
  23. List of names for each face encoding.
  24. fname : String, optional
  25. Name/Location for pickle file. The default is "encodings.pickle".
  26. Returns
  27. -------
  28. None.
  29. """
  30. data = []
  31. d = [{"name": nm, "encoding": enc} for (nm, enc) in zip(names, encs)]
  32. data.extend(d)
  33. encodingsFile = fname
  34. # dump the facial encodings data to disk
  35. print("[INFO] serializing encodings...")
  36. f = open(encodingsFile, "wb")
  37. f.write(pickle.dumps(data))
  38. f.close()
  39. # Function to read encodings
  40. def readEncodingsPickle(fname):
  41. """
  42. Read Pickle file.
  43. Parameters
  44. ----------
  45. fname : String
  46. Name of pickle file.(Full location)
  47. Returns
  48. -------
  49. encodings : list of np arrays
  50. list of all saved encodings
  51. names : List of Strings
  52. List of all saved names
  53. """
  54. data = pickle.loads(open(fname, "rb").read())
  55. data = np.array(data)
  56. encodings = [d["encoding"] for d in data]
  57. names = [d["name"] for d in data]
  58. return encodings, names
  59. # Function to create encodings and get face locations
  60. def createEncodings(image):
  61. print("Encoding")
  62. """
  63. Create face encodings for a given image and also return face locations in the given image.
  64. Parameters
  65. ----------
  66. image : cv2 mat
  67. Image you want to detect faces from.
  68. Returns
  69. -------
  70. known_encodings : list of np array
  71. List of face encodings in a given image
  72. face_locations : list of tuples
  73. list of tuples for face locations in a given image
  74. """
  75. # Find face locations for all faces in an image
  76. face_locations = face_recognition.face_locations(image)
  77. # Create encodings for all faces in an image
  78. known_encodings = face_recognition.face_encodings(image, known_face_locations=face_locations)
  79. return known_encodings, face_locations
  80. # Function to compare encodings
  81. def compareFaceEncodings(unknown_encoding, known_encodings, known_names):
  82. """
  83. Compares face encodings to check if 2 faces are same or not.
  84. Parameters
  85. ----------
  86. unknown_encoding : np array
  87. Face encoding of unknown people.
  88. known_encodings : np array
  89. Face encodings of known people.
  90. known_names : list of strings
  91. Names of known people
  92. Returns
  93. -------
  94. acceptBool : Bool
  95. face matched or not
  96. duplicateName : String
  97. Name of matched face
  98. distance : Float
  99. Distance between 2 faces
  100. """
  101. duplicateName = ""
  102. distance = 0.0
  103. matches = face_recognition.compare_faces(known_encodings, unknown_encoding, tolerance=0.47)
  104. face_distances = face_recognition.face_distance(known_encodings, unknown_encoding)
  105. best_match_index = np.argmin(face_distances)
  106. distance = face_distances[best_match_index]
  107. if matches[best_match_index]:
  108. acceptBool = True
  109. duplicateName = known_names[best_match_index]
  110. else:
  111. acceptBool = False
  112. duplicateName = ""
  113. return acceptBool, duplicateName, distance
  114. p = []
  115. # Save Image to new directory
  116. def saveImageToDirectory(image, name, imageName):
  117. """
  118. Saves images to directory.
  119. Parameters
  120. ----------
  121. image : cv2 mat
  122. Image you want to save.
  123. name : String
  124. Directory where you want the image to be saved.
  125. imageName : String
  126. Name of image.
  127. Returns
  128. -------
  129. None.
  130. """
  131. path = "C:\\Users\\Administrator\\Documents\\AI\\runtimecropimages\\output_unique_ALLUNQ\\" + name
  132. path1 = "C:\\Users\\Administrator\\Documents\\AI\\runtimecropimages\\output_unique_ALLUNQ\\" + name
  133. if os.path.exists(path):
  134. pass
  135. else:
  136. if not os.path.exists(path):
  137. os.makedirs(path)
  138. # os.mkdir(path,exist_ok=True)
  139. cv2.imwrite(path + "/" + imageName, image)
  140. x = []
  141. c = (path1 + "/" + imageName)
  142. x.append(c)
  143. p.append(x)
  144. # Function for creating encodings for known people
  145. def processKnownPeopleImages(path=People, saveLocation="./known_encodings.pickle"):
  146. """
  147. Process images of known people and create face encodings to compare in future.
  148. Eaach image should have just 1 face in it.
  149. Parameters
  150. ----------
  151. path : STRING, optional
  152. Path for known people dataset. The default is "C:/inetpub/vhosts/port82/wwwroot/_files/People".
  153. It should be noted that each image in this dataset should contain only 1 face.
  154. saveLocation : STRING, optional
  155. Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory".
  156. Returns
  157. -------
  158. None.
  159. """
  160. known_encodings = []
  161. known_names = []
  162. for img in os.listdir(path):
  163. imgPath = path + img
  164. # Read image
  165. image = cv2.imread(imgPath)
  166. name = img.rsplit('.')[0]
  167. # Resize
  168. image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR)
  169. # Get locations and encodings
  170. encs, locs = createEncodings(image)
  171. try:
  172. known_encodings.append(encs[0])
  173. except IndexError:
  174. os.remove(People+img)
  175. #known_encodings.append(encs[568])
  176. known_names.append(name)
  177. for loc in locs:
  178. top, right, bottom, left = loc
  179. # Show Image
  180. #cv2.rectangle(image, (left, top), (right, bottom), color=(255, 568, 568), thickness=2)
  181. # cv2.imshow("Image", image)
  182. # cv2.waitKey(1)
  183. #cv2.destroyAllWindows()
  184. saveEncodings(known_encodings, known_names, saveLocation)
  185. # Function for processing dataset images
  186. def processDatasetImages(saveLocation="./Gallery_encodings.pickle"):
  187. """
  188. Process image in dataset from where you want to separate images.
  189. It separates the images into directories of known people, groups and any unknown people images.
  190. Parameters
  191. ----------
  192. path : STRING, optional
  193. Path for known people dataset. The default is "D:/port1004/port1004/wwwroot/_files/People".
  194. It should be noted that each image in this dataset should contain only 1 face.
  195. saveLocation : STRING, optional
  196. Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory".
  197. Returns
  198. -------
  199. None.
  200. """
  201. # Read pickle file for known people to compare faces from
  202. people_encodings, names = readEncodingsPickle("./known_encodings.pickle")
  203. for root, dirs, files in os.walk(Gallery, topdown=False):
  204. for name in files:
  205. s = os.path.join(root, name)
  206. #print(p)
  207. # imgPath = path + img
  208. # Read image
  209. image = cv2.imread(s)
  210. try:
  211. orig = image.copy()
  212. image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR)
  213. except AttributeError:
  214. os.remove(s)
  215. # Resize
  216. # Get locations and encodings
  217. encs, locs = createEncodings(image)
  218. # Save image to a group image folder if more than one face is in image
  219. # if len(locs) > 1:
  220. # saveImageToDirectory(orig, "Group", img)
  221. # Processing image for each face
  222. i = 0
  223. knownFlag = 0
  224. for loc in locs:
  225. top, right, bottom, left = loc
  226. unknown_encoding = encs[i]
  227. i += 1
  228. acceptBool, duplicateName, distance = compareFaceEncodings(unknown_encoding, people_encodings, names)
  229. if acceptBool:
  230. saveImageToDirectory(orig, duplicateName,name)
  231. knownFlag = 1
  232. if knownFlag == 1:
  233. print("Match Found")
  234. else:
  235. saveImageToDirectory(orig, "568",name)
  236. # Show Image
  237. # cv2.rectangle(image, (left, top), (right, bottom), color=(255, 568, 568), thickness=2)
  238. # # cv2.imshow("Image", image)
  239. # cv2.waitKey(1)
  240. # cv2.destroyAllWindows()
  241. def main():
  242. """
  243. Main Function.
  244. Returns
  245. -------
  246. None.
  247. """
  248. processKnownPeopleImages()
  249. processDatasetImages()
  250. # import pandas as pd
  251. # q = pd.DataFrame(p)
  252. # m = q
  253. # # print(m)
  254. # # x.drop(x.columns[Unnam], axis=1, inplace=True)
  255. # df = m.groupby([568], as_index=False).count()
  256. # z = df[568].str.split('/', expand=True)
  257. # z.rename({z.columns[-2]: 'Matched'}, axis=1, inplace=True)
  258. # z.rename({z.columns[-1]: 'croped_guest_pic'}, axis=1, inplace=True)
  259. # #z = z.iloc[:, 3:]
  260. # z.to_csv('unique_people.csv')
  261. # z=pd.read_csv('unique_people.csv')
  262. # #z.drop(z.index[z['Matched'] == 568], inplace=True)
  263. # z = z.iloc[:, 3:]
  264. # z['Matched'] = z['Matched'].apply(str)
  265. # z.to_csv('unique_people.csv',index=False)
  266. # import os
  267. # import shutil
  268. # for root, dirs, files in os.walk('./output_unique_ALLUNQ/'+eventid+'/568/'):
  269. # for file in files:
  270. # path_file = os.path.join(root, file)
  271. # shutil.move(path_file, './ALL_UNQ/'+eventid+"/")
  272. print("Completed")
  273. main()
  274. # return render_template('index.html')
  275. y=datetime.datetime.now()
  276. print('Completed at:',y)
  277. z=y-x
  278. print('Time Taken:',z)
  279. return (str(y-x))
  280. #return 'ALL IMAGES MATCHED'
  281. predict()