天天看點

OpenCV | OpenCV檢測圖像輪廓

步驟

  1. 讀取圖像為灰階圖像。
  2. 使用cv2.threshold()函數擷取門檻值圖像。
  3. 使用cv2.findContours()并傳遞門檻值圖像和必要的參數。
  4. findContours()傳回輪廓。您可以将其繪制在原始圖像或空白圖像上。
import cv2
import numpy as np
 
img = cv2.imread('original.png', cv2.IMREAD_UNCHANGED)
 
#convert img to grey
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#set a thresh
thresh = 100
#get threshold image
ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)
#find contours
img2, contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
 
#create an empty image for contours
img_contours = np.zeros(img.shape)
# draw the contours on the empty image
cv2.drawContours(img_contours, contours, -1, (0,255,0), 3)
#save image
cv2.imwrite('contours.png',img_contours) import cv2
import numpy as np
 
img = cv2.imread('original.png', cv2.IMREAD_UNCHANGED)
 
#convert img to grey
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#set a thresh
thresh = 100
#get threshold image
ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)
#find contours
img2, contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
 
#create an empty image for contours
img_contours = np.zeros(img.shape)
# draw the contours on the empty image
cv2.drawContours(img_contours, contours, -1, (0,255,0), 3)
#save image
cv2.imwrite('contours.png',img_contours)       

原圖

OpenCV | OpenCV檢測圖像輪廓

輸出圖

OpenCV | OpenCV檢測圖像輪廓

繼續閱讀