import cv2 import socket import numpy as np # 创建socket连接 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置服务器地址和端口号 server_address = ('10.132.11.225', 8000) # 连接服务器 try: client_socket.connect(server_address) except socket.error as e: print("Failed to connect to server: {}".format(e)) exit() # 采集摄像头中的照片 cap = cv2.VideoCapture(0) # 检查摄像头是否打开成功 if not cap.isOpened(): print("Failed to open camera") exit() while True: # 采集一帧照片 ret, frame = cap.read() # 检查照片采集是否成功 if not ret: print("Failed to capture frame") break # 在窗口中显示照片 cv2.imshow('frame', frame) # 等待按下空格键拍摄照片 if cv2.waitKey(1) == ord(' '): # 将照片转换为JPEG格式,并压缩 _, jpeg = cv2.imencode('.jpg', frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70]) # 判断数据大小是否符合要求 if len(jpeg) > 1024 * 1024: print("Data size too large") continue # 将JPEG数据转换为numpy数组,发送到服务器 data = np.array(jpeg).tobytes() # 发送数据到服务器 try: client_socket.sendall(data) # 接收确认信息 response = client_socket.recv(1024) if response != b'OK': print("Failed to receive response from server") break except socket.error as e: print("Failed to send data to server: {}".format(e)) break # 等待按下ESC键退出循环 elif cv2.waitKey(1) == 27: break # 关闭socket连接和摄像头 client_socket.close() cap.release() cv2.destroyAllWindows()写一个他的接收端
时间: 2024-02-14 17:16:27 浏览: 148
好的,以下是一个简单的接收端程序:
```
import socket
import numpy as np
import cv2
# 创建socket连接
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置服务器地址和端口号
server_address = ('10.132.11.225', 8000)
# 绑定地址和端口号
server_socket.bind(server_address)
# 开始监听
server_socket.listen(1)
# 等待客户端连接
print("Waiting for client connection...")
client_socket, client_address = server_socket.accept()
print("Client connected: {}".format(client_address))
# 循环接收客户端发送的数据
while True:
# 接收数据
data = bytearray()
while True:
packet = client_socket.recv(1024)
if not packet:
break
data += packet
# 将接收到的数据转换为numpy数组
if len(data) > 0:
jpeg = np.frombuffer(data, dtype=np.uint8)
# 将JPEG数据解码为图像
img = cv2.imdecode(jpeg, cv2.IMREAD_COLOR)
# 在窗口中显示图像
cv2.imshow('image', img)
# 发送确认信息
client_socket.sendall(b'OK')
# 等待按下ESC键退出循环
if cv2.waitKey(1) == 27:
break
# 关闭socket连接和窗口
client_socket.close()
server_socket.close()
cv2.destroyAllWindows()
```
这个程序首先创建一个socket连接,并绑定到指定的地址和端口号。然后它进入一个循环,等待客户端连接。一旦客户端连接成功,它会循环接收客户端发送的数据,将接收到的JPEG数据解码为图像,并在窗口中显示图像。程序还会向客户端发送确认信息,以便客户端知道数据已经成功接收。如果按下ESC键,则程序会退出循环,关闭socket连接和窗口。
阅读全文