# detect orange -adjustable upper and lower Hue threshholds, and lower Saturation and lower Value threshholds import numpy as np import cv2 def nothing(x): pass # create video capture cap = cv2.VideoCapture(0) cv2.namedWindow('Th') cv2.createTrackbar('HL', 'Th',8,180,nothing) cv2.createTrackbar('HH', 'Th',15,180,nothing) cv2.createTrackbar('SL', 'Th',100,255,nothing) cv2.createTrackbar('VL', 'Th',100,255,nothing) # main loop while(1): # get trackbar variables hl = cv2.getTrackbarPos('HL', 'Th') hh = cv2.getTrackbarPos('HH', 'Th') sl = cv2.getTrackbarPos('SL', 'Th') vl = cv2.getTrackbarPos('VL', 'Th') # read the current video frame _, frame = cap.read() # resize captured video frame to smaller size for faster processing frame = cv2.resize(frame, (300, 200), interpolation = cv2.INTER_LINEAR) # smooth it 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((hl, sl, vl)), np.array((hh, 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 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) # 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 cap.release() cv2.destroyAllWindows()