如何删除图像中除python中的文本以外的所有内容?

2024-09-28 16:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有度量的图像,我需要用python来读取,现在它读取的文本最多,但不是全部,因为有些行挡住了它的去路。我不能使用原始图像,所以我做了一个像我正在使用的图像。你知道吗

def erode(img):
        kernel = np.ones((3,3), np.uint8)
        eroded = cv2.erode(img, kernel, iterations=1)
        gray = cv2.cvtColor(eroded,cv2.COLOR_BGR2GRAY)
        edges = cv2.Canny(gray,50,150,apertureSize = 3)
        minLineLength = 10
        maxLineGap = 1
        lines = cv2.HoughLinesP(edges,1,np.pi/180,120,minLineLength,maxLineGap)
        for line in lines:
            for x1,y1,x2,y2 in line:
                cv2.line(eroded,(x1,y1),(x2,y2),(255,255,255),7)

我尝试过使用OpenCV函数houghLinesP并在这些函数上画一条线,但这并没有删除所有的线,仍然会留下一些点,就像这样: img with dots

我要做的是提供这样的信息作为输入: with lines

得到这样的输出: without lines

我需要删除所有行但不更改 文本是因为我需要保存文本坐标。你知道吗


Tags: 图像文本imgfornplinecv2kernel
1条回答
网友
1楼 · 发布于 2024-09-28 16:18:41

其思想是将文本展开并连接在一起,形成一个单一的轮廓。从这里我们可以找到轮廓和过滤器使用最小阈值面积。如果它通过了这个过滤器,那么我们就有一个想要的文本ROI要保留,我们把这个ROI画到一个遮罩上

enter image description here

import cv2
import numpy as np

image = cv2.imread('3.png')
mask = np.ones(image.shape, dtype=np.uint8) * 255
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=3)

cnts = cv2.findContours(dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area < 5000:
        x,y,w,h = cv2.boundingRect(c)
        mask[y:y+h, x:x+w] = image[y:y+h, x:x+w]

cv2.imshow('thresh', thresh)
cv2.imshow('dilate', dilate)
cv2.imshow('mask', mask)
cv2.waitKey()

相关问题 更多 >