Python OpenCV轮廓排序(按照面积大小)

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深度学习

 

posted @ 2020-01-10 14:08  Color_Spcae  阅读(8385)  评论(3编辑  收藏  举报