opencv 二值化、自适应二值化、Otsu’s 二值化

普通二值化

import cv2


def cv_show(neme, img):
    # cv2.namedWindow(neme, cv2.WINDOW_NORMAL)
    cv2.imshow(neme, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


img = cv2.imread('1.png')
# 灰度化
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 二值化
# 大于127=0,小于127=255
ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 大于127=255,小于127=0
ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)

# 大于127=127,否则不变
ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)

# 小于127=0,否则不变
ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)

# 大于127=0,否则不变
ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)

cv_show("s", img)
cv_show("s", thresh1)
cv_show("s", thresh2)
cv_show("s", thresh3)
cv_show("s", thresh4)
cv_show("s", thresh5)

自适应二值化

img = cv2.imread('1.png', 0)  
# 中值滤波
img = cv2.medianBlur(img, 5)
ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 自适应阈值 二值化
# 11 为 Block size, 2 为 C 值
# cv2.ADPTIVE_THRESH_MEAN_C 阈值取自相邻区域的平均值
th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
# v2.ADPTIVE_THRESH_GAUSSIAN_C:阈值取值相邻区域的加权和,权重为一个高斯窗口。
th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

cv_show("s", th2)
cv_show("s", th3)

Otsu’s 二值化

# Otsu’s 二值化
img = cv2.imread('1.png', 0)
# 两种写法
# 1、可以在后面加[1],代表直接返回第二个
# 2、直接接2个返回值

thresh, _ = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
print(_)
print("="*100)
print(thresh1)
cv_show("s", _)
cv_show("s", thresh1)

调节阈值小工具(普通二值化) 有时候不靠谱,先自己用原本的方法验证一遍吧

import cv2


def nothing(x):
    pass


img = cv2.imread('../1.jpeg', 0)
# 截图
# img = img[0:579, 315:704]

cv2.namedWindow('res')

cv2.createTrackbar('max', 'res', 127, 255, nothing)
cv2.createTrackbar('min', 'res', 127, 255, nothing)

# img = cv2.resize(img, (640, 360))
maxVal = 200
minVal = 100

while True:
    key = cv2.waitKey(1) & 0xff
    if key == ord(" "):
        break
    maxVal = cv2.getTrackbarPos('min', 'res')
    minVal = cv2.getTrackbarPos('max', 'res')

    ret, edge = cv2.threshold(img, minVal, maxVal, cv2.THRESH_BINARY)
    cv2.imshow('res', edge)
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

默执_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值