Açıklama Yok
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.

test_attendence.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 "Face not found in profile (please change your profile)"
  228. check_faces=People+"/" + y + "/" + y + ".jpg"
  229. print(check_faces)
  230. ############ detecting no of faceses #######################
  231. import cv2
  232. import numpy as np
  233. import dlib
  234. # Connects to your computer's default camera
  235. cap = cv2.imread(check_faces)
  236. # Detect the coordinates
  237. detector = dlib.get_frontal_face_detector()
  238. number_of_faces=[]
  239. # Capture frames continuously
  240. # while True:
  241. # Capture frame-by-frame
  242. # ret, frame = cap
  243. frame = cap
  244. # RGB to grayscale
  245. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  246. faces = detector(gray)
  247. # Iterator to count faces
  248. i = 0
  249. for face in faces:
  250. # Get the coordinates of faces
  251. x, y = face.left(), face.top()
  252. x1, y1 = face.right(), face.bottom()
  253. cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)
  254. # Increment iterator for each face in faces
  255. i = i+1
  256. # Display the box and faces
  257. cv2.putText(frame, 'face num'+str(i), (x-10, y-10),
  258. cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
  259. # if len(i)>1:
  260. # print(i)
  261. number_of_faces.append(i)
  262. if (len(number_of_faces))>1:
  263. print("Group Photo")
  264. return "Group Photo"
  265. elif (len(number_of_faces))==1:
  266. print("Single Photo")
  267. pass
  268. def readEncodingsPickle(fname):
  269. """
  270. Read Pickle file.
  271. Parameters
  272. ----------
  273. fname : String
  274. Name of pickle file.(Full location)
  275. Returns
  276. -------
  277. encodings : list of np arrays
  278. list of all saved encodings
  279. names : List of Strings
  280. List of all saved names
  281. """
  282. data = pickle.loads(open(fname, "rb").read())
  283. data = np.array(data)
  284. encodings = [d["encoding"] for d in data]
  285. names = [d["name"] for d in data]
  286. return encodings, names
  287. def compareFaceEncodings(unknown_encoding, known_encodings, known_names):
  288. """
  289. Compares face encodings to check if 2 faces are same or not.
  290. Parameters
  291. ----------
  292. unknown_encoding : np array
  293. Face encoding of unknown people.
  294. known_encodings : np array
  295. Face encodings of known people.
  296. known_names : list of strings
  297. Names of known people
  298. Returns
  299. -------
  300. acceptBool : Bool
  301. face matched or not
  302. duplicateName : String
  303. Name of matched face
  304. distance : Float
  305. Distance between 2 faces
  306. """
  307. duplicateName = ""
  308. distance = 0.0
  309. matches = face_recognition.compare_faces(known_encodings, unknown_encoding, tolerance=0.54)
  310. face_distances = face_recognition.face_distance(known_encodings, unknown_encoding)
  311. best_match_index = np.argmin(face_distances)
  312. distance = face_distances[best_match_index]
  313. if matches[best_match_index]:
  314. acceptBool = True
  315. duplicateName = known_names[best_match_index]
  316. else:
  317. acceptBool = False
  318. duplicateName = ""
  319. return acceptBool, duplicateName, distance
  320. #p = []
  321. def processDatasetImages(path=path, pickle_location=pickle_location):
  322. """
  323. Process image in dataset from where you want to separate images.
  324. It separates the images into directories of known people, groups and any unknown people images.
  325. Parameters
  326. ----------
  327. path : STRING, optional
  328. Path for known people dataset. The default is "D:/port1004/port1004/wwwroot/_files/People".
  329. It should be noted that each image in this dataset should contain only 1 face.
  330. saveLocation : STRING, optional
  331. Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory".
  332. Returns
  333. -------
  334. None.
  335. """
  336. # Read pickle file for known people to compare faces from
  337. people_encodings, names = readEncodingsPickle(pickle_location)
  338. # print(p)
  339. # imgPath = path + img
  340. # Read image
  341. # path=r"C:\Users\katku\Pictures\final\100011460000611.jpg"
  342. image = cv2.imread(path)
  343. #orig = image.copy()
  344. # Resize
  345. image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR)
  346. # Get locations and encodings
  347. encs, locs = createEncodings(image)
  348. # Save image to a group image folder if more than one face is in image
  349. # if len(locs) > 1:
  350. # saveImageToDirectory(orig, "Group", img)
  351. # Processing image for each face
  352. i = 0
  353. knownFlag = 0
  354. for loc in locs:
  355. top, right, bottom, left = loc
  356. unknown_encoding = encs[i]
  357. i += 1
  358. acceptBool, duplicateName, distance = compareFaceEncodings(unknown_encoding, people_encodings, names)
  359. if acceptBool:
  360. # saveImageToDirectory(orig, duplicateName,name)
  361. knownFlag = 1
  362. if knownFlag == 1:
  363. print("Match Found")
  364. #print(path)
  365. with_extension = path.split("/")[-1]
  366. without_extension = with_extension.split(".")[0]
  367. # output_s = {"FileID": without_extension,
  368. # "Date": India_Date,
  369. # "Time": India_Time}
  370. # output_json = json.dumps(output_s)
  371. output_json='Matched successfully'
  372. print(loc)
  373. lst.append(output_json)
  374. print(output_json)
  375. # exit()
  376. else:
  377. print('Not Matched')
  378. pass
  379. # saveImageToDirectory(orig, "0",name)
  380. import numpy as np
  381. import json
  382. processDatasetImages(path, pickle_location)
  383. return lst[0]
  384. #return 'matched successfully'
  385. @app.route('/test_detect', methods=["POST"])
  386. def detect():
  387. if __name__ == "__main__":
  388. url_list=[]
  389. Dataset= request.get_json()
  390. # id = "100013660000125"
  391. url_list.append(Dataset)
  392. # multiprocessing
  393. pool_size = multiprocessing.cpu_count() * 2
  394. with multiprocessing.Pool(pool_size) as pool:
  395. try:
  396. results = pool.map(submit, url_list)
  397. except FileNotFoundError:
  398. return 'plese get registered with your PhotoID'
  399. except IndexError:
  400. #return 'unable to recognize face'
  401. return 'failed'
  402. pool.close()
  403. return results[0]
  404. @app.route('/test_register', methods=["POST"])
  405. def register():
  406. print("hello start..........")
  407. if __name__ == "__main__":
  408. url_list=[]
  409. Dataset= request.get_json()
  410. # id = "100013660000125"
  411. url_list.append(Dataset)
  412. UserLocation=Dataset["FilePath"]
  413. print(UserLocation)
  414. # if "cO2" in UserLocation or UserLocation is None:
  415. # pass
  416. # else:
  417. # return "Please update the URL in the integration"
  418. # multiprocessing
  419. pool_size = multiprocessing.cpu_count() * 2
  420. with multiprocessing.Pool(pool_size) as pool:
  421. try:
  422. results = pool.map(registered, url_list)
  423. except IndexError:
  424. pass
  425. print('face not found')
  426. except FileNotFoundError:
  427. pass
  428. #os.remove(img)
  429. # return 'unable to recognize face'
  430. pool.close()
  431. #return results[0]
  432. return 'Successfully saved encoding.........'
  433. if __name__ == "__main__":
  434. app.run(host='0.0.0.0',port =5004,debug=False)