超大图像二值化一般用局部阈值法或者先分块再用全局阈值。
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: col+cw]
print(np.std(roi), np.mean(roi))
dev = np.std(roi)
# 方差小于15的设为255,是空白图像,称为空白图像过滤,可以减少噪声
if dev < 15:
gray[row: row+ch, col: col+cw] = 255
else:
# 局部阈值
# dst = cv.adaptiveThreshold(roi, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 127, 20)
# 全局阈值
ret, dst = cv.threshold(roi, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
gray[row: row + ch, col: col + cw] = dst
print(np.std(dst), np.mean(dst))
cv.imwrite('C:/Users/Y/Pictures/Saved Pictures/result_binary', gray)
src = cv.imread('C:/Users/Y/Pictures/Saved Pictures/demo.png')
# cv.namedWindow('input image', cv.WINDOW_AUTOSIZE)
# cv.imshow('input image', src)
big_image_binary(src)
cv.waitKey(0)
cv.destroyAllWindows()