如何使用opencv检测在白色背景上的白皮书

时间:2018-07-11 08:22:15

标签: android opencv ocr object-detection

我使用OpenCV库检测书中的白页。在深色表面上找到4个角,但是白色背景仅找到3个角。如何找到在白色背景上找到四个角或阅读页面的方法?

或者您能建议我可以在Opencv之外使用的另一个库吗?

我使用以下代码查找轮廓。

    Mat grayImage = new Mat(imageMat.size(), CvType.CV_8UC4);
    Mat cannedImage = new Mat(imageMat.size(), CvType.CV_8UC4);
    Mat dilate = new Mat(imageMat.size(), CvType.CV_8UC4);

    Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGBA2GRAY);
    Imgproc.GaussianBlur(imageMat, imageMat, new Size(3, 3), 0);
    Imgproc.cvtColor(imageMat, grayImage, Imgproc.COLOR_BGR2GRAY);
    Imgproc.GaussianBlur(grayImage, grayImage, new Size(5.0, 5.0), 0.0);
    Imgproc.threshold(grayImage, grayImage, 20.0, 255.0, Imgproc.THRESH_TRIANGLE);
    Imgproc.Canny(grayImage, cannedImage, 75.0, 200.0);
    Imgproc.dilate(cannedImage, dilate, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(10.0, 10.0)));

如何更改此代码?

我用这些照片测试代码。

enter image description here

enter image description here

谢谢, 祝你有美好的一天。

1 个答案:

答案 0 :(得分:2)

import numpy as np
import cv2


if __name__ == '__main__':
    image = cv2.imread('image.jpg', cv2.IMREAD_UNCHANGED);

    lab = cv2.cvtColor(image, cv2.COLOR_BGR2Lab)
    lab = cv2.split(lab)

    binary = cv2.adaptiveThreshold(lab[2], 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 7, 7)

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
    binary = cv2.morphologyEx(binary, cv2.MORPH_DILATE, kernel,iterations=3)

    contours = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[1]

    points = np.concatenate(contours)

    (x,y,w,h) = cv2.boundingRect(points)

    cv2.rectangle(image, (x,y), (x+w,y+h), (0,0,255))

    cv2.imshow('image', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

result

result2