gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:33 26 4
gpt4 key购买 nike

我的输入图像

My input image

提取高亮部分

To extract highlighted part

我想要的输出

My desired output

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

PS:板材尺寸会有所不同,模板有可能错位。但大部分会在左下角

最佳答案

这是一个可能的方法:

  1. 获得二值图像。我们转换为灰度,高斯模糊,然后是 Otsu 的阈值

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

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

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


  1. 二进制图像

enter image description here

  1. 填充轮廓

enter image description here

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

enter image description here

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

enter image description here

提取的投资返回率

enter image description here

代码

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()

关于python - 如何使用python从工程图图像中提取底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com