(一)分块处理超大图像的二值化问题
python实现,包括全局阈值和局部阈值方法
import cv2 import numpy as np __author__ = "boboa" def big_image_demo(image): print(image.shape) # 分成小块,宽高 cw = 256 ch = 256 h, w = image.shape[:2] gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) for row in range(0, h, ch): for col in range(0, w, cw): roi = gray[row:row + ch, col:col + cw] # 获取分块 # ret, dst = cv2.threshold(roi,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU) #全局阈值 dst = cv2.adaptiveThreshold(roi, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 127, 20) # 局部阈值 gray[row:row + ch, col:col + cw] = dst # 分块覆盖 print(np.std(dst), np.mean(dst)) cv2.imwrite("image/result_bigimage.jpg", gray) if __name__ == "__main__": img = cv2.imread("image/big.jpg") cv2.namedWindow("input image", cv2.WINDOW_AUTOSIZE) cv2.imshow("input image", img) big_image_demo(img) cv2.waitKey(0) cv2.destroyAllWindows()
原图
全局阈值效果较差
局部阈值效果较好
(二)图像ROI与空白区域过滤
python实现
import cv2 import numpy as np __author__ = "boboa" def big_image_demo(image): print(image.shape) # 分成小块,宽高 cw = 256 ch = 256 h, w = image.shape[:2] gray = cv2.cvtColor(image, cv2.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 = cv2.threshold(roi, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) gray[row: row + ch, col: col + cw] = dst cv2.imwrite("image/result_bigimage.jpg", gray) if __name__ == "__main__": img = cv2.imread("image/big.jpg") cv2.namedWindow("input image", cv2.WINDOW_AUTOSIZE) cv2.imshow("input image", img) big_image_demo(img) cv2.waitKey(0) cv2.destroyAllWindows()
运行结果,可以看出过滤之后,效果有所改善