要隔离文本,一种方法是获取所需 ROI 的边界框坐标,然后将该 ROI 蒙版到空白图像上。主要思想是:
- 将图像转换为灰度
- 阈值图像
- 放大图像以将文本连接为单个边界框
- 查找轮廓并过滤使用的轮廓区域以查找 ROI
- 将 ROI 放置在遮罩上
阈值图像(左)然后扩大连接文本(右)
您可以使用 cv2.boundingRect() 找到轮廓,然后一旦您有了 ROI,您就可以将这个 ROI 放置在蒙版上
mask = np.zeros(image.shape, dtype='uint8')
mask.fill(255)
mask[y:y+h, x:x+w] = original_image[y:y+h, x:x+w]
找到轮廓然后过滤 ROI(左),最终结果(右)
根据您的图像大小,您可能需要调整轮廓区域的过滤器。
import cv2
import numpy as np
original_image = cv2.imread('1.png')
image = original_image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
dilate = cv2.dilate(thresh, kernel, iterations=5)
# Find contours
cnts = cv2.findContours(dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
# Create a blank white mask
mask = np.zeros(image.shape, dtype='uint8')
mask.fill(255)
# Iterate thorugh contours and filter for ROI
for c in cnts:
area = cv2.contourArea(c)
if area < 15000:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
mask[y:y+h, x:x+w] = original_image[y:y+h, x:x+w]
cv2.imshow("mask", mask)
cv2.imshow("image", image)
cv2.imshow("dilate", dilate)
cv2.imshow("thresh", thresh)
cv2.imshow("result", image)
cv2.waitKey(0)