OpenCV学习笔记-超大图像二值化
在处理的时候,我们可能会碰到一些超大图像,如果直接处理会因为图像的问题造成一些细节被忽略,我们对图像进行切分,分块处理。
同上一篇文章一样,图像二值化有全局和区域的分别,先讨论全局处理的方式:
def big_image_binary(img):
cw = 256 # 分块的步长
ch = 256
h, w = img.shape[:2] # 图像的高宽
gray = cv.cvtColor(img, 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) # 计算像素的标准差
if dev < 15:
# 如果像素的标准差小于某一阈值 我们就理解这个区域的图像变化不大,即黑白区间不明显,我们全部赋值为255
gray[row:row+ch, col:col+cw] = 255
else:
ret, dst = cv.threshold(roi, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
gray[row: row + ch, col: col + cw] = dst
cv.imwrite('img/big_image_binary.png', gray)
局部自适应的处理结果还是一如既往的好,而且操作更简单:
def big_image_binary(img): cw = 256 # 分块的步长 ch = 256 h, w = img.shape[:2] # 图像的高宽 gray = cv.cvtColor(img, 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) # 计算像素的标准差 dst = cv.adaptiveThreshold(roi, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 127, 10) gray[row:row+ch, col:col+ch] = dst cv.imwrite('img/big_image_binary.png', gray)