关键词搜索

源码搜索 ×
×

Python文档阅读笔记-Car detection with OpenCV

发布2023-03-20浏览1305次

详情内容

人脸检测中,使用预先被训练过的模型文件去侦测脸和眼睛。同样使用预先被训练过来的模型文件去检测汽车。将用这个模型检测出来的汽车用矩形框出来。

代码如下:

  1. # OpenCV Python program to detect cars in video frame
  2. # import libraries of python OpenCV
  3. import cv2
  4. # capture frames from a video
  5. cap = cv2.VideoCapture('video.avi')
  6. # Trained XML classifiers describes some features of some object we want to detect
  7. car_cascade = cv2.CascadeClassifier('cars.xml')
  8. # loop runs if capturing has been initialized.
  9. while True:
  10. # reads frames from a video
  11. ret, frames = cap.read()
  12. # convert to gray scale of each frames
  13. gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
  14. # Detects cars of different sizes in the input image
  15. cars = car_cascade.detectMultiScale(gray, 1.1, 1)
  16. # To draw a rectangle in each cars
  17. for (x,y,w,h) in cars:
  18. cv2.rectangle(frames,(x,y),(x+w,y+h),(0,0,255),2)
  19. # Display frames in a window
  20. cv2.imshow('video2', frames)
  21. # Wait for Esc key to stop
  22. if cv2.waitKey(33) == 27:
  23. break
  24. # De-allocate any associated memory usage
  25. cv2.destroyAllWindows()

下面用个图片来试下,代码改成:

  1. # OpenCV Python program to detect cars in video frame
  2. # import libraries of python OpenCV
  3. import cv2
  4. if __name__ == '__main__':
  5. # capture frames from a video
  6. cap = cv2.imread('c1.jpg')
  7. # Trained XML classifiers describes some features of some object we want to detect
  8. car_cascade = cv2.CascadeClassifier('haarcascade_car.xml')
  9. # convert to gray scale of each frames
  10. gray = cv2.cvtColor(cap, cv2.COLOR_BGR2GRAY)
  11. # Detects cars of different sizes in the input image
  12. cars = car_cascade.detectMultiScale(gray, 1.1, 1)
  13. # To draw a rectangle in each cars
  14. for (x, y, w, h) in cars:
  15. cv2.rectangle(cap, (x, y), (x + w, y + h), (0, 0, 255), 2)
  16. # Display frames in a window
  17. cv2.imshow('ret', cap)
  18. cv2.waitKey(0)
  19. # De-allocate any associated memory usage
  20. cv2.destroyAllWindows()
  21. pass

结果如下:

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载