clean main-1

Former-commit-id: 2e5b02b7800d14661a4fe1d0d85fd00ec7678863
This commit is contained in:
2025-05-26 19:50:22 +08:00
parent 90a54aae45
commit f39768eb8b

View File

@ -1,60 +1,40 @@
import torch
import cv2 import cv2
import time import time
import os
import serial
from datetime import datetime from datetime import datetime
import numpy as np import numpy as np
import joblib
import ch340 import ch340
from threading import Thread from threading import Thread
import atexit import atexit
LOCAL_DEBUG = False
if LOCAL_DEBUG:
print("WARNING: Local debug mode is enabled. Serial communication will be skipped.")
time.sleep(2)
class MAT: class MAT:
def __init__(self, videoSourceIndex=0, weights_path = "resnet34-1Net.pth", json_path = 'class_indices.json', classes = 2,bounce_time=1): def __init__(self, videoSourceIndex=0, bounce_time=1):
print('实验初始化中') print('Initializing MAT...')
self.data_root = os.getcwd() self.videoSourceIndex = videoSourceIndex
self.videoSourceIndex = videoSourceIndex # 摄像机编号 self.cap = cv2.VideoCapture(videoSourceIndex, cv2.CAP_DSHOW)
self.cap = cv2.VideoCapture(videoSourceIndex, cv2.CAP_DSHOW) # 打开摄像头
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
self.ch340 = ch340.CH340() self.ch340 = ch340.CH340()
self.classes = classes self.bounce_time = bounce_time
self.bounce_time = bounce_time # 防抖时间 self.total_volume = 0
self.total_volume = 0 # 记录总体积 self.now_volume = 0
self.now_volume = 0 # 记录当前注射泵内体积 self.start_time = time.time()
self.volume_list = [] # 记录体积变化
self.color_list = [] # 记录颜色变化
self.start_time = time.time() # 记录实验开始时间
self.weights_path = os.path.join(self.data_root, weights_path) # 权重文件路径
self.json_path = os.path.join(self.data_root, json_path) # 类别文件路径
# 将开始时间转化为年月日时分秒的格式,后续文件命名都已此命名 # 将开始时间转化为年月日时分秒的格式,后续文件命名都已此命名
self.formatted_time = datetime.fromtimestamp(self.start_time).strftime('%Y%m%d_%H%M%S') self.formatted_time = datetime.fromtimestamp(self.start_time).strftime('%Y%m%d_%H%M%S')
atexit.register(self.start_move_3) atexit.register(self.ch340.stop)
print("实验开始于", self.formatted_time) print("实验开始于", self.formatted_time)
def start_move_1(self): # 抽料程序 def ch340_pull(self):
self.ch340.max_speed() self.ch340.max_speed()
self.ch340.pull(vol=12) self.ch340.pull(vol=12)
print('完成抽取') print('完成抽取')
def start_move_init(self): # init def ch340_init(self):
self.ch340.push(speed=1,t=1) self.ch340.push(speed=1,t=1)
self.ch340.pull(speed=1.2,vol=3) self.ch340.pull(speed=1.2,vol=3)
print('INITED') print('CH340 INITED')
def start_move_2(self, speed=0.1): # 进料程序 def ch340_push(self, speed=0.1):
self.ch340.push(speed=speed, t=1) self.ch340.push(speed=speed, t=1)
def start_move_3(self): # 进料急停
self.ch340.stop()
def _pred(self): def _pred(self):
suc,im = self.cap.read() suc,im = self.cap.read()
if not suc: if not suc:
@ -88,33 +68,28 @@ class MAT:
else: else:
print("Got middle flag, bounce check start, val:",self.total_volume) print("Got middle flag, bounce check start, val:",self.total_volume)
self.typ = 1 self.typ = 1
self.start_move_3() self.ch340.stop()
self.debounce[1].append((time.time(),self.total_volume)) self.debounce[1].append((time.time(),self.total_volume))
elif ret == self.end_kind: elif ret == "colored":
if self.debounce[1]: if self.debounce[1]:
print("Got stop flag, val:",self.total_volume) print("Got stop flag, val:",self.total_volume)
self.running = False self.running = False
self.start_move_3() self.ch340.stop()
return return
else: else:
if self.debounce[0]: if self.debounce[0]:
# print(self.debounce)
if self.debounce[1]: if self.debounce[1]:
# print(self.debounce[1][0][0],now,self.bounce_time)
# print(self.debounce[1][0][0] > now - self.bounce_time)
while self.debounce[1] and self.debounce[1][0][0] > now - self.bounce_time: while self.debounce[1] and self.debounce[1][0][0] > now - self.bounce_time:
self.debounce[1].pop(0) self.debounce[1].pop(0)
while self.debounce[0] and self.debounce[0][0] < now - self.bounce_time: while self.debounce[0] and self.debounce[0][0] < now - self.bounce_time:
self.debounce[0].pop(0) self.debounce[0].pop(0)
self.debounce[0].append(now) self.debounce[0].append(now)
self.thr = Thread(target=self._pred).start() self.thr = Thread(target=self._pred).start()
return ret,0.9 return ret
def my_predictor(self,im): def my_predictor(self,im):
# im = cv2.imread(file)
hsv = cv2.cvtColor(im,cv2.COLOR_BGR2HSV) hsv = cv2.cvtColor(im,cv2.COLOR_BGR2HSV)
s = hsv[:,:,1] s = hsv[:,:,1]
# print(mask)
mask = s>60 mask = s>60
tot = mask.shape[0]*mask.shape[1] tot = mask.shape[0]*mask.shape[1]
val = np.sum(mask) val = np.sum(mask)
@ -141,27 +116,26 @@ class MAT:
if not cv2.imwrite(name,im): if not cv2.imwrite(name,im):
print("Failed to save image",name) print("Failed to save image",name)
def run(self,quick_speed = 0.2, mid_speed=0.1,slow_speed = 0.05,expect:float|int = 5, end_kind = 'orange'): def run(self,quick_speed = 0.2, mid_speed=0.1,slow_speed = 0.05):
self.running = True self.running = True
self.typ = 0 self.typ = 0
self.end_kind = end_kind
self.last = [time.time(),0] self.last = [time.time(),0]
self.debounce = [[],[]] self.debounce = [[],[]]
self.thr = Thread(target=self._pred) self.thr = Thread(target=self._pred)
self.thr.start() self.thr.start()
while self.running: while self.running:
if self.now_volume <= 0: if self.now_volume <= 0:
self.start_move_1() # 抽取12ml self.ch340_pull() # 抽取12ml
self.now_volume += 12 self.now_volume += 12
if self.typ == 0: # 每次加0.2ml if self.typ == 0: # 每次加0.2ml
speed = quick_speed speed = quick_speed
self.start_move_2(speed) self.ch340_push(speed)
self.total_volume += speed self.total_volume += speed
self.now_volume -= speed self.now_volume -= speed
else: else:
speed = slow_speed speed = slow_speed
self.start_move_2(speed) # 每次加0.05ml self.ch340_push(speed) # 每次加0.05ml
self.total_volume += speed self.total_volume += speed
self.now_volume -= speed self.now_volume -= speed
time.sleep(1) time.sleep(1)
@ -169,7 +143,6 @@ class MAT:
self.total_volume = round(self.total_volume, 3) self.total_volume = round(self.total_volume, 3)
self.volume_list.append(self.total_volume)
self.save_img() self.save_img()
cv2.waitKey(1) cv2.waitKey(1)
@ -177,17 +150,12 @@ class MAT:
self.save_img() self.save_img()
print('----->>Visual Endpoint<<-----') print('----->>Visual Endpoint<<-----')
print(f"Total Volume: {self.total_volume} ml") print(f"Total Volume: {self.total_volume} ml")
print("Volume List:", self.volume_list)
print("Color List:", self.color_list)
if __name__ == "__main__": if __name__ == "__main__":
# 创建MAT类的实例并运行 # 创建MAT类的实例并运行
mat = MAT( mat = MAT(
videoSourceIndex = 1, videoSourceIndex = 1,
weights_path = "resnet34-1Net.pth",
json_path = 'class_indices.json',
classes = 2,
bounce_time=0.2 bounce_time=0.2
) )
@ -195,8 +163,6 @@ if __name__ == "__main__":
mat.run( mat.run(
quick_speed = 0.15, quick_speed = 0.15,
slow_speed = 0.05, slow_speed = 0.05,
expect = 10,
end_kind = 'colored',
) )