Opencv对象追踪的示例代码

时间:2022-10-20 21:52:39

1 HSV上下限

颜色的HSV上下限如下表:

Opencv对象追踪的示例代码

2 追踪单个颜色

  1. import cv2 as cv
  2. import numpy as np
  3.  
  4. cap = cv.VideoCapture(0)
  5. lower_color = np.array([0, 43, 46])
  6. upper_color = np.array([10, 255, 255])
  7. while cap.isOpened():
  8. # 读取帧
  9. _, frame = cap.read()
  10. # 转换颜色空间 BGR 到 HSV
  11. hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
  12. # 设置HSV的阈值使得只取某色
  13. mask = cv.inRange(hsv, lower_color, upper_color)
  14. # 将掩膜和图像逐像素相加
  15. res = cv.bitwise_and(frame, frame, mask=mask)
  16. # cv.imshow('frame', frame)
  17. cv.imshow('mask', mask)
  18. cv.imshow('res', res)
  19. if cv.waitKey(1) == ord("q"):
  20. break
  21. cv.destroyAllWindows()

结果如下:

Opencv对象追踪的示例代码

2 追踪多个颜色

  1. import cv2 as cv
  2. import numpy as np
  3.  
  4. cap = cv.VideoCapture(0)
  5. lower_red = np.array([0, 43, 46])
  6. upper_red = np.array([10, 255, 255])
  7. lower_blue = np.array([100, 43, 46])
  8. upper_blue = np.array([124, 255, 255])
  9. while cap.isOpened():
  10. _, frame = cap.read()
  11. hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
  12. mask1 = cv.inRange(hsv, lower_red, upper_red)
  13. mask2 = cv.inRange(hsv, lower_blue, upper_blue)
  14. mask = mask1 + mask2
  15. res = cv.bitwise_and(frame, frame, mask=mask)
  16. # cv.imshow('frame', frame)
  17. cv.imshow('mask', mask)
  18. cv.imshow('res', res)
  19. if cv.waitKey(1) == ord("q"):
  20. break
  21. cv.destroyAllWindows()

Opencv对象追踪的示例代码

参考文献:

【1】OpenCV中HSV颜色模型及颜色分量范围

到此这篇关于Opencv对象追踪的示例代码的文章就介绍到这了,更多相关Opencv 对象追踪内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_44575152/article/details/114799122