You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.2 KiB

import cv2
import numpy as np
def init_camera():
global cap
cap = cv2.VideoCapture(0)
def select_color_area(frame):
global color_selected, greenLower, greenUpper
cv2.imshow('Select color area', frame)
if cv2.waitKey(1) & 0xFF == ord('c'):
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
roi = cv2.selectROI('Select color area', hsv)
if roi != (0, 0, 0, 0):
roi_hsv = hsv[int(roi[1]):int(roi[1] + roi[3]), int(roi[0]):int(roi[0] + roi[2])]
color_mean = np.mean(roi_hsv, axis=(0, 1))
color_mean = np.uint8(color_mean)
greenLower = np.array([max(color_mean[0] - 10, 0), 50, 50])
greenUpper = np.array([min(color_mean[0] + 10, 179), 255, 255])
print(f"Selected color: {color_mean}, Lower bound: {greenLower}, Upper bound: {greenUpper}")
color_selected = True
cv2.destroyAllWindows()
else:
print("No ROI selected. Exiting...")
cv2.destroyAllWindows()
return False
return True
def track_color(frame, greenLower, greenUpper):
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, greenLower, greenUpper)
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) > 200:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
return frame, mask
def main():
init_camera()
color_selected = False
while True:
ret, frame = cap.read()
if not ret:
break
if not color_selected:
if not select_color_area(frame):
break
else:
frame, mask = track_color(frame, greenLower, greenUpper)
cv2.imshow('Original', frame)
cv2.imshow('Mask', mask)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()