python 建立本地 YOLOv3 服务器

本文介绍了一个使用YOLOv3进行实时目标检测的Python实现案例,详细展示了如何通过Socket通信,在Python与Matlab之间传输图像数据并返回检测结果。此方案适用于需要在不同编程环境间进行图像识别任务的应用场景。
部署运行你感兴趣的模型镜像
# -- encoding=gbk --
import cv2
import numpy as np
import os
import socket
import time


with open('yolo/coco.names','r') as file:     # 这是读取所有种类的名字
	LABELS = file.read().splitlines()

args = {
    "yolo": "yolo",                 #.weights 和 .cfg 文件所在的目录
    "confidence": 0.5,              # minimum bounding box confidence
    "threshold": 0.3,               # NMS threshold
}

# derive the paths to the YOLO weights and model configuration
weightsPath = os.path.sep.join([args["yolo"], "yolov3.weights"])
configPath = os.path.sep.join([args["yolo"], "yolov3.cfg"])
 
# load YOLO object detector trained on COCO dataset (80 classes)
print("[INFO] loading YOLO from disk...")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)


sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  # IPV4,TCP协议
sock.bind(('127.0.0.1',54321))  # 绑定ip和端口,bind接受的是一个元组
sock.listen(1)  # 置监听数量
print("start server")

while True:
	connection, address = sock.accept()
	print("client ip is:", address)
	buf = connection.recv(40960)
	bufstr = buf.decode('utf8')
	print('recieved:',bufstr)
	# load our input image and grab its spatial dimensions
	image = cv2.imread(bufstr)
	(H, W) = image.shape[:2]

	# determine only the *output* layer names that we need from YOLO
	ln = net.getLayerNames()
	ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]

	# construct a blob from the input image and then perform a forward
	# pass of the YOLO object detector, giving us our bounding boxes and
	# associated probabilities
	blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416),
		swapRB=True, crop=False)
	net.setInput(blob)
	start = time.time()
	layerOutputs = net.forward(ln)
	end = time.time()

	# show timing information on YOLO
	print("[INFO] YOLO took {:.6f} seconds".format(end - start))

	boxes, confidences, classIDs = [], [], []
	# loop over each of the layer outputs
	for output in layerOutputs:
		# loop over each of the detections
		for detection in output:
			# extract the class ID and confidence of the current object detection
			scores = detection[5:]
			classID = np.argmax(scores)
			confidence = scores[classID]

			# filter out weak predictions by ensuring the detected
			# probability is greater than the minimum probability
			if confidence > args["confidence"]:
				# scale the bounding box coordinates back relative to the size of the image,
				# keeping in mind that YOLO actually returns the center (x, y)-coordinates
				# of the bounding box followed by the boxes' width and height
				box = detection[0:4] * np.array([W, H, W, H])
				(centerX, centerY, width, height) = box.astype("int")

				# use the center (x, y)-coordinates to derive the top and left corner of the bounding box
				x = int(centerX - (width / 2))
				y = int(centerY - (height / 2))

				# update our list of bounding box coordinates, confidences, and class IDs
				boxes.append([x, y, int(width), int(height)])
				confidences.append(float(confidence))
				classIDs.append(classID)

	idxs = cv2.dnn.NMSBoxes(boxes, confidences, args["confidence"],
		args["threshold"])

	# ensure at least one detection exists
	if len(idxs) > 0:
		# loop over the indexes we are keeping
		for i in idxs.flatten():
			# extract the bounding box coordinates
			(x, y) = (boxes[i][0], boxes[i][1])
			(w, h) = (boxes[i][2], boxes[i][3])
			print("{}:{:.4f}".format(LABELS[classIDs[i]], confidences[i]))
			text = "[{},{},{},{},{}]".format(classIDs[i], x,y,w,h)
			print('send:',text)

			connection.send(bytes(text, encoding="utf8"))  # 发送数据
			connection.close()  # 关闭连接
			# time.sleep(1)
			break
sock.close()  # 关闭服务器

服务器接收图片地址,发送图片中对象的 bbox

下面是 log

[INFO] loading YOLO from disk...
start server

client ip is: ('127.0.0.1', 57295)
recieved: ./Least_Auklet_0011_795109.jpg
[INFO] YOLO took 1.371394 seconds
bird:0.9966
send: [14,9,10,179,195]

client ip is: ('127.0.0.1', 57296)
recieved: ./Least_Auklet_0011_795109.jpg
[INFO] YOLO took 0.636665 seconds
bird:0.9966
send: [14,9,10,179,195]

如此一来,python 就可以和 matlab 通信了。

matlab 端:

clc
clear

data_all=[];%用于存储所有的数据
t = tcpip('localhost', 54321, 'Timeout', 30,'InputBufferSize',1024);%连接这个ip和这个端口的服务器

while(1)
    fopen(t);
    fwrite(t,'./Least_Auklet_0011_795109.jpg');%发送一段数据给tcp服务器。服务器好知道matlab的ip和端口
    while(1) %轮询,直到有数据了再fread
        nBytes = get(t,'BytesAvailable');
        if nBytes>0
            break;
        end
    end
    receive = fread(t,nBytes);%读取tcp服务器传来的数据
    fclose(t);
    data=str2num(char(receive(1:end)')); %将ASCII码转换为str,再将str转换为数组
    data
    pause(1);
end
delete(t);

您可能感兴趣的与本文相关的镜像

Yolo-v5

Yolo-v5

Yolo

YOLO(You Only Look Once)是一种流行的物体检测和图像分割模型,由华盛顿大学的Joseph Redmon 和Ali Farhadi 开发。 YOLO 于2015 年推出,因其高速和高精度而广受欢迎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值