import cv2 import socket import numpy as np server_ip = '10.132.11.225' server_port = 8000 cap = cv2.VideoCapture(0) client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((server_ip, server_port)) while True: ret, frame = cap.read() cv2.imshow('frame', frame) # 显示视频帧 key = cv2.waitKey(1) & 0xFF if key == ord('s'): # 当按下's'键时,拍摄照片 _, img_encoded = cv2.imencode('.jpg', frame) img_bytes = np.array(img_encoded).tobytes() client_socket.sendall(img_bytes) elif key == ord('q'): # 当按下'q'键时,退出程序 break cap.release() cv2.destroyAllWindows() client_socket.close()优化一下可以连续拍照
时间: 2024-03-24 13:40:14 浏览: 88
可以在 while 循环中增加一个变量,控制连续拍照的次数,例如:
```python
import cv2
import socket
import numpy as np
server_ip = '10.132.11.225'
server_port = 8000
cap = cv2.VideoCapture(0)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_ip, server_port))
num_photos = 0 # 记录拍照次数
max_photos = 10 # 最大拍照次数
while num_photos < max_photos:
ret, frame = cap.read()
cv2.imshow('frame', frame) # 显示视频帧
key = cv2.waitKey(1) & 0xFF
if key == ord('s'): # 当按下's'键时,拍摄照片
_, img_encoded = cv2.imencode('.jpg', frame)
img_bytes = np.array(img_encoded).tobytes()
client_socket.sendall(img_bytes)
num_photos += 1 # 拍照次数加1
elif key == ord('q'): # 当按下'q'键时,退出程序
break
cap.release()
cv2.destroyAllWindows()
client_socket.close()
```
这样,当按下's'键时,程序会拍摄一张照片并发送给服务器,然后将拍照次数加1,直到达到最大拍照次数为止。当按下'q'键时,程序会退出。
阅读全文