Nenhuma descrição
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Allunq_People.py 16KB

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