1400-张同学

, , ,

# 全局阈值

# 图像二值化 0白色 1黑色
# 全局阈值
def threshold_image(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow("original", gray)
------------------------------------
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 大律法,全局自适应阈值 参数0可改为任意数字但不起作用
print("阈值：%s" % ret)
cv.imshow("OTSU", binary)
-------------------------------------
ret, binary = cv.threshold(gray, 0, 255,
cv.THRESH_BINARY | cv.THRESH_TRIANGLE)  # TRIANGLE法,，全局自适应阈值, 参数0可改为任意数字但不起作用，适用于单个波峰
print("阈值：%s" % ret)
cv.imshow("TRIANGLE", binary)
--------------------------------------
ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_BINARY)  # 自定义阈值为150,大于150的是白色 小于的是黑色
print("阈值：%s" % ret)
cv.imshow("myself", binary)

ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_BINARY_INV)  # 自定义阈值为150,大于150的是黑色 小于的是白色
print("阈值：%s" % ret)
cv.imshow("myself_inv", binary)
--------------------------------------------
ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_TRUNC)  # 截断 大于150的是改为150  小于150的保留
print("阈值：%s" % ret)
cv.imshow("trunc", binary)

ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_TOZERO)  # 截断 小于150的是改为150  大于150的保留
print("阈值：%s" % ret)
cv.imshow("tozero", binary)

threshold_image(src)
cv.waitKey(0)
cv.destroyAllWindows()


# 局部阈值

#局部阈值
def local_image(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow("original", gray)
cv.imshow("local1", binary1)
cv.imshow("local2", binary2)
local_image(src2)
cv.waitKey(0)
cv.destroyAllWindows()


# 求图像均值寻找阈值

# 求出图像均值作为阈值来二值化
def custom_image(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow("original", gray)
h, w = gray.shape[:2]
m = np.reshape(gray, [1, w * h])  # 化为一维数组
mean = m.sum() / (w * h)
print("mean: ", mean)
ret, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)
cv.imshow("binary", binary)

custom_image(src3)
cv.waitKey(0)


Vieu3.3主题

Q Q 登 录