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.

190 lines
7.7KB

  1. import asyncio
  2. import copy
  3. import json
  4. import os
  5. import time
  6. from concurrent.futures import ThreadPoolExecutor
  7. from multiprocessing import Queue, Process
  8. from loguru import logger
  9. import subprocess as sp
  10. import cv2
  11. import numpy as np
  12. from aip import AipImageClassify
  13. import sys
  14. from enums.BaiduSdkEnum import BAIDUERRORDATA, VehicleEnumVALUE
  15. from enums.ExceptionEnum import ExceptionType
  16. from enums.ModelTypeEnum import ModelType
  17. from exception.CustomerException import ServiceException
  18. from util.ModelUtils import Model
  19. def get_recording_video_info(url):
  20. try:
  21. video_info = 'ffprobe -show_format -show_streams -of json %s' % url
  22. p = sp.Popen(video_info, stdout=sp.PIPE, stderr=sp.PIPE, shell=True)
  23. out, err = p.communicate(timeout=17)
  24. if p.returncode != 0:
  25. raise Exception("未获取视频信息!!!!!")
  26. probe = json.loads(out.decode('utf-8'))
  27. if probe is None or probe.get("streams") is None:
  28. raise Exception("未获取视频信息!!!!!:")
  29. video_stream = next((stream for stream in probe['streams'] if stream.get('codec_type') == 'video'), None)
  30. if video_stream is None:
  31. raise Exception("未获取视频信息!!!!!")
  32. width = video_stream.get('width')
  33. height = video_stream.get('height')
  34. nb_frames = video_stream.get('nb_frames')
  35. fps = video_stream.get('r_frame_rate')
  36. up, down = str(fps).split('/')
  37. fps = int(eval(up) / eval(down))
  38. return (width, height, nb_frames, fps)
  39. except Exception as e:
  40. raise e
  41. client = AipImageClassify(str(31096670), 'Dam3O4tgPRN3qh4OYE82dbg7', '1PGZ9LAXRR5zcT5MN9rHcW8kLBIS5DAa')
  42. def vehicleDetect(client, iamge, options={}):
  43. reply_num = 0
  44. reply_value = None
  45. while True:
  46. try:
  47. options["show"] = "true"
  48. res_image = client.vehicleDetect(iamge,options)
  49. error_code = res_image.get("error_code")
  50. if error_code:
  51. enum = BAIDUERRORDATA.get(error_code)
  52. # 如果异常编码未知, 返回空值
  53. if enum is None:
  54. logger.error("百度云车辆检测异常!error_code:{}", error_code)
  55. return None
  56. # 重试指定次数后,还是异常,输出统一内部异常
  57. if enum.value[3] == 0:
  58. if reply_value is None:
  59. reply_value = 10
  60. logger.error("百度云车辆检测异常!error_code:{}, error_msg:{}, reply_num:{}", enum.value[0], enum.value[2], reply_num)
  61. raise Exception()
  62. # 重试指定次数后,还是异常,输出对应的异常
  63. if enum.value[3] == 1:
  64. if reply_value is None:
  65. reply_value = 10
  66. raise ServiceException(str(enum.value[0]), enum.value[2])
  67. # 重试指定次数后,还是异常,输出空
  68. if enum.value[3] == 2:
  69. if reply_value is None:
  70. reply_value = 10
  71. if reply_num >= reply_value:
  72. return None
  73. return res_image
  74. except ServiceException as s:
  75. time.sleep(0.2)
  76. reply_num += 1
  77. if reply_num > reply_value:
  78. logger.exception("车辆检测识别失败: {}", s.msg)
  79. raise ServiceException(e.code, e.msg)
  80. except Exception as e:
  81. logger.exception("车辆检测失败: {}, 当前重试次数:{}", e, reply_num)
  82. time.sleep(0.2)
  83. reply_num += 1
  84. if reply_num > reply_value:
  85. logger.exception("车辆检测识别失败: {}", e)
  86. raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  87. ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
  88. def mark(content, info, img, color):
  89. score = info.get("probability")
  90. if score is None:
  91. score = info.get("location").get("score")
  92. text = "%s: %.2f" % (content, score)
  93. text_xy = (info.get("location").get("left"), info.get("location").get("top") - 25)
  94. img_lu = (info.get("location").get("left"), info.get("location").get("top"))
  95. img_rd = (info.get("location").get("left") + info.get("location").get("width"),
  96. info.get("location").get("top") + info.get("location").get("height"))
  97. cv2.putText(img, text, text_xy, cv2.FONT_HERSHEY_SIMPLEX, 1.0, color, 2, cv2.LINE_AA)
  98. count = 1
  99. if img.shape[1] > 1600:
  100. count = 2
  101. cv2.rectangle(img, img_lu, img_rd, color, count)
  102. return img
  103. async def mode_handler(img, width):
  104. return senlin_mod.process(copy.deepcopy(img), width)
  105. async def modprocess(img, width):
  106. p_result, timeOut = await mode_handler(img, width)
  107. return p_result, timeOut
  108. async def car_handler(img, width):
  109. return car_mod.process(copy.deepcopy(img), width)
  110. async def carprocess(img, width):
  111. p_result, timeOut = await car_handler(img, width)
  112. return p_result, timeOut
  113. async def baidu_handler(img, client):
  114. or_result, or_image = cv2.imencode(".jpg", img)
  115. return vehicleDetect(client, or_image)
  116. async def baiduprocess(img, client):
  117. result = await baidu_handler(img, client)
  118. return result
  119. url ='/home/th/tuo_heng/dev/11.mp4'
  120. width, height, nb_frames, fps = get_recording_video_info(url)
  121. current_path = os.path.abspath(os.path.dirname(__file__))
  122. import GPUtil
  123. senlin_mod = Model(str(GPUtil.getAvailable()[0]), [2,3,4], logger, "11112", ModelType.FOREST_FARM_MODEL)
  124. car_mod = Model(str(GPUtil.getAvailable()[0]), [0], logger, "11112", ModelType.VEHICLE_MODEL)
  125. or_video_file = cv2.VideoWriter("aaa2.mp4", cv2.VideoWriter_fourcc(*'mp4v'), fps,
  126. (int(width) * 2, int(height)))
  127. command = ['ffmpeg -re -y -i ' + url +' -f rawvideo -pix_fmt bgr24 -an -']
  128. pull_p = sp.Popen(command, stdout=sp.PIPE, shell=True)
  129. num = 0
  130. loop = asyncio.new_event_loop()
  131. asyncio.set_event_loop(loop)
  132. try:
  133. while True:
  134. print(num, nb_frames)
  135. in_bytes = pull_p.stdout.read(width*height*3)
  136. if in_bytes is not None and len(in_bytes) > 0:
  137. img = np.frombuffer(in_bytes, np.uint8).reshape([height, width, 3])
  138. # r = loop.run_until_complete(asyncio.gather(modprocess(img, width), carprocess(img, width)))
  139. p_result, timeOut = senlin_mod.process(copy.deepcopy(img), width)
  140. p_result1, timeOut1 = car_mod.process(copy.deepcopy(p_result[1]), width)
  141. # r = loop.run_until_complete(asyncio.gather(modprocess(img, width), baiduprocess(img, client)))
  142. # p_result, timeOut = r[0]
  143. # result = r[1]
  144. # p_result, timeOut = senlin_mod.process(copy.deepcopy(img), width)
  145. # if result is not None:
  146. # vehicleInfo = result.get("vehicle_info")
  147. # if vehicleInfo is not None and len(vehicleInfo) > 0:
  148. # for i, info in enumerate(vehicleInfo):
  149. # value = VehicleEnumVALUE.get(info.get("type"))
  150. # if value is None:
  151. # logger.error("车辆识别出现未支持的目标类型!type:{}", info.get("type"))
  152. # raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  153. # ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
  154. # p_result[1] = mark(value.value[1], info, p_result[1], (255, 0, 255))
  155. frame_merge = np.hstack((img, p_result1[1]))
  156. or_video_file.write(frame_merge)
  157. num+=1
  158. else:
  159. if num -10 > nb_frames:
  160. break;
  161. finally:
  162. or_video_file.release()
  163. pull_p.terminate()
  164. pull_p.wait()