前言: 小白一个, 没有系统性的学习过python网络通信,只是单纯的cv加修改代码,仅作留念以及参考用,感谢互联网博主们和bito插件,使得chatGPT得以免费使用.
另外该多线程传输图片的速度比没有多线程执行还满,后续不对python服务端做优化,而改为C++服务端实现.写出来继续再分享把
前篇博客地址
python客户端
采用生存者消费者模式、模式2和joinablequeue库.
客户端实现还是比较简单的,麻烦在server端
import pickle
import time
from multiprocessing import Process, JoinableQueue
from queue import Queue
from multiprocessing.connection import Client, Listener
from client_apart import draw_box
from image import plot_boxes, img_encode
import os
from natsort import ns, natsorted
host = 'localhost'
port = 9006
total_time = 0
def img_product(img_queue, path, path_mode='image'):
if path_mode == 'image':
img = img_encode(path)
img_obj = {
'frame_num': 1, 'image': img} # need frame_num?
img_queue.put(img_obj)
elif path_mode == 'dir':
dir_list = os.listdir(path)
files = natsorted(dir_list, alg=ns.PATH) # 顺序读取文件名
i = 1
for filename in files:
img_path = path + '/' + filename
img = img_encode(img_path)
img_obj = {
'frame_num': i, 'image': img} # need frame_num?
i += 1
img_queue.put(img_obj)
img_queue.put({
'frame_num': 0, 'image': "end"}) # end signal
img_queue.join()
def server_consumer(img_queue):
# 1. send data
while True:
img_obj = img_queue.get()
if img_obj is None:
client.close() # avoid connection-reset-by-peer
break # exit end
data_bytes = pickle.dumps(img_obj)
start = int(round(time.time() * 1000))
start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
client.send(data_bytes) # 40ms/per send img
# print('send cost time: ', (end - start))
img_queue.task_done()
try:
det_result = client.recv()
end = int(round(time.time() * 1000))
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print('recv cost time: ', (end-start))
except EOFError:
break
det_result = pickle.loads(det_result)
draw_box(det_result, img_obj)
if __name__ == '__main__':
client = Client((host, port))
Listener()
img_dir = './data'
one_img = './data/Enterprise001.jpg'
mode = 'dir'
img_jq = JoinableQueue()
producer = Process(target=img_product, args=(img_jq, img_dir, mode,))
consumer = Process(target=server_consumer, args=(img_jq,))
consumer.daemon = True # set daemon but not set join()
producer.start()
consumer.start()
producer.join()
Python服务端
此处接受图片和发送结果线程处在一个类内,使得可以共享一个Listener,来自chatGPT的idea.
from ctypes import *
import ctypes
import time
impo
Python多线程图像传输与C++模型交互优化

最低0.47元/天 解锁文章
9026

被折叠的 条评论
为什么被折叠?



