查詢輪廓並使用 Python 中的 OpenCV 繪製
對於影像分析的目的是使用Opencv(開放原始碼計算機視覺庫)python庫。安裝opencv後需要匯入的庫名是cv2。
在下面的示例中,我們在影像檔案中查詢輪廓。輪廓幫助我們識別影像中出現的形狀。輪廓被定義為影像邊界上所有具有相同強度的點的連線線。OPenCV中的findContours函式幫助我們識別輪廓。類似地,drawContours函式幫助我們繪製輪廓。以下是它們二者語法。
語法
cv.FindContours(image, mode=CV_RETR_LIST, method=CV_CHAIN_APPROX_SIMPLE) Where image is the name of the image Mode is Contour retrieval mode Method is Contour approximation method cv.DrawContours(img, contours, contourIdx, colour, thickness) Where image is the name of the image contours – All the input contours. contourIdx – Parameter indicating a contour to draw. If it is negative, all the contours are drawn. color – Color of the contours thickness is how thick are the lines drawing the contour
示例
在以下示例中,我們使用下圖作為輸入影像。然後執行以下程式來獲取其周圍的輪廓。
我們可以在上圖中找到三種形狀。我們可以使用以下程式繪製所有形狀或部分形狀周圍的輪廓。
示例
import cv2 # Load an image image = cv2.imread(“path to image file”) # Changing the colour-space LUV = cv2.cvtColor(image, cv2.COLOR_BGR2LUV) # Find edges edges = cv2.Canny(LUV, 10, 100) # Find Contours contours, hierarchy = cv2.findContours(edges,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Find Number of contours print("Number of Contours is: " + str(len(contours))) # Draw yellow border around two contours cv2.drawContours(image, contours, 0, (0, 230, 255), 6) cv2.drawContours(image, contours, 2, (0, 230, 255), 6) # Show the image with contours cv2.imshow('Contours', image) cv2.waitKey(0)
執行上面的程式碼會得到以下結果 -
輸出
Number of Contours found = 3
然後我們得到下圖,顯示輸出。
廣告