feat:新增通信协议,修改数据接收+处理部分

This commit is contained in:
GG 2024-06-13 22:04:02 +08:00
parent 6a063345c7
commit 8771f84a7b
8 changed files with 96 additions and 38 deletions

2
.idea/.name generated
View File

@ -1 +1 @@
04average.ipynb main.py

View File

@ -4,7 +4,7 @@
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.idea/copilot/chatSessions" /> <excludeFolder url="file://$MODULE_DIR$/.idea/copilot/chatSessions" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="jdk" jdkName="tengg" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
</module> </module>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

View File

@ -0,0 +1,5 @@
import pathlib
file_path = pathlib.Path(__file__)
ROOT_DIR = file_path.parent

View File

@ -18,7 +18,7 @@ import time
import os import os
from root_dir import ROOT_DIR from root_dir import ROOT_DIR
import logging import logging
from utils import create_pipes, receive_rgb_data, send_data, receive_spec_data, analyze_tomato, analyze_passion_fruit from utils import parse_protocol, create_pipes, receive_rgb_data, send_data, receive_spec_data, analyze_tomato, analyze_passion_fruit
from collections import deque from collections import deque
import time import time
import io import io
@ -26,7 +26,7 @@ from PIL import Image
import threading import threading
import queue import queue
def process_data(img: any) -> tuple: def process_data(cmd: str, img: any) -> tuple:
""" """
处理指令 处理指令
@ -65,56 +65,55 @@ def main(is_debug=False):
while True: while True:
long_axis_list = [] long_axis_list = []
short_axis_list = [] short_axis_list = []
defect_num_sum = 0 max_defect_num = 0 # 初始化最大缺陷数量为0
total_defect_area_sum = 0 max_total_defect_area = 0 # 初始化最大总像素数为0
rp = None rp = None
start_time = time.time() # start_time = time.time()
for i in range(5): for i in range(5):
# start_time = time.time() # start_time = time.time()
data = receive_rgb_data(rgb_receive)
img_data = receive_rgb_data(rgb_receive) cmd, img = parse_protocol(data)
image = Image.open(io.BytesIO(img_data)) # print(img.shape)
img = np.array(image)
print(img.shape)
# end_time = time.time() # end_time = time.time()
# elapsed_time = end_time - start_time # elapsed_time = end_time - start_time
# print(f'接收时间:{elapsed_time}秒') # print(f'接收时间:{elapsed_time}秒')
long_axis, short_axis, number_defects, total_pixels, rp = process_data(img=img) long_axis, short_axis, number_defects, total_pixels, rp = process_data(cmd=cmd, img=img)
# print(long_axis, short_axis, number_defects, type(total_pixels), rp.shape) # print(long_axis, short_axis, number_defects, type(total_pixels), rp.shape)
if i <= 2: if i <= 2:
long_axis_list.append(long_axis) long_axis_list.append(long_axis)
short_axis_list.append(short_axis) short_axis_list.append(short_axis)
# 更新最大缺陷数量和最大总像素数
max_defect_num = max(max_defect_num, number_defects)
max_total_defect_area = max(max_total_defect_area, total_pixels)
if i == 1: if i == 1:
rp_result = rp rp_result = rp
defect_num_sum += number_defects
total_defect_area_sum += total_pixels
long_axis = round(sum(long_axis_list) / 3) long_axis = round(sum(long_axis_list) / 3)
short_axis = round(sum(short_axis_list) / 3) short_axis = round(sum(short_axis_list) / 3)
# print(type(long_axis), type(short_axis), type(defect_num_sum), type(total_defect_area_sum), type(rp_result)) # print(type(long_axis), type(short_axis), type(defect_num_sum), type(total_defect_area_sum), type(rp_result))
spec_data = receive_spec_data(spec_receive) spec_data = receive_spec_data(spec_receive)
print(f'光谱数据接收长度:', len(spec_data)) cmd, spec_data = parse_protocol(spec_data)
# print(f'光谱数据接收长度:', len(spec_data))
response = send_data(pipe_send=rgb_send, long_axis=long_axis, short_axis=short_axis, response = send_data(pipe_send=rgb_send, long_axis=long_axis, short_axis=short_axis,
defect_num=defect_num_sum, total_defect_area=total_defect_area_sum, rp=rp_result) defect_num=max_defect_num, total_defect_area=max_total_defect_area, rp=rp_result)
end_time = time.time() # end_time = time.time()
elapsed_time = (end_time - start_time) * 1000 # elapsed_time = (end_time - start_time) * 1000
print(f'总时间:{elapsed_time}毫秒') # print(f'总时间:{elapsed_time}毫秒')
#
print(long_axis, short_axis, defect_num_sum, total_defect_area_sum, rp_result.shape) # print(long_axis, short_axis, defect_num_sum, total_defect_area_sum, rp_result.shape)

