使用python检测图像中的文本

时间:2018-08-10 04:20:50

标签: python image-processing

我大约有100多张图片,上面有2种不同的文字。图像如下。一个人被占用,另一个人未被占用。

那么python中有什么方法可以使用一些代码来检测其中的文本来区分这些图像?

如果是,我想识别占用的图像并删除未占用的图像。 既然我是python的新手,有人可以帮助我吗?

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:2)

此答案基于以下假设:您在问题中张贴的图像上只有两个不同的文本。因此,我假设字符数和文本的颜色始终相同(红色的“房间状态:未占用”和“房间状态”已占用)。也就是说,我将尝试一种更简单的方法来区分在这两种不同的类型之间。这些图像包含彼此非常接近的角色,因此我认为将每个字符分开并用OCR进行识别非常困难,我会尝试一种更简单的方法,例如查找区域包含文本并找到文本的纯长度-“未占用”在文本中还有两个字符为“已占用”,因此长度更大。因此,您可以将图像转换为HSV颜色空间并使用{{ 1}}函数提取文本(红色),然后可以使用cv2.inRange()将字符合并到一个轮廓,并使用cv2.morphologyEx()来获取其长度,希望对您有所帮助或至少为您提供一个新的视角关于如何找到您的解决方案的方法。欢呼!

示例代码:

cv2.minAreaRect()

结果:

enter image description here

import cv2
import numpy as np

# Read the image and transform to HSV colorspace.
img = cv2.imread('ocupied.jpg')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Extract the red text.
lower_red = np.array([0,150,50])
upper_red = np.array([40,255,255])
mask_red = cv2.inRange(hsv, lower_red, upper_red)

# Search for contours on the mask.
_, contours, hierarchy = cv2.findContours(mask_red,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

# Create a new mask for further processing.
mask = np.ones(img.shape, np.uint8)*255

# Draw contours on the mask with size and ratio of borders for threshold (to remove other noises from the image).
for cnt in contours:
    size = cv2.contourArea(cnt)
    x,y,w,h = cv2.boundingRect(cnt)
    if 10000 > size > 50 and w*2.5 > h:
        cv2.drawContours(mask, [cnt], -1, (0,0,0), -1)

# Connect neighbour contours and select the biggest one (text).
kernel = np.ones((50,50),np.uint8)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
gray_op = cv2.cvtColor(opening, cv2.COLOR_BGR2GRAY)
_, threshold_op = cv2.threshold(gray_op, 150, 255, cv2.THRESH_BINARY_INV)
_, contours_op, hierarchy_op = cv2.findContours(threshold_op, cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cnt = max(contours_op, key=cv2.contourArea)

# Create rotated rectangle to get the 4 points of the rectangle.
rect = cv2.minAreaRect(cnt)

# Create bounding and calculate the "lenght" of the text.
box = cv2.boxPoints(rect)
a, b, c, d = box = np.int0(box)
bound =[]
bound.append(a)
bound.append(b)
bound.append(c)
bound.append(d)
bound = np.array(bound)
(x1, y1) = (bound[:,0].min(), bound[:,1].min())
(x2, y2) = (bound[:,0].max(), bound[:,1].max())

# Draw the rectangle.
cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),1)

# Identify the room status.   
if x2 - x1 > 200:
    print('unoccupied')
else:
    print('occupied')

# Display the result
cv2.imshow('img', img)

enter image description here

occupied

答案 1 :(得分:0)

使用tesseract OCR Engine和python包装器pytesseract,这只是几行的任务:

public interface AddressRepository extends JpaRepository<Address, Long> {

   Address findByPersonId(Integer person_id);
}

我已经在Windows 7上对此进行了测试。当然,我假设文本在每个图像中都出现在相同的位置(从您的示例看来,确实是这样)。否则,您需要找到更好的裁剪机制。