import numpy as np import serial import cv2 # create video capture, serial port cap = cv2.VideoCapture(0) ser = serial.Serial('/dev/ttyUSB0', 115200) # main loop while(1): # read the current video frame _, frame = cap.read() # resize captured video frame to smaller size for faster processing frame = cv2.resize(frame, (110, 80), interpolation = cv2.INTER_LINEAR) # smooth frame frame = cv2.blur(frame, (3, 3)) # convert to hsv and find range of colors hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) thresh = cv2.inRange(hsv, np.array((5, 60, 60)), np.array((15, 255, 255))) thresh2 = thresh.copy() # find contours in the threshold image contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # finding contour with maximum area and store it as best_cnt max_area = 0 for cnt in contours: area = cv2.contourArea(cnt) if area > max_area: max_area = area best_cnt = cnt # find centroid of best_cnt and draw a red box there, send to serial port if max_area > 0: M = cv2.moments(best_cnt) cx, cy = int(M['m10'] / M['m00']), int(M['m01'] / M['m00']) cz = int(max_area) cv2.rectangle(frame, (cx - 5, cy - 5), (cx + 5, cy + 5), (0, 0, 255), 2) ser.write('!') ser.write('&') ser.write(chr(cx)) ser.write(chr(cy)) ser.write(chr(cz & 0xff)) ser.write(chr(cz >> 8)) # Show it, if key pressed is 'Esc', exit the loop cv2.imshow('Fr', frame) cv2.imshow('Th', thresh2) if cv2.waitKey(1) == 27: break # Clean up everything before leaving ser.close() cap.release() cv2.destroyAllWindows()