You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

api.py 7.5 kB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. from api.model.model import PicoDet
  2. import time
  3. import cv2
  4. import json
  5. import datetime
  6. import os
  7. import sys
  8. from utils.utils import send_notifycation
  9. def getFile(ruleFile):
  10. if getattr(sys, 'frozen', False):
  11. absPath = os.path.dirname(os.path.abspath(sys.executable))
  12. elif __file__:
  13. absPath = os.path.dirname(os.path.abspath(__file__))
  14. else:
  15. absPath = ''
  16. return os.path.join(absPath,ruleFile)
  17. def get_settings_status_name(data, settings,setting_name):
  18. # 访问指定 "setting" 的信息
  19. for setting in data[settings]:
  20. if setting["name"] == setting_name:
  21. # 使用 filter() 和 map() 函数提取信息
  22. names = list(map(lambda x: x["name"], filter(lambda x: x["status"], setting["status"])))
  23. return names[0]
  24. def get_setting_status(data, settings,setting_name):
  25. # 使用 filter() 和 map() 函数提取信息
  26. status = list(map(lambda x: x["status"], filter(lambda x: x["name"] == setting_name, data[settings])))
  27. return status[0]
  28. def get_photo(cap):
  29. # cap = cv2.VideoCapture(0) # 开启摄像头
  30. f, frame = cap.read() # 将摄像头中的一帧图片数据保存
  31. return frame
  32. # print('开始咯!')
  33. # while cv2.waitKey(1)==-1:
  34. # #计时
  35. def get_photo_detect(cap,net):
  36. '''
  37. 输入{图像,网络模型},输出[预测时间,预测结果]
  38. '''
  39. result = net.detect_img(get_photo(cap),show_result=False)
  40. return result
  41. def get_photo_detect_img(cap,net):
  42. '''
  43. 输入{图像,网络模型},输出[预测时间,预测图片]
  44. '''
  45. start = time.time()
  46. [result,img] = net.detect_img(get_photo(cap),show_result=True)
  47. # cv2.imshow('Video Cam', result)
  48. # # print(result)
  49. end = time.time()
  50. # print('time:',end-start)
  51. # cap.release() # 关闭摄像头
  52. # # cv2.destroyAllWindows()
  53. return [end-start,result,img]
  54. def get_photo_base64(cap):
  55. import base64
  56. # import numpy as np
  57. img = get_photo(cap)
  58. image = cv2.imencode('.jpg',img)[1]
  59. image_code = str(base64.b64encode(image))[2:-1]
  60. return image_code
  61. def mat2base64(frame):
  62. import base64
  63. # import numpy as np
  64. image = cv2.imencode('.jpg',frame)[1]
  65. image_code = str(base64.b64encode(image))[2:-1]
  66. return image_code
  67. class API:
  68. '''本地API,供前端JS调用'''
  69. window = None
  70. net = None
  71. cap = None
  72. args = None
  73. def __init__(self):
  74. with open(getFile("config.json"),'r',encoding='utf8')as fp:
  75. self.args = json.load(fp)
  76. self.net = PicoDet(
  77. get_settings_status_name(self.args,"ModelSetting","模型版本设置"),
  78. self.args['classfile'],
  79. prob_threshold=float(get_setting_status(self.args,"ModelSetting",'confThreshold')),
  80. iou_threshold=float(get_setting_status(self.args,"ModelSetting",'nmsThreshold')))
  81. # net.detect_folder(args['img_fold'], args['result_fold'])
  82. # 调用摄像头拍摄照片
  83. self.cap = cv2.VideoCapture(0) # 开启摄像头
  84. # cv2.namedWindow('Video Cam', cv2.WINDOW_NORMAL)
  85. if(self.args['toggle'] and self.args['tip']):
  86. send_notifycation("功能触发:鼠标悬停","EMC[嘴控]")
  87. def getPrimaryImg(self,type="不裁剪"):
  88. # 三种处理图片的方式:不裁剪、居中裁剪成224*224、居中裁剪成320*320。
  89. if(type=="不裁剪"):
  90. return get_photo_base64(self.cap)
  91. elif(type=="居中裁剪成224*224"):
  92. img = get_photo(self.cap)
  93. height=len(img)
  94. width=len(img[0])
  95. if(height>224 and width>224):
  96. y0 = height//2
  97. x0 = width//2
  98. x1 = x0-112
  99. y1 = y0-112
  100. x2 = x0+112
  101. y2 = y0+112
  102. img = img[y1:y2, x1:x2]
  103. return mat2base64(img)
  104. elif(type=="居中裁剪成320*320"):
  105. img = get_photo(self.cap)
  106. height=len(img)
  107. width=len(img[0])
  108. if(height>320 and width>320):
  109. y0 = height//2
  110. x0 = width//2
  111. x1 = x0-160
  112. y1 = y0-160
  113. x2 = x0+160
  114. y2 = y0+160
  115. img = img[y1:y2, x1:x2]
  116. return mat2base64(img)
  117. def getDetectImg(self):
  118. [time,result,img] = get_photo_detect_img(self.cap,self.net)
  119. return [time,result,mat2base64(img)]#AttributeError: 'InferenceSession' object has no attribute 'detect'
  120. def getIndexSetting(self):
  121. toggle = self.args['toggle']
  122. tip = self.args['tip']
  123. control = self.args['control']
  124. return [toggle,tip,control]
  125. def getAdvanceSetting(self):
  126. return [self.args['ControlSetting'], self.args['ModelSetting'], self.args['otherSetting']]
  127. def changeSetting(self,data):
  128. self.args.update(data)
  129. with open(getFile("config.json"),'w',encoding='utf8')as fp:
  130. json.dump(self.args,fp,ensure_ascii=False,indent=4)
  131. def getPersonalizationPrimaryImg(self):
  132. #判断是否存在"primary_img"文件夹
  133. if(os.path.exists(getFile("primary_img"))==False):
  134. #不存在则创建
  135. os.mkdir(getFile("primary_img"))
  136. #返回该文件夹下png文件的数量和列表
  137. return [len(os.listdir(getFile("primary_img"))),os.listdir(getFile("primary_img"))]
  138. def setPersonalizationPrimaryImg(self,type="不裁剪"):
  139. #判断是否存在"primary_img"文件夹
  140. if(os.path.exists(getFile("primary_img"))==False):
  141. #不存在则创建
  142. os.mkdir(getFile("primary_img"))
  143. #保存图片
  144. # 图片名字是当前时间
  145. # 三种处理图片的方式:不裁剪、居中裁剪成224*224、居中裁剪成320*320。
  146. if(type=="不裁剪"):
  147. cv2.imwrite(getFile("primary_img")+"/"+time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())+".png",get_photo(self.cap))
  148. elif(type=="居中裁剪成224*224"):
  149. img = get_photo(self.cap)
  150. height=len(img)
  151. width=len(img[0])
  152. if(height>224 and width>224):
  153. y0 = height//2
  154. x0 = width//2
  155. x1 = x0-112
  156. y1 = y0-112
  157. x2 = x0+112
  158. y2 = y0+112
  159. img = img[y1:y2, x1:x2]
  160. cv2.imwrite(getFile("primary_img")+"/"+time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())+".png",img)
  161. elif(type=="居中裁剪成320*320"):
  162. img = get_photo(self.cap)
  163. height=len(img)
  164. width=len(img[0])
  165. if(height>320 and width>320):
  166. y0 = height//2
  167. x0 = width//2
  168. x1 = x0-160
  169. y1 = y0-160
  170. x2 = x0+160
  171. y2 = y0+160
  172. img = img[y1:y2, x1:x2]
  173. cv2.imwrite(getFile("primary_img")+"/"+time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())+".png",img)
  174. #返回该文件夹下png文件的数量和列表
  175. return [len(os.listdir(getFile("primary_img"))),os.listdir(getFile("primary_img"))]
  176. def openPrimaryImgFiles(self):
  177. #判断是否存在"primary_img"文件夹
  178. if(os.path.exists(getFile("primary_img"))==False):
  179. #不存在则创建
  180. os.mkdir(getFile("primary_img"))
  181. #打开文件夹
  182. os.startfile(getFile("primary_img"))