pythonopencv二值化_OpenCV——全局二值化,局部二值化与自定义二值化

import cv2 as cv

import numpy as np

from matplotlib import pyplot as plt

def global_binary(image):

gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

plt.hist(gray.ravel(), 256, [0, 256])

plt.show()

"""

src:输入图像

thresh:设置阈值,当进行二值化时,大于该值的为1,小于归0

maxval:maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding types.最大像素值

type:所采用的方法

注意:当设置了自动搜索阈值的方法时(如cv.THRESH_OTSU或者cv.THRESH_TRIANGLE),手动设置的阈值将不生效

"""

thr, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)

print("threshold:{}".format(thr))

cv.imshow("binary", binary)

def local_binary(image):

gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

"""

src:输入图像

maxValue:同上

adaptiveMethod:自适应方法,常用的有ADAPTIVE_THRESH_MEAN_C以及ADAPTIVE_THRESH_GAUSSIAN_C,分别为均值发育高斯均值法

The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries.

thresholdType: must be either #THRESH_BINARY or #THRESH_BINARY_INV,只能是二值化或INV(反二值化)

blockSize:局部二值的参考块大小

C : Constant subtracted from the mean or weighted mean. Normally, it is positive but may be zero or negative as well.

对每个块,结算得到的阈值减去常数C再来进行二值化,用于减小特殊值带来的误差

"""

dst = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10)

cv.imshow("local_binary", dst)

def custom_binary(image):

gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

h, w = gray.shape[:2]

print("h:{}, w:{}".format(h, w))

mean = np.sum(gray.ravel()) / (h*w)

thr, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)

print("threshold:{}".format(thr))

cv.imshow("custom_binary", binary)

src = cv.imread("data/lena.jpg")

cell = cv.imread("data/cell.jpg")

# cv.imshow("original", cell)

# global_binary(cell)

# local_binary(src)

custom_binary(src)

cv.waitKey(0)

cv.destroyAllWindows()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值