CV2 二值化处理图像

CV2 binarizing processed image

我正在尝试对图像进行阈值处理并将其转换为文本图像的二值化形式(1- 前景和 0- 背景)。 我已经进行了几个图像处理步骤,在最后阶段我对图像使用了二进制阈值。但是,它会生成完全白色(所有像素值为 255)的图像。

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
#Load image file
img = cv.imread('img/Merani.png')

#Define Structuring elements
kernel = np.ones((1,20),np.uint8) #Kernel for Opening and Closing
kernel2 = np.ones((5,5),np.uint8) #Kernel for secong Closing

#Step One Image Smoothing
gauss = cv.GaussianBlur(img,(3,3),0) #Image smoothing

#Step Two Opening
opening = cv.morphologyEx(gauss, cv.MORPH_OPEN, kernel)
#Step three Closing
closing = cv.morphologyEx(gauss, cv.MORPH_CLOSE, kernel)
#Step four gradients
gradient = cv.morphologyEx(gauss, cv.MORPH_GRADIENT, kernel)
difference = closing -opening
#Step five second closing
closing2 = cv.morphologyEx(gradient, cv.MORPH_CLOSE, kernel2)

#Step six - Binarization - Thresholding
ret2,threshold = cv.threshold(closing2,0,255,cv.THRESH_BINARY)

#Plotting Results
plt.subplot(421),plt.imshow(img),plt.title('Original Image')
plt.xticks([]), plt.yticks([])
plt.subplot(422),plt.imshow(gauss),plt.title('Gaussian smoothing')
plt.xticks([]), plt.yticks([])

plt.subplot(423),plt.imshow(opening),plt.title('MM Opening')
plt.xticks([]), plt.yticks([])
plt.subplot(424),plt.imshow(closing),plt.title('MM Closing')
plt.xticks([]), plt.yticks([])

plt.subplot(425),plt.imshow(difference),plt.title('Difference')
plt.xticks([]), plt.yticks([])
plt.subplot(426),plt.imshow(gradient),plt.title('MM Gradient')
plt.xticks([]), plt.yticks([])

plt.subplot(427),plt.imshow(closing2),plt.title('Second Closing')
plt.xticks([]), plt.yticks([])
plt.subplot(428),plt.imshow(threshold),plt.title('Threshold - OTSU')

plt.xticks([]), plt.yticks([])
plt.show()

请指教,我做错了什么,我该如何解决。

您似乎没有使用 Otsu,只是将阈值设置为 0,请尝试将 ret2,threshold = cv.threshold(closing2,0,255,cv.THRESH_BINARY) 更改为 cv.threshold(closing2,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)