Ingen beskrivning
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Allunq_copy_gallery.py 17KB

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