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) # 采集摄像头中的照片 cap = cv2.VideoCapture(0) # 检查摄像头是否打开成功 if not cap.isOpened(): print("Failed to open camera") exit() # 连接服务器 while True: try: client_socket.connect(server_address) break except socket.error as e: print("Failed to connect to server: {}".format(e)) continue # 发送照片到服务器 while True: # 采集一帧照片 ret, frame = cap.read() # 检查照片采集是否成功 if not ret: print("Failed to capture frame") break # 将照片转换为JPEG格式,并压缩 _, jpeg = cv2.imencode('.jpg', frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70]) # 将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键退出循环 if cv2.waitKey(1) == 27: break # 关闭socket连接和摄像头 client_socket.close() cap.release() cv2.destroyAllWindows()优化一下
时间: 2024-02-14 20:21:39 浏览: 72
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
这段代码的主要功能是采集摄像头中的照片并发送到服务器,其中使用了OpenCV库和Socket库。
以下是对代码的优化建议:
1. 建议将while True循环中的socket连接放在外面,只连接一次即可。
2. 建议在发送数据到服务器前,先判断一下数据的大小是否符合要求,若超出限制可以进行压缩或者分多个包发送。
3. 建议在发送数据时,使用try...except语句进行异常处理,避免发送失败导致程序崩溃。
4. 建议在程序结束时,关闭socket连接和释放摄像头资源,避免资源浪费和异常。
以下是优化后的代码:
```python
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
# 将照片转换为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键退出循环
if cv2.waitKey(1) == 27:
break
# 关闭socket连接和摄像头
client_socket.close()
cap.release()
cv2.destroyAllWindows()
```
阅读全文