【问题标题】:Detect space between text (OpenCV, Python)检测文本之间的空间(OpenCV、Python)
【发布时间】:2018-02-10 13:39:27
【问题描述】:

我有以下代码(实际上只是运行我正在处理的所有项目所需的 4 部分中的一部分..):

#python classify.py --model models/svm.cpickle --image images/image.png

from __future__ import print_function
from sklearn.externals import joblib
from hog import HOG
import dataset
import argparse
import mahotas
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required = True,
    help = "path to where the model will be stored")
ap.add_argument("-i", "--image", required = True,
    help = "path to the image file")
args = vars(ap.parse_args())

model = joblib.load(args["model"])

hog = HOG(orientations = 18, pixelsPerCell = (10, 10),
    cellsPerBlock = (1, 1), transform = True)

image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 30, 150)
(_, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

cnts = sorted([(c, cv2.boundingRect(c)[0]) for c in cnts], key =
    lambda x: x[1])

for (c, _) in cnts:
    (x, y, w, h) = cv2.boundingRect(c)

    if w >= 7 and h >= 20:
        roi = gray[y:y + h, x:x + w]
        thresh = roi.copy()
        T = mahotas.thresholding.otsu(roi)
        thresh[thresh > T] = 255
        thresh = cv2.bitwise_not(thresh)

        thresh = dataset.deskew(thresh, 20)
        thresh = dataset.center_extent(thresh, (20, 20))

        cv2.imshow("thresh", thresh)

        hist = hog.describe(thresh)
        digit = model.predict([hist])[0]
        print("I think that number is: {}".format(digit))

        cv2.rectangle(image, (x, y), (x + w, y + h),
        (0, 255, 0), 1)
        cv2.putText(image, str(digit), (x - 10, y - 10),
        cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2)
        cv2.imshow("image", image)
        cv2.waitKey(0)

此代码正在检测和识别图像中的手写数字。这是一个例子:

假设我不关心准确性识别。

我的问题如下:如您所见,程序获取他可以看到的所有数字并在控制台中打印它们。如果需要,我可以从控制台将它们保存在文本文件中,但我不能告诉程序数字之间有空格。

我想要的是,如果我在文本文件中打印数字,它们应该像图像中那样分开(抱歉,这有点难以解释......)。 这些数字不应该(即使在控制台中)一起打印,但是,在有空格的地方,也打印一个空白区域。

看一下第一张图片。在前 10 位数字之后,图像中有一个空格,控制台中没有。

无论如何,这里有一个完整代码的链接。有 4 个.py 文件和 3 个文件夹。要执行,请在文件夹中打开 CMD 并粘贴命令 python classify.py --model models/svm.cpickle --image images/image.png,其中 image.png 是 images 文件夹中一个文件的名称。

Full Code

提前致谢。在我看来,所有这些工作都必须使用神经网络来完成,但我想首先尝试这种方式。我对此很陌生。

【问题讨论】:

  • 嗨,我想计算图像中数字之间的距离?你能给我一些想法,我该怎么做?

标签: python opencv handwriting-recognition


【解决方案1】:

这是一个入门解决方案。

我暂时没有 Python 中的任何东西,但转换它应该不难,而且 OpenCV 函数调用是相似的,我在下面链接了它们。


TLDR;

找到boundingRects的中心,然后找到它们之间的距离。如果一个矩形在某个阈值之外,您可以假设它是一个空格。


首先,找到边界矩形的中心

vector<Point2f> centres;

for(size_t index = 0; index < contours.size(); ++index)
{
    Moments moment = moments(contours[index]);

    centres.push_back(Point2f(static_cast<float>(moment.m10/moment.m00), static_cast<float>(moment.m01/moment.m00)));
}

(可选但推荐)

您可以绘制中心以直观地了解它们。

for(size_t index = 0; index < centres.size(); ++index)
{
    Scalar colour = Scalar(255, 255, 0);
    circle(frame, circles[index], 2, colour, 2);
}

有了这个,只需遍历它们,确认到下一个的距离在合理阈值内

for(size_t index = 0; index < centres.size(); ++index)
{
    // this is just a sample value. Tweak it around to see which value actually makes sense
    double distance = 0.5;
    Point2f current = centres[index];
    Point2f nextPoint = centres[index + 1];

    // norm calculates the euclidean distance between two points
    if(norm(nextPoint - current) >= distance)
    {
        // TODO: This is a potential space??
    }
}

您可以阅读更多关于 Python 中的 momentsnormcircle drawing 调用的信息。

快乐的编码, 干杯队友:)

【讨论】:

    【解决方案2】:

    使用此代码来完成这项工作。它检测图像中的文本/数字区域。

    import cv2
    
    image = cv2.imread("C:\\Users\\Bob\\Desktop\\PyHw\\images\\test5.png")
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
    _,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
    dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
    _, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours
    
    
    idx =0
    # for each contour found, draw a rectangle around it on original image
    for contour in contours:
    
        idx += 1
    
        # get rectangle bounding contour
        [x,y,w,h] = cv2.boundingRect(contour)
    
        # discard areas that are too large
        if h>300 and w>300:
            continue
    
        # discard areas that are too small
        if h<40 or w<40:
            continue
    
        # draw rectangle around contour on original image
        #cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)
    
        roi = image[y:y + h, x:x + w]
    
        cv2.imwrite('C:\\Users\\Bob\\Desktop\\' + str(idx) + '.jpg', roi)
    
        cv2.imshow('img',roi)
        cv2.waitKey(0)
    

    代码基于其他问题/答案:Extracting text OpenCV

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      相关资源
      最近更新 更多