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