OpenCV with PHP - 识别文本

时间:2015-12-09 10:39:12

标签: php c++ opencv

我需要识别图像中的文本,然后使用文本裁剪矩形以缩小图像大小

第一步是识别文本,我在这里找到了解决方案

Extracting text OpenCV

但是如何从PHP编译和运行它?我不熟悉C

如何编译代码,以便您可以将参数传递给程序,如exec('opencv_test input.jpg output.jpg')

不是在每个文本块周围绘制矩形,程序应该分析所有文本块并获取应该裁剪图像的两个坐标。然后裁剪图像,将输出文件写入输出目标

#include "stdafx.h"

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;

#define INPUT_FILE              "1.jpg"
#define OUTPUT_FOLDER_PATH      string("")

int _tmain(int argc, _TCHAR* argv[])
{
    Mat large = imread(INPUT_FILE);
    Mat rgb;
    // downsample and use it for processing
    pyrDown(large, rgb);
    Mat small;
    cvtColor(rgb, small, CV_BGR2GRAY);
    // morphological gradient
    Mat grad;
    Mat morphKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
    morphologyEx(small, grad, MORPH_GRADIENT, morphKernel);
    // binarize
    Mat bw;
    threshold(grad, bw, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
    // connect horizontally oriented regions
    Mat connected;
    morphKernel = getStructuringElement(MORPH_RECT, Size(9, 1));
    morphologyEx(bw, connected, MORPH_CLOSE, morphKernel);
    // find contours
    Mat mask = Mat::zeros(bw.size(), CV_8UC1);
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    findContours(connected, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
    // filter contours
    for(int idx = 0; idx >= 0; idx = hierarchy[idx][0])
    {
        Rect rect = boundingRect(contours[idx]);
        Mat maskROI(mask, rect);
        maskROI = Scalar(0, 0, 0);
        // fill the contour
        drawContours(mask, contours, idx, Scalar(255, 255, 255), CV_FILLED);
        // ratio of non-zero pixels in the filled region
        double r = (double)countNonZero(maskROI)/(rect.width*rect.height);

        if (r > .45 /* assume at least 45% of the area is filled if it contains text */
            && 
            (rect.height > 8 && rect.width > 8) /* constraints on region size */
            /* these two conditions alone are not very robust. better to use something 
            like the number of significant peaks in a horizontal projection as a third condition */
            )
        {
            rectangle(rgb, rect, Scalar(0, 255, 0), 2);
        }
    }
    imwrite(OUTPUT_FOLDER_PATH + string("rgb.jpg"), rgb);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

您可以看到GPPK评论。它应该适合你。但是,如果你需要一些快速的方法而没有那么多额外的库和包装器。只需将您的c ++代码编译成可执行文件(例如exe或您平台中的任何内容)并设置参数可能性(将图像路径作为参数传递)。然后,我认为你可以从你的PHP代码中调用它。据我所知,PHP是服务器端的,因此它应该是一项简单的任务。但是,您可以向托管服务或服务器管理员请求许可,以便在服务器上运行exe文件。