people_detection.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import cv2
  2. import argparse
  3. from ultralytics import YOLO
  4. import supervision as sv
  5. import numpy as np
  6. import requests
  7. import time
  8. import os
  9. from email.mime.text import MIMEText
  10. from email.mime.multipart import MIMEMultipart
  11. from email.mime.image import MIMEImage
  12. from pathlib import Path
  13. import smtplib
  14. ZONE_POLYGON = np.array([
  15. [0, 0],
  16. [0.3, 0],
  17. [0.3, 1],
  18. [0, 1]
  19. ])
  20. def parse_arguments() -> argparse.Namespace:
  21. parser = argparse.ArgumentParser(description="YOLOv8 live")
  22. parser.add_argument(
  23. "--webcam-resolution",
  24. default=[800, 600],
  25. nargs=2,
  26. type=int
  27. )
  28. args = parser.parse_args()
  29. return args
  30. # 修改為你要傳送的訊息內容
  31. msg = '偵測到:'
  32. # 修改為你的權杖內容
  33. token = 'fDzzBZtLGAukpn7BATssNcB2zbkUajyoHMSQh0IgfT4'
  34. def lineNotifyMessage(token,msg):
  35. headers = {
  36. "Authorization": "Bearer " + token
  37. }
  38. payload = {'message': msg}
  39. image = open('result.jpg','rb')
  40. #files = { 'imageFile': image }
  41. #r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=payload, files = files)
  42. r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=payload)
  43. print(r.text)
  44. return r.status_code
  45. def main():
  46. args = parse_arguments()
  47. frame_width, frame_height = args.webcam_resolution
  48. #print(frame_width,frame_height)
  49. cap = cv2.VideoCapture(0)
  50. cap.set(cv2.CAP_PROP_FRAME_WIDTH, frame_width)
  51. cap.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_height)
  52. #model = YOLO("yolov8n.pt")
  53. model = YOLO("best.pt")
  54. box_annotator = sv.BoxAnnotator(
  55. thickness=2,
  56. text_thickness=2,
  57. text_scale=1
  58. )
  59. zone_polygon = (ZONE_POLYGON * np.array(args.webcam_resolution)).astype(int)
  60. zone = sv.PolygonZone(polygon=zone_polygon, frame_resolution_wh=tuple(args.webcam_resolution))
  61. zone_annotator = sv.PolygonZoneAnnotator(
  62. zone=zone,
  63. color=sv.Color.blue(),
  64. thickness=2,
  65. text_thickness=4,
  66. text_scale=2
  67. )
  68. count = 0
  69. while True:
  70. ret, frame = cap.read()
  71. result = model(frame, agnostic_nms=True)[0]
  72. detections = sv.Detections.from_yolov8(result)
  73. labels = [
  74. f"{model.model.names[class_id]} {confidence:0.2f}"
  75. for _, confidence, class_id, _
  76. in detections
  77. ]
  78. labels_name = [
  79. f"{model.model.names[class_id]}"
  80. for _, confidence, class_id, _
  81. in detections
  82. ]
  83. labels_confidence = [
  84. f"{confidence:0.2f}"
  85. for _, confidence, class_id, _
  86. in detections
  87. ]
  88. frame = box_annotator.annotate(
  89. scene=frame,
  90. detections=detections,
  91. labels=labels
  92. )
  93. #print('name',labels_name)
  94. # print('confidence', labels_confidence)
  95. if labels_name == 0:
  96. continue
  97. elif labels_name == ['Fatwolf']:
  98. count = count+1
  99. now_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
  100. get_labels_name = ''.join(filter(str.isalpha,labels_name))
  101. save_picpath = "./"+get_labels_name
  102. if not os.path.isdir(save_picpath):
  103. os.makedirs(save_picpath)
  104. cv2.imwrite('result.jpg',frame)
  105. write_image = now_time + '_' + str(count) + '.jpg'
  106. cv2.imwrite(save_picpath+'/'+write_image, frame)
  107. lineNotifyMessage(token, (msg+get_labels_name))
  108. message = MIMEMultipart()
  109. message["from"] = "qwe03160825@gmail.com"
  110. message["to"] = "service.gitcr081@gmail.com"
  111. message["subject"] = "[警告訊息]偵測到不明人士!"
  112. now_time = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime(time.time()))
  113. #image = 'result.jpg'
  114. message.attach(MIMEText("時間:" + now_time + "\n偵測到不明人士"))
  115. #message.attach(MIMEImage(Path(image).read_bytes()))
  116. with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
  117. smtp.ehlo()
  118. smtp.starttls()
  119. smtp.login("qwe03160825@gmail.com", "jbroyqabjqdscujo")
  120. smtp.send_message(message)
  121. print("sent...")
  122. # zone.trigger(detections=detections)
  123. # frame = zone_annotator.annotate(scene=frame)
  124. cv2.imshow("yolov8", frame)
  125. key = cv2.waitKey(1)
  126. if key == ord('q'):
  127. break
  128. if __name__ == "__main__":
  129. main()