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

OpenCV轮廓排序(按照面积大小),原图如下:

Python OpenCV轮廓排序(按照面积大小)_第1张图片

代码如下:

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()
       

结果如下(面积从小到大,从大到小):

Python OpenCV轮廓排序(按照面积大小)_第2张图片

Python OpenCV轮廓排序(按照面积大小)_第3张图片

更多相关文章咨询欢迎关注:OpenCV与AI深度学习

 

Python OpenCV轮廓排序(按照面积大小)_第4张图片

你可能感兴趣的:(Python OpenCV轮廓排序(按照面积大小))