暫無描述
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.

attendence.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. from flask import Flask, render_template, request, redirect, Response, send_file
  2. import multiprocessing
  3. import face_recognition
  4. #from numba import jit
  5. import numpy as np
  6. import os
  7. #from flask_cors import CORS
  8. app = Flask(__name__)
  9. #CORS(app)
  10. lst = []
  11. Gallery="Gallery"
  12. People='People'
  13. @app.route('/', methods=['GET'])
  14. def resume():
  15. #return render_template('index.html')
  16. return 'Attendence app running'
  17. def createEncodings(image):
  18. print("Encoding")
  19. """
  20. Create face encodings for a given image and also return face locations in the given image.
  21. Parameters
  22. -------
  23. image : cv2 mat
  24. Image you want to detect faces from.
  25. Returns
  26. -------
  27. known_encodings : list of np array
  28. List of face encodings in a given image
  29. face_locations : list of tuples
  30. list of tuples for face locations in a given image
  31. """
  32. # Find face locations for all faces in an image
  33. face_locations = face_recognition.face_locations(image)
  34. # Create encodings for all faces in an image
  35. known_encodings = face_recognition.face_encodings(image, known_face_locations=face_locations)
  36. return known_encodings, face_locations
  37. #@app.route('/registered', methods=["POST","GET"])
  38. def registered(url_list):
  39. input=url_list
  40. from pathlib import Path
  41. Path(People).mkdir(exist_ok=True)
  42. Path(People+"/" + input["FileName"]).mkdir(exist_ok=True)
  43. a = input
  44. # print(a)
  45. x = a['FileData']
  46. # print(x)
  47. y = a['FileName']
  48. #z = a['FileType']
  49. z='jpg'
  50. # CreatedBy=a['CreatedBy']
  51. name = y+ '.'+ z
  52. print(name)
  53. # print(y)
  54. # image = y.split("/")
  55. # filename=image[-1]
  56. # print(x)
  57. try:
  58. img_data = x.encode()
  59. except AttributeError:
  60. return "Successfully saved encoding........."
  61. import base64
  62. with open(People+"/" + input["FileName"] + "/" + name, "wb") as fh:
  63. fh.write(base64.decodebytes(img_data))
  64. img = People+"/" + y + "/" + name
  65. saveLocation = People+"/" + y + "/" + y + ".pickle"
  66. ############ detecting no of faceses #######################
  67. # import cv2
  68. # import numpy as np
  69. # import dlib
  70. # # Connects to your computer's default camera
  71. # cap = cv2.imread(img)
  72. # # Detect the coordinates
  73. # detector = dlib.get_frontal_face_detector()
  74. # number_of_faces=[]
  75. # # Capture frames continuously
  76. # # while True:
  77. # # Capture frame-by-frame
  78. # # ret, frame = cap
  79. # frame = cap
  80. # # RGB to grayscale
  81. # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  82. # faces = detector(gray)
  83. # # Iterator to count faces
  84. # i = 0
  85. # for face in faces:
  86. # # Get the coordinates of faces
  87. # x, y = face.left(), face.top()
  88. # x1, y1 = face.right(), face.bottom()
  89. # cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)
  90. # # Increment iterator for each face in faces
  91. # i = i+1
  92. # # Display the box and faces
  93. # cv2.putText(frame, 'face num'+str(i), (x-10, y-10),
  94. # cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
  95. # # if len(i)>1:
  96. # # print(i)
  97. # number_of_faces.append(i)
  98. # if (len(number_of_faces))>1:
  99. # print("Group Photo")
  100. # return "Group Photo"
  101. # elif (len(number_of_faces))==1:
  102. # print("Single Photo")
  103. # pass
  104. def saveEncodings(encs, names, fname='encodings.pickle'):
  105. """
  106. Save encodings in a pickle file to be used in future.
  107. Parameters
  108. ----------
  109. encs : List of np arrays
  110. List of face encodings.
  111. names : List of strings
  112. List of names for each face encoding.
  113. fname : String, optional
  114. Name/Location for pickle file. The default is "encodings.pickle".
  115. Returns
  116. -------
  117. None.
  118. """
  119. data = []
  120. d = [{"name": nm, "encoding": enc} for (nm, enc) in zip(names, encs)]
  121. data.extend(d)
  122. encodingsFile = fname
  123. # dump the facial encodings data to disk
  124. print("[INFO] serializing encodings...")
  125. print("[INFO] Encodings Created sucessfully")
  126. f = open(encodingsFile, "wb")
  127. f.write(pickle.dumps(data))
  128. f.close()
  129. # Function to create encodings and get face locations
  130. def processKnownPeopleImages(img=img, saveLocation=saveLocation):
  131. """
  132. Process images of known people and create face encodings to compare in future.
  133. Eaach image should have just 1 face in it.
  134. Parameters
  135. ----------
  136. path : STRING, optional
  137. Path for known people dataset. The default is "C:/inetpub/vhosts/port82/wwwroot/_files/People".
  138. It should be noted that each image in this dataset should contain only 1 face.
  139. saveLocation : STRING, optional
  140. Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory".
  141. Returns
  142. -------
  143. None.
  144. """
  145. known_encodings = []
  146. known_names = []
  147. # for img in os.listdir(path):
  148. imgPath = img
  149. # Read image
  150. image = cv2.imread(imgPath)
  151. name = img.rsplit('.')[0]
  152. # Resize
  153. try:
  154. print(image.shape)
  155. except AttributeError:
  156. return "Successfully saved encoding........."
  157. image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR)
  158. # Get locations and encodings
  159. encs, locs = createEncodings(image)
  160. try:
  161. known_encodings.append(encs[0])
  162. except IndexError:
  163. os.remove(saveLocation)
  164. print('------------------------------------- save location --------------------------------')
  165. print(saveLocation)
  166. return "hello world!"
  167. # known_encodings.append(encs[0])
  168. known_names.append(name)
  169. for loc in locs:
  170. top, right, bottom, left = loc
  171. # Show Image
  172. # cv2.rectangle(image, (left, top), (right, bottom), color=(255, 0, 0), thickness=2)
  173. # cv2.imshow("Image", image)
  174. # cv2.waitKey(1)
  175. # cv2.destroyAllWindows()
  176. saveEncodings(known_encodings, known_names, saveLocation)
  177. import cv2
  178. #import face_recognition
  179. import pickle
  180. processKnownPeopleImages(img, saveLocation)
  181. return 'Successfully saved encoding.........'
  182. # ******************************** COMPARUISION *********************************************************
  183. #@app.route('/submit', methods=["POST","GET"])
  184. def submit(url_list):
  185. from datetime import datetime
  186. import pytz
  187. tz_NY = pytz.timezone('Asia/Kolkata')
  188. datetime_NY = datetime.now(tz_NY)
  189. India_Date = (datetime_NY.strftime("%Y-%m-%d"))
  190. India_Date = str(India_Date)
  191. # India_Time = (datetime_NY.strftime("%I:%M:%S %p"))
  192. # India_Time = str(India_Time)
  193. input=url_list
  194. import pickle
  195. import cv2
  196. from pathlib import Path
  197. Path(Gallery).mkdir(exist_ok=True)
  198. Path(Gallery+"/"+ India_Date).mkdir(exist_ok=True)
  199. Path(Gallery+"/"+ India_Date +'/'+ input["FileName"]).mkdir(exist_ok=True)
  200. a = input
  201. # print(a)
  202. x = a['FileData']
  203. # print(x)
  204. y = a['FileName']
  205. # z = a['FileType']
  206. z='jpg'
  207. # CreatedBy=a['CreatedBy']
  208. name = y + '.' + z
  209. # print(name)
  210. # print(y)
  211. # image = y.split("/")
  212. # filename=image[-1]
  213. # print(x)
  214. img_data = x.encode()
  215. import base64
  216. with open(Gallery+"/"+India_Date+'/' + input["FileName"] + "/" + name, "wb") as fh:
  217. fh.write(base64.decodebytes(img_data))
  218. path = Gallery+"/" +India_Date+'/'+ y + "/" + name
  219. pickle_location = People+"/" + y + "/" + y + ".pickle"
  220. import pathlib
  221. file = pathlib.Path(pickle_location)
  222. if file.exists ():
  223. pass
  224. else:
  225. print ("pickle File not exist")
  226. print(name)
  227. return "Please get registered with your Profile Picture",500
  228. # return "Face not found in profile (please change your profile)",500
  229. check_faces=People+"/" + y + "/" + y + ".jpg"
  230. print(check_faces)
  231. ############ detecting no of faceses #######################
  232. import cv2
  233. import numpy as np
  234. import dlib
  235. # Connects to your computer's default camera
  236. cap = cv2.imread(check_faces)
  237. # Detect the coordinates
  238. detector = dlib.get_frontal_face_detector()
  239. number_of_faces=[]
  240. # Capture frames continuously
  241. # while True:
  242. # Capture frame-by-frame
  243. # ret, frame = cap
  244. frame = cap
  245. # RGB to grayscale
  246. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  247. faces = detector(gray)
  248. # Iterator to count faces
  249. i = 0
  250. for face in faces:
  251. # Get the coordinates of faces
  252. x, y = face.left(), face.top()
  253. x1, y1 = face.right(), face.bottom()
  254. cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)
  255. # Increment iterator for each face in faces
  256. i = i+1
  257. # Display the box and faces
  258. cv2.putText(frame, 'face num'+str(i), (x-10, y-10),
  259. cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
  260. # if len(i)>1:
  261. # print(i)
  262. number_of_faces.append(i)
  263. if (len(number_of_faces))>1:
  264. print("Group Photo")
  265. return "Too Many Faces in Profile Picture",500
  266. elif (len(number_of_faces))==1:
  267. print("Single Photo")
  268. pass
  269. def readEncodingsPickle(fname):
  270. """
  271. Read Pickle file.
  272. Parameters
  273. ----------
  274. fname : String
  275. Name of pickle file.(Full location)
  276. Returns
  277. -------
  278. encodings : list of np arrays
  279. list of all saved encodings
  280. names : List of Strings
  281. List of all saved names
  282. """
  283. data = pickle.loads(open(fname, "rb").read())
  284. data = np.array(data)
  285. encodings = [d["encoding"] for d in data]
  286. names = [d["name"] for d in data]
  287. return encodings, names
  288. def compareFaceEncodings(unknown_encoding, known_encodings, known_names):
  289. """
  290. Compares face encodings to check if 2 faces are same or not.
  291. Parameters
  292. ----------
  293. unknown_encoding : np array
  294. Face encoding of unknown people.
  295. known_encodings : np array
  296. Face encodings of known people.
  297. known_names : list of strings
  298. Names of known people
  299. Returns
  300. -------
  301. acceptBool : Bool
  302. face matched or not
  303. duplicateName : String
  304. Name of matched face
  305. distance : Float
  306. Distance between 2 faces
  307. """
  308. duplicateName = ""
  309. distance = 0.0
  310. matches = face_recognition.compare_faces(known_encodings, unknown_encoding, tolerance=0.54)
  311. face_distances = face_recognition.face_distance(known_encodings, unknown_encoding)
  312. best_match_index = np.argmin(face_distances)
  313. distance = face_distances[best_match_index]
  314. if matches[best_match_index]:
  315. acceptBool = True
  316. duplicateName = known_names[best_match_index]
  317. else:
  318. acceptBool = False
  319. duplicateName = ""
  320. return acceptBool, duplicateName, distance
  321. #p = []
  322. def processDatasetImages(path=path, pickle_location=pickle_location):
  323. """
  324. Process image in dataset from where you want to separate images.
  325. It separates the images into directories of known people, groups and any unknown people images.
  326. Parameters
  327. ----------
  328. path : STRING, optional
  329. Path for known people dataset. The default is "D:/port1004/port1004/wwwroot/_files/People".
  330. It should be noted that each image in this dataset should contain only 1 face.
  331. saveLocation : STRING, optional
  332. Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory".
  333. Returns
  334. -------
  335. None.
  336. """
  337. # Read pickle file for known people to compare faces from
  338. people_encodings, names = readEncodingsPickle(pickle_location)
  339. # print(p)
  340. # imgPath = path + img
  341. # Read image
  342. # path=r"C:\Users\katku\Pictures\final\100011460000611.jpg"
  343. image = cv2.imread(path)
  344. #orig = image.copy()
  345. # Resize
  346. image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR)
  347. # Get locations and encodings
  348. encs, locs = createEncodings(image)
  349. # Save image to a group image folder if more than one face is in image
  350. # if len(locs) > 1:
  351. # saveImageToDirectory(orig, "Group", img)
  352. # Processing image for each face
  353. i = 0
  354. knownFlag = 0
  355. for loc in locs:
  356. top, right, bottom, left = loc
  357. unknown_encoding = encs[i]
  358. i += 1
  359. acceptBool, duplicateName, distance = compareFaceEncodings(unknown_encoding, people_encodings, names)
  360. if acceptBool:
  361. # saveImageToDirectory(orig, duplicateName,name)
  362. knownFlag = 1
  363. if knownFlag == 1:
  364. print("Match Found")
  365. #print(path)
  366. with_extension = path.split("/")[-1]
  367. without_extension = with_extension.split(".")[0]
  368. # output_s = {"FileID": without_extension,
  369. # "Date": India_Date,
  370. # "Time": India_Time}
  371. # output_json = json.dumps(output_s)
  372. output_json='Matched successfully'
  373. print(loc)
  374. lst.append(output_json)
  375. print(output_json)
  376. # exit()
  377. else:
  378. print('Not Matched')
  379. pass
  380. # saveImageToDirectory(orig, "0",name)
  381. import numpy as np
  382. import json
  383. processDatasetImages(path, pickle_location)
  384. return lst[0]
  385. #return 'matched successfully'
  386. @app.route('/detect', methods=["POST"])
  387. def detect():
  388. if __name__ == "__main__":
  389. url_list=[]
  390. Dataset= request.get_json()
  391. # id = "100013660000125"
  392. url_list.append(Dataset)
  393. # multiprocessing
  394. pool_size = multiprocessing.cpu_count() * 2
  395. with multiprocessing.Pool(pool_size) as pool:
  396. try:
  397. results = pool.map(submit, url_list)
  398. except FileNotFoundError:
  399. return 'please get registered with your PhotoID',500
  400. except IndexError:
  401. #return 'unable to recognize face'
  402. #return 'failed',500
  403. return "Face does not Match with Profile Picture",500
  404. pool.close()
  405. return results[0]
  406. @app.route('/register', methods=["POST"])
  407. def register():
  408. print("hello start..........")
  409. if __name__ == "__main__":
  410. url_list=[]
  411. Dataset= request.get_json()
  412. # id = "100013660000125"
  413. url_list.append(Dataset)
  414. UserLocation=Dataset["FilePath"]
  415. print(UserLocation)
  416. # if "cO2" in UserLocation or UserLocation is None:
  417. # pass
  418. # else:
  419. # return "Please update the URL in the integration"
  420. # multiprocessing
  421. #pool_size = multiprocessing.cpu_count() * 2
  422. #with multiprocessing.Pool(pool_size) as pool:
  423. # try:
  424. # results = pool.map(registered, url_list)
  425. # except IndexError:
  426. # pass
  427. # print('face not found')
  428. # except FileNotFoundError:
  429. # pass
  430. #os.remove(img)
  431. # return 'unable to recognize face'
  432. # pool.close()
  433. #return results[0]
  434. result=registered(url_list)
  435. return 'Successfully saved encoding.........'
  436. if __name__ == "__main__":
  437. app.run(host='0.0.0.0',port =5003,debug=False)