21_maskDetection.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. #version : 2023.04.04
  3. #language : en
  4. from time import time
  5. from maix import display, camera,image
  6. ScreenOrientation = False
  7. class Mask:
  8. mud_path = "/root/preset/model/mask_int8.mud"
  9. labels = ["no wear","wear"]
  10. anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
  11. def __init__(self) -> None:
  12. from maix import nn
  13. self.model = nn.load(self.mud_path)
  14. from maix.nn import decoder
  15. self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
  16. def __del__(self):
  17. del self.model
  18. del self.decoder
  19. def cal_fps(self ,start , end):
  20. one_second = 1
  21. one_flash = end - start
  22. fps = one_second / one_flash
  23. return fps
  24. def draw_rectangle_with_title(self ,img, box, disp_str , fps ):
  25. img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
  26. img.draw_string(box[0], box[1]+ box[3] ,disp_str, scale=1,color=(0, 0, 255), thickness=1)
  27. img.draw_string(0, 0 ,'FPS :'+str(fps), scale=2 ,color=(0, 0, 255), thickness=1)
  28. def process(self,input):
  29. t = time()
  30. out = self.model.forward(input, quantize=1, layout = "hwc")
  31. boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.6, img_size=(224,224))
  32. for i, box in enumerate(boxes):
  33. class_id = probs[i][0]
  34. prob = probs[i][1][class_id]
  35. disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
  36. fps = self.cal_fps(t, time())
  37. self.draw_rectangle_with_title(input, box, disp_str, fps)
  38. app = Mask()
  39. def lcdRotation(inputImg,rotationAngle):
  40. from maix import image
  41. imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
  42. if ScreenOrientation:
  43. imgRotationAim = image.new(size = (240, 320))
  44. else:
  45. imgRotationAim = image.new(size = (320, 240))
  46. return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
  47. image.load_freetype("/root/preset/fonts/CascadiaCodePL-Italic.ttf")
  48. if ScreenOrientation:
  49. CAMERAROTATE = +180
  50. else:
  51. CAMERAROTATE = +90
  52. canvasImg = image.new(size = (320, 240))
  53. while True:
  54. img = camera.capture().crop(0, 0,224, 224)
  55. app.process(img)
  56. canvasImg.draw_image(img,48,8)
  57. canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
  58. display.show(canvasImg)