TShopping

標題: OpenCV findContours 與 drawContours 用法 [打印本頁]

作者: woff    時間: 2021-4-6 22:08
標題: OpenCV findContours 與 drawContours 用法
一、獲取輪廓--findContours
cv2.findContours() 的第二個引數主要有
cv2.findContours() 的第三個引數 method為輪廓的近似辦法
返回值:image, contours, hierarchy
二、繪出輪廓--drawContours
cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset ]]]]])
三、測試
  1. import cv2

  2. img = cv2.imread('test.png')
  3. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  4. ret,binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

  5. _,contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

  6. draw_img0 = cv2.drawContours(img.copy(),contours,0,(0,255,255),3)
  7. draw_img1 = cv2.drawContours(img.copy(),contours,1,(255,0,255),3)
  8. draw_img2 = cv2.drawContours(img.copy(),contours,2,(255,255,0),3)
  9. draw_img3 = cv2.drawContours(img.copy(), contours, -1, (0, 0, 255), 3)


  10. print ("contours:型別:",type(contours))
  11. print ("第0 個contours:",type(contours[0]))
  12. print ("contours 數量:",len(contours))

  13. print ("contours[0]點的個數:",len(contours[0]))
  14. print ("contours[1]點的個數:",len(contours[1]))

  15. cv2.imshow("img", img)
  16. cv2.imshow("draw_img0", draw_img0)
  17. cv2.imshow("draw_img1", draw_img1)
  18. cv2.imshow("draw_img2", draw_img2)
  19. cv2.imshow("draw_img3", draw_img3)

  20. cv2.waitKey(0)
  21. cv2.destroyAllWindows()

  22. #################################
  23. # 輸出:
  24. # contours:型別: <class 'list'>
  25. # 第0 個contours: <class 'numpy.ndarray'>
  26. # contours 數量: 3
  27. # contours[0]點的個數: 6
  28. # contours[1]點的個數: 74
複製代碼


文章出處





歡迎光臨 TShopping (http://www.tshopping.com.tw/) Powered by Discuz! X3.2