opencv进阶二:阈值分割

adaptiveThreshold

参数

InputArray src
OutputArray dst
double maxValue
int adaptiveMethod,
int thresholdType
int blockSize
double C

原理

为每个像素计算阈值,并二值化(参数thresholdType是二值化类型,参数maxValue是二值化的大灰度值)。
计算阈值有两种方法(参数adaptiveMethod),一是取该像素邻域blockSize*blockSize块的灰度均值,一是根据高斯函数、按照周围像素距目标像素的距离进行加权计算。C是一个偏移值,可正可负。

适用场合

代码以及结果显示

import cv2
from matplotlib.pylab import plt
import numpy as np

# 为了支持plot的中文显示,加上这两句
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

imgColor = cv2.imread("D:/test.jpg", cv2.IMREAD_COLOR)
img = cv2.cvtColor(imgColor, cv2.COLOR_RGB2GRAY)
dst = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 177, -4)
dst, contours, hierarchy = cv2.findContours(dst, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
size = dst.shape
tmp = np.ones((size[0], size[1], 3),np.uint8)*255
cv2.drawContours(tmp, contours, -1, (255, 0, 0), 3)
rect = cv2.boundingRect(contours[0])
fig = plt.figure(figsize=(15, 15))
plt.subplot(221)
plt.title("源图像", size=16)
plt.imshow(imgColor)
plt.subplot(222)
plt.title("灰度图", size=16)
plt.imshow(img, cmap='gray')
plt.subplot(223)
plt.title("自适应阈值结果", size=16)
plt.imshow(dst, cmap='gray')
plt.subplot(224)
plt.title("轮廓图", size=16)
plt.imshow(tmp, cmap='gray')
plt.show()

效果
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值