Sebanti
Sebanti

Reputation: 21

How to detect white space in an image in opencv Python?

I have an image:

input.png

I have to detect the white space in between and basically partition it into two parts like this-

expected_output.png

This is what I have coded so far... but it does detect only the black lines and not the middle white region.

import numpy as np
import cv2

img = cv2.imread('12.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
median = cv2.medianBlur(gray,5)
minLineLength = 250
maxLineGap = 100
lines = cv2.HoughLinesP(edges,0.3,np.pi/180,250,minLineLength,maxLineGap)
for line in lines:
    x1,y1,x2,y2 =line[0]
    cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)

cv2.imwrite('newwhite.png',img)

Upvotes: 0

Views: 3972

Answers (1)

I have a simple solution based on mean values along axis. I prefer scikit-image against opencv but you can use cv2.

import matplotlib.pyplot
import numpy as np
import skimage.io
import skimage.color
import skimage.morphology
import scipy.signal

img = skimage.io.imread('12.png')
gray = skimage.color.rgb2gray(img)

# Create some large dark area with the text, 10 is quite big!
eroded = skimage.morphology.erosion(gray, skimage.morphology.square(5))

# Compute mean values along axis 0 or 1
hist = np.mean(eroded, axis=0)

# Search large (here 3% of dimension size) and distant (here 20% of dimension size) peaks
scipy.signal.find_peaks(hist, width=len(hist)*3//100, distance=len(hist)*20//100)

Then each peak represents a white line in one dimension of your image

Upvotes: 1

Related Questions