bzy_mqtt_photo.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # -*- coding: utf-8 -*-
  2. # File Name:mqtt_chat_client.py
  3. # Python Version:3.5.1
  4. import os
  5. import django
  6. import sys
  7. from imutils import paths
  8. import argparse
  9. import cv2
  10. import shutil
  11. import glob
  12. BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 定位到你的django根目录
  13. sys.path.append(os.path.abspath(os.path.join(BASE_DIR, os.pardir)))
  14. os.environ.setdefault("DJANGO_SETTINGS_MODULE",
  15. "yfwlw_pro.settings") # project_name 项目名称
  16. django.setup()
  17. print("<-----python_mqtt_client_bzy is run----->")
  18. import paho.mqtt.client as mqtt
  19. import json
  20. from apps.AppInfoManage.models import Equip, Equip_type, MyUser, Alarm_record, BZYdata, BZYstatus, BZYphoto
  21. import re
  22. import datetime
  23. import time
  24. from PIL import Image
  25. def mkdir(path):
  26. # 去除首位空格
  27. path=path.strip()
  28. # 去除尾部 \ 符号
  29. path=path.rstrip("\\")
  30. # 判断路径是否存在
  31. # 存在 True
  32. # 不存在 False
  33. isExists=os.path.exists(path)
  34. # 判断结果
  35. if not isExists:
  36. # 如果不存在则创建目录
  37. # 创建目录操作函数
  38. os.makedirs(path)
  39. print(path+' 创建成功')
  40. return True
  41. else:
  42. # 如果目录存在则不创建,并提示目录已存在
  43. print(path+' 目录已存在')
  44. return False
  45. def variance_of_laplacian(image):
  46. # 拉普拉斯的方差
  47. return cv2.Laplacian(image, cv2.CV_64F).var()
  48. class CJSONEncoder(json.JSONEncoder):
  49. def default(self, obj):
  50. if isinstance(obj, datetime):
  51. return obj.strftime('%Y-%m-%d %H:%M:%S')
  52. elif isinstance(obj, date):
  53. return obj.strftime('%Y-%m-%d')
  54. else:
  55. return json.JSONEncoder.default(self, obj)
  56. # 连接后的操作: 0为成功
  57. def on_connect(client, userdata, flags, rc):
  58. # print("Connected with result code "+str(rc))
  59. client.subscribe("/yfkj/bzy/c2s/#")
  60. client.subscribe("/yfkj/bzy/offline/#")
  61. # *****成功发布******
  62. def on_publish(msg, rc):
  63. if rc == 0:
  64. print("publish success,msg = "+msg)
  65. # 从服务器接受到消息后回调此函数 :
  66. def on_message(client, userdata, msg):
  67. print('\r')
  68. print('=================================================')
  69. print('\r')
  70. print("<-----topic:\n" + msg.topic + ';\n')
  71. print("Message:\n" + str(msg.payload) + "----->\n")
  72. # 从主题中获取imei
  73. # imei = msg.topic[14:len(msg.topic)]
  74. reg = re.compile(r"(?<=/)\d+")
  75. imei = reg.search(msg.topic).group(0)
  76. # imei = re.sub("\D", "", msg.topic)
  77. # nowtime = datetime.datetime.now().strftime('%Y%m%d')
  78. # origin = sys.stdout
  79. # f = open('./logs/'+nowtime+'bzymqtt.txt','a+')
  80. # sys.stdout = f
  81. print("<-----imei:", imei, "----->")
  82. # 判断主题:
  83. if "c2s" in msg.topic:
  84. # 将json字符串解析:
  85. payload = json.loads(msg.payload.decode())
  86. if payload.get("cmd") == "photo":
  87. nowtime = datetime.datetime.now().strftime('%Y%m%d')
  88. origin = sys.stdout
  89. f = open('../logs/'+"bzyphoto" + nowtime +'.txt','a')
  90. sys.stdout = f
  91. print('=================================================')
  92. print("<-----imei:\n" + imei + ';\n')
  93. print("Message:\n" + "bzyphoto" + "----->\n")
  94. print("%s"%datetime.datetime.now())
  95. print('=================================================')
  96. sys.stdout = origin
  97. f.close()
  98. pic_name = datetime.datetime.now().strftime('%Y%m')
  99. try:
  100. pic_name = datetime.datetime.now().strftime('%Y%m')
  101. args = "../pyftp/ftp_file/bzy_test/" + imei
  102. cv_num_list = []
  103. file_list1 = list(paths.list_images(args))
  104. print("\n===========================")
  105. print("file_list1:",file_list1)
  106. print("type file_list1:",type(file_list1))
  107. cv_num_list1 = []
  108. for imagePath1 in file_list1[::]:
  109. # fm = get_value(imagePath)
  110. # 孢子仪图片过小删除
  111. if os.path.getsize(imagePath1) <= 10:
  112. file_list1.remove(imagePath1)
  113. img1 = cv2.imread(imagePath1)
  114. img1 = cv2.resize(img1, (800, 600))
  115. gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
  116. # 创建SIFT对象
  117. sift = cv2.xfeatures2d.SIFT_create()
  118. keypoints, descriptor = sift.detectAndCompute(gray, None)
  119. img1 = cv2.drawKeypoints(image=img1, outImage=img1, keypoints=keypoints,flags=cv2.DRAW_MATCHES_FLAGS_DEFAULT, color=(0, 0, 255))
  120. fm1 = len(keypoints)
  121. cv_num_list1.append(fm1)
  122. # 打印清晰度值:
  123. print("fm1",fm1)
  124. # 打印文件路径
  125. print("imagePath1",imagePath1)
  126. file_cv_tuple1 = tuple(zip(cv_num_list1,file_list1))
  127. print("file_cv_tuple1:\n",file_cv_tuple1)
  128. print("=========================================/n")
  129. file_cv_tuple_list1 = list(file_cv_tuple1)
  130. print("file_cv_tuple_list1:\n",file_cv_tuple_list1)
  131. print("*****************************************/n")
  132. # 按照清晰度排序:, reverse=True降序
  133. result1 = sorted(file_cv_tuple_list1, key=lambda s: s[0],reverse=True)
  134. print("result1:\n",result1)
  135. # 切片取清晰度最高的前五张图片:
  136. result1_5 = result1[0:3]
  137. # result5 = result[0:1]
  138. print("result1_5:\n",result1_5)
  139. pic_name = datetime.datetime.now().strftime('%Y%m')
  140. # 定义要创建的目录:
  141. mkpath="../pyftp/ftp_file/bzy_photo/" + imei + "/" + pic_name
  142. # 调用函数,创建目录:
  143. mkdir(mkpath)
  144. for i in result1_5:
  145. # for i in result5:
  146. #i值:(137.06453470539032, 'images\\192.168.2.64_01_20190802095315882_ALARM_INPUT.jpg')
  147. print("file path:",i[1])
  148. #复制文件:
  149. shutil.copy(i[1],mkpath)
  150. # os.system("rm ./pyftp/ftp_file/bzy_test/%s/*.jpg -rf"%imei)
  151. os.system("mv ../pyftp/ftp_file/bzy_test/%s ../pyftp/ftp_file/bzy_test/%s_%s"%(imei,imei,datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
  152. print("-----------------image move success----------------------")
  153. equip = Equip.objects.get(equip_id=imei)
  154. file_dir="/data/yfwlw/pyftp/ftp_file/bzy_photo/" + imei + "/" + pic_name
  155. for root, dirs, files in os.walk(file_dir):
  156. print("当前目录为=========>>",root) #当前目录路径
  157. print("当前子目录为=========>>",dirs) #当前路径下所有子目录
  158. print("当前目录文件为=========>>",files) #当前路径下所有非目录子文件
  159. for i in files:
  160. photo_addr = file_dir + "/" + i
  161. print("文件夹图片路径===========》》",photo_addr)
  162. if BZYphoto.objects.filter(addr=photo_addr[12:]).exists():
  163. print("照片存在")
  164. else:
  165. BZYphoto.objects.create(equip_id=equip, addr=photo_addr[12:])
  166. print("照片不存在")
  167. except Exception as a:
  168. print('=================================================')
  169. print("<-----imei:\n" + imei + ';\n')
  170. print("Message:\n" + "http:bzyphoto" + "----->\n")
  171. print("%s"%datetime.datetime.now())
  172. print("==========%s========"%a)
  173. print("-----------------image move default----------------------")
  174. # ------------------------------------------------------------------------------------------------
  175. # nowtime = datetime.datetime.now().strftime('%Y%m%d')
  176. # origin = sys.stdout
  177. # f = open('logs/'+"bzyphoto" + nowtime +'.txt','a')
  178. # sys.stdout = f
  179. # print('=================================================')
  180. # print("<-----topic:\n" + msg.topic + ';\n')
  181. # print("Message:\n" + str(msg.payload) + "----->\n")
  182. # print("%s"%datetime.datetime.now())
  183. # print('=================================================')
  184. # sys.stdout = origin
  185. # f.close()
  186. # pic_name = datetime.datetime.now().strftime('%Y%m')
  187. # try:
  188. # # f = os.popen(r"python3 bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/" + imei + "," + imei, "r")
  189. # # shuchu = f.read()
  190. # # print("shuchu:",shuchu)
  191. # # f.close()
  192. # # pFile = open(r"test.txt", "w")
  193. # # pFile.write('shuchu')
  194. # # pFile.close()
  195. # # os.system("python bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/" + imei + "/" + pic_name + "," + imei)
  196. # # from subprocess import run
  197. # # run("python bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/" + imei + "," + imei)
  198. # # print("=====================================",datetime.datetime.now())
  199. # # aaa = os.system("python3 bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/" + imei + "," + imei + " > test.txt")
  200. # # print("aaa:",aaa)
  201. # # # os.system("python bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/865650042816310,865650042816310 > test.txt")
  202. # pic_name = datetime.datetime.now().strftime('%Y%m')
  203. # args = "pyftp/ftp_file/bzy_test/" + imei
  204. # # 清晰度的list:
  205. # cv_num_list = []
  206. # # 文件名的列表
  207. # file_list = list(paths.list_images(args))
  208. # print("\n===========================")
  209. # print("file_list:",file_list)
  210. # print("type file_list:",type(file_list))
  211. # for imagePath in file_list[::]:
  212. # # 孢子仪图片过小删除
  213. # if os.path.getsize(imagePath) <= 10:
  214. # file_list.remove(imagePath)
  215. # # 加载图像,将其转换为灰度,然后计算
  216. # # 使用拉普拉斯方差对图像进行聚焦测量
  217. # image = cv2.imread(imagePath)
  218. # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  219. # fm = variance_of_laplacian(gray)
  220. # # 加载图片
  221. # img = Image.open(imagePath)
  222. # # 获取图像的
  223. # height = img.size[0]
  224. # width = img.size[1]
  225. # im=Image.open(imagePath)
  226. # print(im.mode) #查看图像的模式
  227. # im1=im.convert("YCbCr") #转换图像的模式到视频模式
  228. # y1,cb1,cr1=im1.getpixel((height*0.2,width*0.2)) #提取点(10,10)位置的亮度、蓝色分量、红色分量的值。
  229. # y2,cb2,cr2=im1.getpixel((height*0.8,width*0.2)) #提取点(10,10)位置的亮度、蓝色分量、红色分量的值。
  230. # y3,cb3,cr3=im1.getpixel((height*0.2,width*0.8)) #提取点(10,10)位置的亮度、蓝色分量、红色分量的值。
  231. # y4,cb4,cr4=im1.getpixel((height*0.8,width*0.8)) #提取点(10,10)位置的亮度、蓝色分量、红色分量的值。
  232. # if y1 < 50 and y2 < 50 and y3 < 50 and y4 < 50:
  233. # file_list.remove(imagePath)
  234. # else:
  235. # cv_num_list.append(fm)
  236. # # 打印清晰度值:
  237. # print("fm",fm)
  238. # # 打印文件路径
  239. # print("imagePath",imagePath)
  240. # print("////////////////////////////////////////////////////////n")
  241. # print("cv_num_list:\n",cv_num_list)
  242. # # 清晰度列表和文件列表对应,生成dict
  243. # # file_cv_dict = dict(zip(cv_num_list,file_list))
  244. # # 清晰度列表和文件列表对应,生成tuple
  245. # file_cv_tuple = tuple(zip(cv_num_list,file_list))
  246. # print("file_cv_tuple:\n",file_cv_tuple)
  247. # print("=========================================/n")
  248. # file_cv_tuple_list = list(file_cv_tuple)
  249. # print("file_cv_tuple_list:\n",file_cv_tuple_list)
  250. # print("*****************************************/n")
  251. # # 按照清晰度排序:, reverse=True降序
  252. # result = sorted(file_cv_tuple_list, key=lambda s: s[0],reverse=True)
  253. # print("result:\n",result)
  254. # # 切片取清晰度最高的前五张图片:
  255. # # result5 = result[0:5]
  256. # result5 = result[0:1]
  257. # print("result5:\n",result5)
  258. # pic_name = datetime.datetime.now().strftime('%Y%m')
  259. # # 定义要创建的目录:
  260. # mkpath="./pyftp/ftp_file/bzy_photo/" + imei + "/" + pic_name
  261. # # 调用函数,创建目录:
  262. # mkdir(mkpath)
  263. # for i in result5:
  264. # #i值:(137.06453470539032, 'images\\192.168.2.64_01_20190802095315882_ALARM_INPUT.jpg')
  265. # print("file path:",i[1])
  266. # #复制文件:
  267. # shutil.copy(i[1],mkpath)
  268. # # os.system("rm ./pyftp/ftp_file/bzy_test/%s/*.jpg -rf"%imei)
  269. # os.system("mv ./pyftp/ftp_file/bzy_test/%s ./pyftp/ftp_file/bzy_test/%s_%s"%(imei,imei,datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
  270. # print("-----------------image move success----------------------")
  271. # equip = Equip.objects.get(equip_id=imei)
  272. # file_dir="pyftp/ftp_file/bzy_photo/" + imei + "/" + pic_name
  273. # for root, dirs, files in os.walk(file_dir):
  274. # print("当前目录为=========>>",root) #当前目录路径
  275. # print("当前子目录为=========>>",dirs) #当前路径下所有子目录
  276. # print("当前目录文件为=========>>",files) #当前路径下所有非目录子文件
  277. # for i in files:
  278. # photo_addr = file_dir + "/" + i
  279. # print("文件夹图片路径===========》》",photo_addr)
  280. # if BZYphoto.objects.filter(addr=photo_addr).exists():
  281. # print("照片存在")
  282. # else:
  283. # BZYphoto.objects.create(equip_id=equip, addr=photo_addr)
  284. # print("照片不存在")
  285. # except Exception as a:
  286. # print("==========%s========"%a)
  287. # print("-----------------image move default----------------------")
  288. if __name__ == '__main__':
  289. client = mqtt.Client(
  290. client_id="PY_MQTT_PHOTO_BZY",
  291. clean_session=True,
  292. userdata=None,
  293. # protocol=MQTTv311,# 数据库版本
  294. )
  295. # 必须设置,否则会返回「Connected with result code 4」
  296. client.username_pw_set("admin", "password")
  297. client.on_connect = on_connect
  298. client.on_message = on_message
  299. HOST = "127.0.0.1"
  300. client.connect(HOST, 1883, 60)
  301. client.loop_forever()