OpenCV:文本处理和噪声消除

ahm*_*ama 1 python opencv opencv3.0

我想删除包含文本的图像的背景,使其在白色背景上的文本.

图像样本
在此输入图像描述

到目前为止我已经尝试过获取图像的HSV和上下边界,但我找不到可以去除所有背景效果的上下边界

直到现在使用的代码:

import cv2
import numpy as np


# Take each frame
filename = 'img2.png'

img = cv2.imread(filename, 1)

# Convert BGR to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
# Threshold the HSV image to get only blue colors
image_final = cv2.inRange(hsv, lower_blue, upper_blue)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(img,img, mask= mask)
cv2.imshow('frame',img)
cv2.imwrite('mask.png',image_final)


cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法,或者我必须结合多个下边界和上边界来达到我的目标?

Sno*_*ing 6

您可以将图像读取为灰度并设置阈值:

import cv2

img = cv2.imread('img2.png', 0)     # 0 means grayscale
new_img = (img >= 230)*255          # 230 is the threshold, change as desired
cv2.imwrite('mask.png',new_img)
Run Code Online (Sandbox Code Playgroud)

这会将左侧pic转换为右侧:

原版的 产量

由于你的图片都有纯白色字母,你可以选择一个非常高的恒定阈值(0表示黑色,255表示白色),例如230.

编辑

@Ishara Madhawa对使用内核摆脱中心条纹有一个非常好的想法.但是,如果您使用cv2.morphologyEx,则不要更改字母的粗细:

import cv2

img = cv2.imread('img2.png', 0)
new_img = ((img >= 230)*255).astype('uint8')
cv2.imwrite('mask.png',255-new_img)    # 255-... to get black on white

kernel = np.ones((5, 1), np.uint8)    
new_img2 = cv2.morphologyEx(new_img, cv2.MORPH_CLOSE, kernel)
cv2.imwrite('mask2.png',255-new_img2)
Run Code Online (Sandbox Code Playgroud)

没有内核与内核