1、排序
- sorted(cts, key=cv2.contourArea, reverse=True)
按面积排序,最大的在最前面
2、程序
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 10:49:36 2024
Ky_Area005.py
"""
import cv2
import numpy as np
img = cv2.imread(r'D:\imgs\my_img01.jpg', 1)
new_img = cv2.resize(img, None, fx=0.3, fy=0.3)
rows, cols, channels = new_img.shape
print(rows, cols, channels)
# 显示图像
cv2.imshow('new_img', new_img)
# bright = cv2.convertScaleAbs(new_img, None, 1.1, 30)
# cv2.imshow('bright', bright)
# 将图片转换为灰度图片
gray_img = cv2.cvtColor(new_img, cv2.COLOR_BGR2HSV)
# cv2.imshow('hsv', gray_img)
# 图片二值化处理
low_value = np.array([11, 43, 46])
high_value = np.array([155, 255, 255])
binary_img = cv2.inRange(gray_img, low_value, high_value)
# 腐蚀膨胀
erode = cv2.erode(binary_img, None, iterations=1)
dilate = cv2.dilate(erode, None, iterations=1)
cv2.imshow('dilate', dilate)
edges = cv2.Canny(dilate, 0, 255)
cv2.imshow('edges', edges)
cts, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cts, key=cv2.contourArea, reverse=True) # 所有轮廓按面积排序
print("轮廓个数:",len(cts[0]))
cnt = cnts[0] # 第 0 个轮廓,面积最大的轮廓,(664, 1, 2)
kk=0
print("shape of max contour:", cnt.shape[0])
for kk in range(len(cts[0]) ):
new_img2 =new_img.copy()
cv2.drawContours(new_img2,cnts, kk,(0,0,255),3)
print(kk,"轮廓面积:",cnts[kk].shape[0])
cv2.imshow("new_img2", new_img2)
cv2.waitKey(0)
# 窗口等待命令 0表示无限等待
cv2.waitKey(0)
cv2.destroyAllWindows()
3、运行结果