如何使用open去除图像中的其他噪声

2024-04-26 14:09:11 发布

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

在这里,我使用下面的脚本来去除图像附近的黑点,并通过上面的数字删除线,但它去除了噪音,但不正确。在

def get_string(img_path):
    # Read image with opencv
    img = cv2.imread(img_path)

    # Convert to gray
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply dilation and erosion to remove some noise
    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=12)
    img = cv2.erode(img, kernel, iterations=12)

    # Write image after removed noise
    cv2.imwrite(src_path + "removed_noise.png", img)

    #  Apply threshold to get image with only black and white
    img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)

    # Write the image after apply opencv to do some ...
    cv2.imwrite(src_path + "thres.png", img)

    # Recognize text with tesseract for python
    result = pytesseract.image_to_string(Image.open(src_path + "vertical_final.jpg"))

    # Remove template file
    #os.remove(temp)

    return result

但它不能正常工作。在

输入图像:

img

输出图片:-在

img

我需要有人帮我摆脱这些问题,这是高度赞赏。 来源代码:-在

^{pr2}$

Tags: andtopath图像imagesrcimgget
1条回答
网友
1楼 · 发布于 2024-04-26 14:09:11

你在哪里

kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=12)

使用1x1结构元素(SE)进行12次膨胀。除非OpenCV对这样一个SE做了一些特殊的处理,否则这些代码根本不会改变您的图像。在

您应该创建一个更大的SE:

^{pr2}$

这将首先扩大,然后侵蚀结果。这样做的结果是小的(薄的)黑色区域消失了。这些是SE不适合的区域。这和

img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)

要删除长线,您需要应用一个拉长的SE结束:

kernel = np.ones((1, 30), np.uint8)
line = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)

这只留下水平线。img和{}的区别是没有行的文本。在

如果您认为imgline和{},那么{}将是{}。但是,仍然存在一个小问题:img背景为白色(255),前景为黑色。所以说真的,它是img = 255 - text - line,而你在上面发现的line图像实际上是{},因为它也有白色的背景。所以直接取差分并不能产生理想的效果。在

解决方法是先反转图像:

img = 255 - img;
line = 255 - line;
text = img - line;

相关问题 更多 >