| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362 |
- # -*- coding: utf-8 -*-
- # File Name:mqtt_chat_client.py
- # Python Version:3.5.1
- import os
- import django
- import sys
- from imutils import paths
- import argparse
- import cv2
- import shutil
- import glob
- BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 定位到你的django根目录
- sys.path.append(os.path.abspath(os.path.join(BASE_DIR, os.pardir)))
- os.environ.setdefault("DJANGO_SETTINGS_MODULE",
- "yfwlw_pro.settings") # project_name 项目名称
- django.setup()
- print("<-----python_mqtt_client_bzy is run----->")
- import paho.mqtt.client as mqtt
- import json
- from apps.AppInfoManage.models import Equip, Equip_type, MyUser, Alarm_record, BZYdata, BZYstatus, BZYphoto
- import re
- import datetime
- import time
- from PIL import Image
- def mkdir(path):
- # 去除首位空格
- path=path.strip()
- # 去除尾部 \ 符号
- path=path.rstrip("\\")
-
- # 判断路径是否存在
- # 存在 True
- # 不存在 False
- isExists=os.path.exists(path)
-
- # 判断结果
- if not isExists:
- # 如果不存在则创建目录
- # 创建目录操作函数
- os.makedirs(path)
- print(path+' 创建成功')
- return True
- else:
- # 如果目录存在则不创建,并提示目录已存在
- print(path+' 目录已存在')
- return False
-
- def variance_of_laplacian(image):
- # 拉普拉斯的方差
- return cv2.Laplacian(image, cv2.CV_64F).var()
- class CJSONEncoder(json.JSONEncoder):
- def default(self, obj):
- if isinstance(obj, datetime):
- return obj.strftime('%Y-%m-%d %H:%M:%S')
- elif isinstance(obj, date):
- return obj.strftime('%Y-%m-%d')
- else:
- return json.JSONEncoder.default(self, obj)
- # 连接后的操作: 0为成功
- def on_connect(client, userdata, flags, rc):
- # print("Connected with result code "+str(rc))
- client.subscribe("/yfkj/bzy/c2s/#")
- client.subscribe("/yfkj/bzy/offline/#")
- # *****成功发布******
- def on_publish(msg, rc):
- if rc == 0:
- print("publish success,msg = "+msg)
- # 从服务器接受到消息后回调此函数 :
- def on_message(client, userdata, msg):
- print('\r')
- print('=================================================')
- print('\r')
- print("<-----topic:\n" + msg.topic + ';\n')
- print("Message:\n" + str(msg.payload) + "----->\n")
- # 从主题中获取imei
- # imei = msg.topic[14:len(msg.topic)]
- reg = re.compile(r"(?<=/)\d+")
- imei = reg.search(msg.topic).group(0)
- # imei = re.sub("\D", "", msg.topic)
- # nowtime = datetime.datetime.now().strftime('%Y%m%d')
- # origin = sys.stdout
- # f = open('./logs/'+nowtime+'bzymqtt.txt','a+')
- # sys.stdout = f
- print("<-----imei:", imei, "----->")
- # 判断主题:
- if "c2s" in msg.topic:
- # 将json字符串解析:
- payload = json.loads(msg.payload.decode())
- if payload.get("cmd") == "photo":
- nowtime = datetime.datetime.now().strftime('%Y%m%d')
- origin = sys.stdout
- f = open('../logs/'+"bzyphoto" + nowtime +'.txt','a')
- sys.stdout = f
- print('=================================================')
- print("<-----imei:\n" + imei + ';\n')
- print("Message:\n" + "bzyphoto" + "----->\n")
- print("%s"%datetime.datetime.now())
- print('=================================================')
- sys.stdout = origin
- f.close()
- pic_name = datetime.datetime.now().strftime('%Y%m')
- try:
- pic_name = datetime.datetime.now().strftime('%Y%m')
- args = "../pyftp/ftp_file/bzy_test/" + imei
- cv_num_list = []
- file_list1 = list(paths.list_images(args))
- print("\n===========================")
- print("file_list1:",file_list1)
- print("type file_list1:",type(file_list1))
- cv_num_list1 = []
- for imagePath1 in file_list1[::]:
- # fm = get_value(imagePath)
- # 孢子仪图片过小删除
- if os.path.getsize(imagePath1) <= 10:
- file_list1.remove(imagePath1)
- img1 = cv2.imread(imagePath1)
- img1 = cv2.resize(img1, (800, 600))
- gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
- # 创建SIFT对象
- sift = cv2.xfeatures2d.SIFT_create()
- keypoints, descriptor = sift.detectAndCompute(gray, None)
- img1 = cv2.drawKeypoints(image=img1, outImage=img1, keypoints=keypoints,flags=cv2.DRAW_MATCHES_FLAGS_DEFAULT, color=(0, 0, 255))
- fm1 = len(keypoints)
- cv_num_list1.append(fm1)
- # 打印清晰度值:
- print("fm1",fm1)
- # 打印文件路径
- print("imagePath1",imagePath1)
- file_cv_tuple1 = tuple(zip(cv_num_list1,file_list1))
- print("file_cv_tuple1:\n",file_cv_tuple1)
- print("=========================================/n")
- file_cv_tuple_list1 = list(file_cv_tuple1)
- print("file_cv_tuple_list1:\n",file_cv_tuple_list1)
- print("*****************************************/n")
- # 按照清晰度排序:, reverse=True降序
- result1 = sorted(file_cv_tuple_list1, key=lambda s: s[0],reverse=True)
- print("result1:\n",result1)
- # 切片取清晰度最高的前五张图片:
- result1_5 = result1[0:3]
- # result5 = result[0:1]
- print("result1_5:\n",result1_5)
- pic_name = datetime.datetime.now().strftime('%Y%m')
- # 定义要创建的目录:
- mkpath="../pyftp/ftp_file/bzy_photo/" + imei + "/" + pic_name
- # 调用函数,创建目录:
- mkdir(mkpath)
- for i in result1_5:
- # for i in result5:
- #i值:(137.06453470539032, 'images\\192.168.2.64_01_20190802095315882_ALARM_INPUT.jpg')
- print("file path:",i[1])
- #复制文件:
- shutil.copy(i[1],mkpath)
- # os.system("rm ./pyftp/ftp_file/bzy_test/%s/*.jpg -rf"%imei)
- 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")))
- print("-----------------image move success----------------------")
- equip = Equip.objects.get(equip_id=imei)
- file_dir="/data/yfwlw/pyftp/ftp_file/bzy_photo/" + imei + "/" + pic_name
- for root, dirs, files in os.walk(file_dir):
- print("当前目录为=========>>",root) #当前目录路径
- print("当前子目录为=========>>",dirs) #当前路径下所有子目录
- print("当前目录文件为=========>>",files) #当前路径下所有非目录子文件
- for i in files:
- photo_addr = file_dir + "/" + i
- print("文件夹图片路径===========》》",photo_addr)
- if BZYphoto.objects.filter(addr=photo_addr[12:]).exists():
- print("照片存在")
- else:
- BZYphoto.objects.create(equip_id=equip, addr=photo_addr[12:])
- print("照片不存在")
- except Exception as a:
- print('=================================================')
- print("<-----imei:\n" + imei + ';\n')
- print("Message:\n" + "http:bzyphoto" + "----->\n")
- print("%s"%datetime.datetime.now())
- print("==========%s========"%a)
- print("-----------------image move default----------------------")
- # ------------------------------------------------------------------------------------------------
- # nowtime = datetime.datetime.now().strftime('%Y%m%d')
- # origin = sys.stdout
- # f = open('logs/'+"bzyphoto" + nowtime +'.txt','a')
- # sys.stdout = f
- # print('=================================================')
- # print("<-----topic:\n" + msg.topic + ';\n')
- # print("Message:\n" + str(msg.payload) + "----->\n")
- # print("%s"%datetime.datetime.now())
- # print('=================================================')
- # sys.stdout = origin
- # f.close()
- # pic_name = datetime.datetime.now().strftime('%Y%m')
- # try:
- # # f = os.popen(r"python3 bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/" + imei + "," + imei, "r")
- # # shuchu = f.read()
- # # print("shuchu:",shuchu)
- # # f.close()
- # # pFile = open(r"test.txt", "w")
- # # pFile.write('shuchu')
- # # pFile.close()
- # # os.system("python bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/" + imei + "/" + pic_name + "," + imei)
- # # from subprocess import run
- # # run("python bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/" + imei + "," + imei)
- # # print("=====================================",datetime.datetime.now())
- # # aaa = os.system("python3 bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/" + imei + "," + imei + " > test.txt")
- # # print("aaa:",aaa)
- # # # os.system("python bzy_pycv_choice.py --images pyftp/ftp_file/bzy_test/865650042816310,865650042816310 > test.txt")
-
- # pic_name = datetime.datetime.now().strftime('%Y%m')
- # args = "pyftp/ftp_file/bzy_test/" + imei
- # # 清晰度的list:
- # cv_num_list = []
- # # 文件名的列表
- # file_list = list(paths.list_images(args))
- # print("\n===========================")
- # print("file_list:",file_list)
- # print("type file_list:",type(file_list))
- # for imagePath in file_list[::]:
- # # 孢子仪图片过小删除
- # if os.path.getsize(imagePath) <= 10:
- # file_list.remove(imagePath)
- # # 加载图像,将其转换为灰度,然后计算
- # # 使用拉普拉斯方差对图像进行聚焦测量
- # image = cv2.imread(imagePath)
- # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- # fm = variance_of_laplacian(gray)
- # # 加载图片
- # img = Image.open(imagePath)
- # # 获取图像的
- # height = img.size[0]
- # width = img.size[1]
- # im=Image.open(imagePath)
- # print(im.mode) #查看图像的模式
- # im1=im.convert("YCbCr") #转换图像的模式到视频模式
- # y1,cb1,cr1=im1.getpixel((height*0.2,width*0.2)) #提取点(10,10)位置的亮度、蓝色分量、红色分量的值。
- # y2,cb2,cr2=im1.getpixel((height*0.8,width*0.2)) #提取点(10,10)位置的亮度、蓝色分量、红色分量的值。
- # y3,cb3,cr3=im1.getpixel((height*0.2,width*0.8)) #提取点(10,10)位置的亮度、蓝色分量、红色分量的值。
- # y4,cb4,cr4=im1.getpixel((height*0.8,width*0.8)) #提取点(10,10)位置的亮度、蓝色分量、红色分量的值。
- # if y1 < 50 and y2 < 50 and y3 < 50 and y4 < 50:
- # file_list.remove(imagePath)
- # else:
- # cv_num_list.append(fm)
- # # 打印清晰度值:
- # print("fm",fm)
- # # 打印文件路径
- # print("imagePath",imagePath)
- # print("////////////////////////////////////////////////////////n")
- # print("cv_num_list:\n",cv_num_list)
- # # 清晰度列表和文件列表对应,生成dict
- # # file_cv_dict = dict(zip(cv_num_list,file_list))
- # # 清晰度列表和文件列表对应,生成tuple
- # file_cv_tuple = tuple(zip(cv_num_list,file_list))
- # print("file_cv_tuple:\n",file_cv_tuple)
- # print("=========================================/n")
- # file_cv_tuple_list = list(file_cv_tuple)
- # print("file_cv_tuple_list:\n",file_cv_tuple_list)
- # print("*****************************************/n")
- # # 按照清晰度排序:, reverse=True降序
- # result = sorted(file_cv_tuple_list, key=lambda s: s[0],reverse=True)
- # print("result:\n",result)
- # # 切片取清晰度最高的前五张图片:
- # # result5 = result[0:5]
- # result5 = result[0:1]
- # print("result5:\n",result5)
- # pic_name = datetime.datetime.now().strftime('%Y%m')
- # # 定义要创建的目录:
- # mkpath="./pyftp/ftp_file/bzy_photo/" + imei + "/" + pic_name
- # # 调用函数,创建目录:
- # mkdir(mkpath)
- # for i in result5:
- # #i值:(137.06453470539032, 'images\\192.168.2.64_01_20190802095315882_ALARM_INPUT.jpg')
- # print("file path:",i[1])
- # #复制文件:
- # shutil.copy(i[1],mkpath)
- # # os.system("rm ./pyftp/ftp_file/bzy_test/%s/*.jpg -rf"%imei)
- # 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")))
- # print("-----------------image move success----------------------")
- # equip = Equip.objects.get(equip_id=imei)
- # file_dir="pyftp/ftp_file/bzy_photo/" + imei + "/" + pic_name
- # for root, dirs, files in os.walk(file_dir):
- # print("当前目录为=========>>",root) #当前目录路径
- # print("当前子目录为=========>>",dirs) #当前路径下所有子目录
- # print("当前目录文件为=========>>",files) #当前路径下所有非目录子文件
- # for i in files:
- # photo_addr = file_dir + "/" + i
- # print("文件夹图片路径===========》》",photo_addr)
- # if BZYphoto.objects.filter(addr=photo_addr).exists():
- # print("照片存在")
- # else:
- # BZYphoto.objects.create(equip_id=equip, addr=photo_addr)
- # print("照片不存在")
- # except Exception as a:
- # print("==========%s========"%a)
- # print("-----------------image move default----------------------")
- if __name__ == '__main__':
- client = mqtt.Client(
- client_id="PY_MQTT_PHOTO_BZY",
- clean_session=True,
- userdata=None,
- # protocol=MQTTv311,# 数据库版本
- )
- # 必须设置,否则会返回「Connected with result code 4」
- client.username_pw_set("admin", "password")
- client.on_connect = on_connect
- client.on_message = on_message
- HOST = "127.0.0.1"
- client.connect(HOST, 1883, 60)
- client.loop_forever()
|