处理流程
# -*- coding: utf-8 -*-
# @note : 形态学 开运算 + 圆形内核 处理
# --------------------------------
import cv2 as cv
import numpy as np
def opening_circle(img_bin, kernel_size=10):
# 形态学
kernel = np.zeros((kernel_size, kernel_size), np.uint8)
center_radius = int(kernel_size / 2)
print(center_radius)
cv.circle(kernel, (center_radius, center_radius), center_radius, (1, 1, 1), -1, cv.LINE_AA)
img_open_circle = cv.morphologyEx(img_bin, cv.MORPH_OPEN, kernel)
return img_open_circle
def main():
# 1.打开图片 灰度化
img_src = cv.imread("./wiresFilled.jpg", cv.IMREAD_GRAYSCALE)
img_show = cv.cvtColor(img_src, cv.COLOR_GRAY2BGR)
img_src[0:60, :] = 255
# 2.二值化
ret, img_bin = cv.threshold(img_src, 35, 255, cv.THRESH_BINARY_INV)
# 3.形态学 执行开操作
img_open = opening_circle(img_bin, 20)
# 4.随机颜色
index = 0
color1 = (255, 0, 0)
color2 = (0, 255, 0)
color3 = (0, 0, 255)
color4 = (255, 255, 0)
color5 = (255, 0, 255)
color6 = (0, 255, 255)
colors = [color1, color2, color3, color4, color5, color6]
# 5.连通域筛选
font = cv.FONT_HERSHEY_SIMPLEX
contours, hierarchy = cv.findContours(img_open, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
img_result = img_show.copy()
for cnt in contours:
area = cv.contourArea(cnt)
center, radius = cv.minEnclosingCircle(cnt)
circularity = area / (np.pi * radius * radius)
print('真圆度', circularity, "面积", area)
if circularity > 0.65 and area < 1000:
# 绘制结果
random_color = colors[index % len(colors)]
cv.circle(img_result, (int(center[0]), int(center[1])), int(radius), random_color, -1, cv.LINE_AA)
cv.putText(img_result, ("D=%0.2f" % (radius * 2)),
(int(center[0] - 5), int(center[1] - 25)),
font, 0.45,
(255, 255, 255), 2)
index = index + 1
# 显示图片
cv.imshow('img_bin', img_bin)
cv.imshow('img_open', img_open)
cv.imshow('img_result', img_result)
cv.imwrite('img_bin.jpg', img_bin)
cv.imwrite('img_open.jpg', img_open)
cv.imwrite('img_result.jpg', img_result)
cv.waitKey()
cv.destroyAllWindows()
if __name__ == '__main__':
main()