如何在同一图像中美白背景和消隐网格

时间:2017-10-02 08:33:27

标签: opencv image-processing

我有这样的图像。我想使用HoughLine检测但图像太暗而无法识别线条。有没有办法可以使背景变白并使网格变黑?我可以应用openCV或python中的算法吗?谢谢

enter image description here

3 个答案:

答案 0 :(得分:2)

您应该尝试一种局部自适应阈值处理方式。 在OpenCV中,这称为cv2.adaptiveThreshold

请参阅此处:http://docs.opencv.org/3.2.0/d7/d4d/tutorial_py_thresholding.html获取python示例。

代码(来自上面的来源:)

import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('sudoku.png',0)
img = cv2.medianBlur(img,5)
ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
            cv2.THRESH_BINARY,11,2)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY,11,2)
titles = ['Original Image', 'Global Thresholding (v = 127)',
            'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in xrange(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

enter image description here

答案 1 :(得分:2)

我首先尝试扩大图像,然后将它放在中间,这样我就得到了背景。使用原始的灰色图像来分配背景,我得到了前景(即网格)。然后做一些其他步骤,我得到这样的结果。

enter image description here

代码如下:

#!/usr/bin/python3
# 2017.10.04 19:37:43 CST

filename = "data/paper.png"
img = cv2.imread(filename)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

## do morph-dilate-op
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
dilated = cv2.morphologyEx(gray, cv2.MORPH_DILATE, kernel)
diff1 = 255 - cv2.subtract(dilated, gray)

## do medianBlur
median = cv2.medianBlur(dilated, 15)
diff2 = 255 - cv2.subtract(median, gray)

## do normalize 
normed = cv2.normalize(diff2,None, 0, 255, cv2.NORM_MINMAX )

## save the result 
dst = np.hstack((gray, normed))
cv2.imwrite("result_paper1.png", dst)
res = np.hstack((gray,dilated, diff1,  median, diff2, normed))
cv2.imwrite("result_paper2.png", res)

enter image description here

答案 2 :(得分:0)

您的图像对比度差,光线不一致。你必须进行一些预处理(这里是c ++代码):

cv::Mat img = cv::imread("E:\\Workspace\\KS\\excercise\\oBwBH.jpg", 0);
cv::Mat workingMat;
cv::GaussianBlur(img, workingMat, cv::Size(101, 101), 31, 31); //high blur to extract background light
img = img - 0.7*work; //adjust light level
cv::normalize(img, img, 0, 255, cv::NORM_MINMAX); \\use whole range
cv::medianBlur(img, img, 5); \\remove noise
cv::Canny(img, work, 100, 200); \\extract lines; you could do hough lines instead since it has canny inside.

结果(从左到右,canny有所有行,在预览中有一些压缩问题): enter image description here