OpenCV python 轮廓周长筛选
处理图片[source.jpg]
import cv2
import numpy as np
def main():
# 1.导入图片
img_src = cv2.imread("source.jpg")
# 2.灰度化与二值化
img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
# 3.连通域分析
img_contour, contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# 4.计算平均周长
lengths = list()
for i in range(len(contours)):
length = cv2.arcLength(contours[i], True)
lengths.append(length)
print("轮廓%d 的周长: %d" % (i, length))
length_avg = np.average(lengths)
print("轮廓平均周长:", length_avg)
# 5.筛选超过平均周长的轮廓
img_contours = []
for i in range(len(contours)):
img_temp = np.zeros(img_src.shape, np.uint8)
img_contours.append(img_temp)
length = cv2.arcLength(contours[i], True)
if length > length_avg:
print("轮廓 %d 的周长是:%d" % (i, length))
cv2.drawContours(img_contours[i], contours, i, (255, 255, 255), -1)
cv2.imshow("轮廓 %d" % i, img_contours[i])
# 6.显示结果
cv2.imshow("img_src", img_src)
cv2.waitKey()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
结果图片:[contour1.jpg]
结果图片:[contour3.jpg]
运行结果: