OpenCV輪廓排序(按照面積大小),原圖如下:

代碼如下:
import cv2
import numpy as np
# putText函數使用的字體定義
font = cv2.FONT_HERSHEY_SIMPLEX
PI = 3.1415926
# 讀取圖片、灰度轉換、OTSU閾值
img = cv2.imread("test.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# 查看二值化結果
cv2.imshow("thres", thresh)
cv2.imwrite("thres.jpg", thresh)
# 輪廓查找
_, contours,hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
def cnt_area(cnt):
area = cv2.contourArea(cnt)
return area
contours.sort(key = cnt_area, reverse=False)
for i in range(0, len(contours)):
(x, y, w, h) = cv2.boundingRect(contours[i])
cv2.rectangle(img,(x,y),(x+w, y+h),(255,0,0),2, cv2.LINE_AA)
cv2.putText(img,"No.%d"%(i+1),(x,y-5),font,0.8,(255,0,0),2)
cv2.imshow("contours", img)
cv2.imwrite("result1.jpg",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
reverse=False(默認)降序排列,reverse=True升序排列
效果如如下:


更多相關文章咨詢歡迎關注:OpenCV與AI深度學習

