图像二值化
全局阈值二值化
局部阈值二值化
import cv2 as cv
import numpy as np
#全局阈值
def threshold_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY|cv.THRESH_OTSU)
#ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)#小于127黑色
#ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY_INV)#大于127黑色
#ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_TRUNC)#大于127显示127,小于127黑色
#ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_TOZERO)#小于127为0,显示黑色
print("threshold value %s"%ret)
cv.imshow("binary", binary)
#局部阈值 自适应阈值
def local_threshold(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
#binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 25, 10)
binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10)
cv.imshow("binary", binary)
#自己计算均值进行二值化分割
def custom_threshold(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
h, w = gray.shape[:2]
m = np.reshape(gray, [1, w*h])
print(m)
mean = m.sum() / (w*h)
print("mean : ", mean)
ret, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)
cv.imshow("binary", binary)
if __name__== "__main__":
print("--------- Python OpenCV Tutorial ---------")
src = cv.imread("../opencv-python-img/lena.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
#threshold_demo(src)
#local_threshold(src)
custom_threshold(src)
cv.waitKey(0)
cv.destroyAllWindows()
超大图像二值化
图像大小获取
空白图像过滤
import cv2 as cv
import numpy as np
def big_image_binary(image):
print(image.shape)
cw = 256
ch = 256
h, w = image.shape[:2]
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
#第一种 过滤空白图像实现图像二值化 如果不过滤直接二值化会导致一些噪点显示黑色
for row in range(0, h, ch):
for col in range(0, w, cw):
roi = gray[row:row+ch, col:cw+col]
print(np.std(roi), np.mean(roi))
dev = np.std(roi)
if dev < 15:#空白图像过滤
gray[row:row + ch, col:cw + col] = 255
else:
ret, dst = cv.threshold(roi, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)#效果不好
#dst=cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 127,20)#超大图像使用局部阈值二值化效果好。
gray[row:row + ch, col:cw + col] = dst
#第二种 使用自适应阈值进行二值化 即局部阈值二值化
# for row in range(0, h, ch):
# for col in range(0, w, cw):
# roi = gray[row:row+ch, col:cw+col]
# dst=cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 127,20)#超大图像使用局部阈值二值化效果好。
# gray[row:row + ch, col:cw + col] = dst
# cv.imwrite("../result_binary.png", gray)
if __name__=="__main__":
print("--------- Python OpenCV Tutorial ---------")
src = cv.imread("../opencv-python-img/text1.png")
#cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
#cv.imshow("input image", src)
big_image_binary(src)
cv.waitKey(0)
cv.destroyAllWindows()