Ei kuvausta
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.

myproject.py 16KB

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