python实现超大图像的二值化方法

一,分块处理超大图像的二值化问题

  (1) 全局阈值处理
  (2) 局部阈值

二,空白区域过滤

三,先缩放进行二值化,然后还原大小

 

np.mean() 返回数组元素的平均值

np.std() 返回数组元素的标准差

一,分块处理超大图像的二值化问题

 (1) 全局阈值处理 

 (2) 局部阈值

 1 import cv2 as cv
 2 import numpy as np
 3 
 4 """
 5 def big_image_binary(image):
 6     print(image.shape)  #(4208, 2368, 3)  #超大图像,屏幕无法显示完整
 7     cw,ch = 256,256
 8     h,w = image.shape[:2]
 9     gray = cv.cvtColor(image,cv.COLOR_RGB2GRAY)   #要二值化图像,要先进行灰度化处理
10     for row in range(0,h,ch):
11         for col in range(0,w,cw):
12             roi = gray[row:row+ch,col:col+cw]   #获取分块
13             #全局阈值
14             # ret,binary = cv.threshold(roi,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
15            
16 
17             #局部阈值  
18             binary = cv.adaptiveThreshold(roi,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,127,20)  
19             gray[row:row + ch, col:col + cw] = binary  #分块覆盖
20             print(np.std(binary),np.mean(binary))
21 
22     cv.imwrite("binary2.jpg",gray)

 二,空白区域过滤

 1 #空白区域过滤
 2 def big_image_binary(image):
 3     print(image.shape)
 4     # 分成小块,每一块的宽高
 5     cw = 256
 6     ch = 256
 7     #整个图像的宽高
 8     h, w = image.shape[:2]
 9     gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
10     #步长 ch cw
11     for row in range(0, h, ch):
12         for col in range(0, w, cw):
13             #获取分块(感兴趣区域)
14             roi = gray[row:row+ch, col:cw+col]
15             print(np.std(roi), np.mean(roi))
16             dev = np.std(roi)
17             if dev < 15:
18                 gray[row:row + ch, col:cw + col] = 255   #dev < 15的让它变白
19             else:
20                 ret, dst = cv.threshold(roi, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
21                 gray[row:row + ch, col:cw + col] = dst
22     cv.imwrite("D:/vcprojects/result_binary.png", gray)
23 
24 
25 print("--------- Python OpenCV Tutorial ---------")
26 src = cv.imread("D:/vcprojects/images/red_text2.png")
27 #cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
28 #cv.imshow("input image", src)
29 big_image_binary(src)
30 cv.waitKey(0)
31 
32 cv.destroyAllWindows()
33 big_image_binary(src)
34 cv.waitKey(0)
35 
36 cv.destroyAllWindows()

 参考:

https://blog.csdn.net/weixin_41722450/article/details/104265595

posted @ 2020-08-30 20:17  山那边不是山  阅读(581)  评论(0编辑  收藏  举报