如何使用python从工程图图像中提取底部?

BAL*_*AJI 5 python ocr opencv image image-processing

我的输入图像

我的输入图像

提取高亮部分

提取高亮部分

我想要的输出

我想要的输出

请有人帮助并给我一个建议。我的图像看起来像这样。这只是示例之一。我需要裁剪底部模板部分并进行 OCR。我附上了我想要的输出图片。请看一看。如何使用python实现它?

PS:纸张大小会有所不同,模板可能会错位。但主要是在左下角

nat*_*ncy 7

这是一种可能的方法:

  1. 获取二值图像。我们转换为灰度、高斯模糊,然后是大津阈值

  2. 填充潜在的轮廓。我们迭代轮廓并使用轮廓近似进行过滤以确定它们是否是矩形。

  3. 执行形态学操作。我们使用矩形内核进行变形开放以删除非矩形轮廓。

  4. 过滤并提取所需的轮廓。使用轮廓近似、纵横比和轮廓面积查找轮廓并进行过滤,以隔离所需的轮廓。然后使用 Numpy 切片进行提取。


  1. 二值图像

在此输入图像描述

  1. 填充轮廓

在此输入图像描述

  1. 去除非矩形轮廓的形态学操作

在此输入图像描述

  1. 所需轮廓以绿色突出显示

在此输入图像描述

提取的投资回报率

在此输入图像描述

代码

import cv2

# Grayscale, blur, and threshold
image = cv2.imread('1.png')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Fill in potential contours
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.05 * peri, True)
    if len(approx) == 4:
        cv2.drawContours(thresh, [c], -1, (255,255,255), -1)

# Remove non rectangular contours
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (40,10))
close = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)

# Filtered for desired contour
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.05 * peri, True)
    x,y,w,h = cv2.boundingRect(approx)
    aspect_ratio = w / float(h)
    area = cv2.contourArea(approx)
    if len(approx) == 4 and w > h and aspect_ratio > 2.75 and area > 45000:
        cv2.drawContours(image, [c], -1, (36,255,12), -1)
        ROI = original[y:y+h, x:x+w]

cv2.imwrite('image.png', image)
cv2.imwrite('ROI.png', ROI)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)