Search code examples
image-processingopencvimage-thresholdingpython

CV2 binarizing processed image


I am trying to threshold the image and convert it to binarize form (1- foreground and 0- background) of a text image. I have conducted several image processing steps and on final stage I use binary threshold on image. However, it produces completely white (all pixels values are 255) image.

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()

Kindly advice, what i am doing wrong and how can i fix it.

enter image description here


Solution

  • It doesn't look like you are using Otsu but just thresholding with 0, try changing ret2,threshold = cv.threshold(closing2,0,255,cv.THRESH_BINARY) to cv.threshold(closing2,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)