python opencv图片二值化后取出图片中心区域的轮廓

python opencv图片二值化后取出图片中心区域的轮廓

1.导入必要的库:

import cv2
import numpy as np

2.读取图片并将其转为灰度图像:

image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

3.对灰度图像进行二值化处理:

ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

4.找到轮廓并筛选出中心区域的轮廓:

# 使用 cv2.findContours() 找到图像的轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
center_contours = []
# 对于每一个轮廓,使用 cv2.moments() 计算矩
for contour in contours:
    M = cv2.moments(contour)
     # 使用 M["m00"] 访问第 0 阶矩
    # 使用 M["m10"] 访问第 1 阶矩
    # 使用 M["m01"] 访问第 2 阶矩
    # 以此类推
    if M['m00'] > 0:
        cX = int(M['m10'] / M['m00'])
        cY = int(M['m01'] / M['m00'])
        # 计算中心轮廓
        if cX > 0.25 * image.shape[1] and cX < 0.75 * image.shape[1] and cY > 0.25 * image.shape[0] and cY < 0.75 * image.shape[0]:
            center_contours.append(contour)

5.在原始图像上绘制中心区域的轮廓:

cv2.drawContours(image, center_contours, -1, (0, 255, 0), 3)

这里将轮廓绘制为绿色。

6.显示结果:

cv2.imshow("Contours", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

车载testing

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

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

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

打赏作者

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

抵扣说明:

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

余额充值