View File

@ -0,0 +1,5 @@
import pathlib
file_path = pathlib.Path(__file__)
ROOT_DIR = file_path.parent

View File

@ -19,36 +19,85 @@ import select
import msvcrt import msvcrt
from classifer import Tomato, Passion_fruit from classifer import Tomato, Passion_fruit
def receive_rgb_data(pipe): def receive_rgb_data(pipe):
try: try:
# 读取图片数据 # 读取图片数据长度
len_img = win32file.ReadFile(pipe, 4, None) len_img = win32file.ReadFile(pipe, 4, None)
data_size = int.from_bytes(len_img[1], byteorder='big') data_size = int.from_bytes(len_img[1], byteorder='big')
result, img_data = win32file.ReadFile(pipe, data_size, None) # 读取实际图片数据
return img_data result, data = win32file.ReadFile(pipe, data_size, None)
# 检查读取操作是否成功
if result != 0:
print(f"读取失败,错误代码: {result}")
return None
# 返回成功读取的数据
return data
except Exception as e: except Exception as e:
print(f"数据接收失败,错误原因: {e}") print(f"数据接收失败,错误原因: {e}")
return None return None
def receive_spec_data(pipe): def receive_spec_data(pipe):
try: try:
# 读取图片数据长度 # 读取光谱数据长度
len_spec = win32file.ReadFile(pipe, 4, None) len_spec = win32file.ReadFile(pipe, 4, None)
if len_spec is None:
# 未能读取到数据长度,返回"0"
return "0"
data_size = int.from_bytes(len_spec[1], byteorder='big') data_size = int.from_bytes(len_spec[1], byteorder='big')
if data_size == 0: # 读取光谱数据
# 接收到空数据,返回"0"
return "0"
# 读取图片数据
result, spec_data = win32file.ReadFile(pipe, data_size, None) result, spec_data = win32file.ReadFile(pipe, data_size, None)
# 检查读取操作是否成功
if result != 0:
print(f"读取失败,错误代码: {result}")
return None
# 返回成功读取的数据
return spec_data return spec_data
except Exception as e: except Exception as e:
print(f"数据接收失败,错误原因: {e}") print(f"数据接收失败,错误原因: {e}")
return '0' return None
def parse_protocol(data: bytes) -> (str, any):
"""
指令转换.
:param data:接收到的报文
:return: 指令类型和内容
"""
try:
assert len(data) > 2
except AssertionError:
logging.error('指令转换失败长度不足3')
return '', None
cmd, data = data[:2], data[2:]
cmd = cmd.decode('ascii').strip().upper()
if cmd == 'TO':
n_rows, n_cols, img = data[:2], data[2:4], data[4:]
try:
n_rows, n_cols = [int.from_bytes(x, byteorder='big') for x in [n_rows, n_cols]]
except Exception as e:
logging.error(f'长宽转换失败, 错误代码{e}, 报文大小: n_rows:{n_rows}, n_cols: {n_cols}')
return '', None
try:
assert n_rows * n_cols * 3 == len(img)
# 因为是float32类型 所以长度要乘12 如果是uint8则乘3
except AssertionError:
logging.error('图像指令IM转换失败数据长度错误')
return '', None
img = np.frombuffer(img, dtype=np.uint8).reshape((n_rows, n_cols, -1))
return cmd, img
elif cmd == 'PF':
n_rows, n_cols, n_bands, spec = data[:2], data[2:4], data[4:6], data[6:]
try:
n_rows, n_cols, n_bands = [int.from_bytes(x, byteorder='big') for x in [n_rows, n_cols, n_bands]]
except Exception as e:
logging.error(f'长宽转换失败, 错误代码{e}, 报文大小: n_rows:{n_rows}, n_cols: {n_cols}, n_bands: {n_bands}')
return '', None
try:
assert n_rows * n_cols * n_bands * 4 == len(spec)
except AssertionError:
logging.error('图像指令转换失败,数据长度错误')
return '', None
spec = np.frombuffer(spec, dtype=np.uint16).reshape(n_cols, n_rows, -1)
return cmd, spec
def create_pipes(rgb_receive_name, rgb_send_name, spec_receive_name): def create_pipes(rgb_receive_name, rgb_send_name, spec_receive_name):
while True: while True: