CV2二值化处理后的图像

问题描述

我正在尝试对图像进行阈值处理并将其转换为文本图像的二值化形式(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,kernel2)

#Step six - Binarization - Thresholding
ret2,threshold = cv.threshold(closing2,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()

善意的建议,我做错了什么,我该如何解决

enter image description here

解决方法

看起来您不是在使用 Otsu 而是使用 0 进行阈值处理,请尝试将 ret2,threshold = cv.threshold(closing2,255,cv.THRESH_BINARY) 更改为 cv.threshold(closing2,cv.THRESH_BINARY+cv.THRESH_OTSU)