OpenCV python 形态学 圆形开运算

在这里插入图片描述
处理流程

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

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

廷益--飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值