Нет описания
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

people_Allunq_zero_maingallery.py 14KB

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