import socket
from collections import deque
import numpy as np
import cv2
import time
import select
def TestClient():
server_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_client.connect(("192.168.10.103", 19999))
camera1 = cv2.VideoCapture(0)
current_camera = camera1
redLower = np.array([156, 43, 46])
redUpper = np.array([180, 255, 255])
mybuffer = 64
pts = deque(maxlen=mybuffer)
index = 2
data = 0
while True:
ready_to_read, _, _ = select.select([server_client], [], [], 0)
if ready_to_read:
data = server_client.recv(1024).decode()
print(data)
(ret, frame) = current_camera.read()
if not ret:
print('No Camera')
break
gs_frame = cv2.GaussianBlur(frame, (5, 5), 0)
hsv = cv2.cvtColor(gs_frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, redLower, redUpper)
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
center = None
if len(cnts) > 0:
c = max(cnts, key=cv2.contourArea)
((center_x, center_y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
cv2.circle(frame, (int(center_x), int(center_y)), int(radius), (0, 255, 255), 2)
cv2.circle(frame, center, 5, (0, 0, 255), -1)
cv2.line(frame, (cx - 10, cy), (cx + 10, cy), (255, 0, 0), 2)
cv2.line(frame, (cx, cy - 10), (cx, cy + 10), (255, 0, 0), 2)
delta_x = 320 - int(center_x)
delta_y = 240 - int(center_y)
if data == '0':
pass
if data == '1':
server_client.send(f"({delta_x},{delta_y})".encode('utf-8'))
print(f"({delta_x},{delta_y})")
cv2.imshow('Frame', frame)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
current_camera.release()
cv2.destroyAllWindows()
server_client.close()
print("server end, exit!")
exit()
if __name__ == '__main__':
TestClient()