这是我正在使用的示例图像:
我基本上是在尝试通过删除非图轮廓来从结构相似的工程图中自动提取图,但是由于该表没有连续流动的数据,因此它将其视为另一个图并将其保留在裁剪区域内。
码:
import cv2
import numpy as np
image = cv2.imread("pin1.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]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 10))
dilate = cv2.dilate(thresh, kernel, iterations=2)
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x, y, w, h = cv2.boundingRect(c)
area = cv2.contourArea(c)
if w/h > 2 and area > 10000:
cv2.drawContours(dilate, [c], -1, (0, 0, 0), -1)
boxes = []
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x, y, w, h = cv2.boundingRect(c)
boxes.append([x, y, x+w, y+h])
boxes = np.asarray(boxes)
x = np.min(boxes[:, 0])
y = np.min(boxes[:, 1])
w = np.max(boxes[:, 2]) - x
h = np.max(boxes[:, 3]) - y
cv2.rectangle(image, (x, y), (x + w, y + h), (36, 255, 12), 2)
cropped_region = original[y:y+h, x:x+w]
cv2.namedWindow("original", cv2.WINDOW_NORMAL)
cv2.namedWindow("thresh", cv2.WINDOW_NORMAL)
cv2.namedWindow("dilate", cv2.WINDOW_NORMAL)
cv2.namedWindow("cropped_region", cv2.WINDOW_NORMAL)
cv2.imshow('original', original)
cv2.imshow('thresh', thresh)
cv2.imshow('dilate', dilate)
cv2.imshow('cropped_region', cropped_region)
cv2.imwrite("Cropped1.png", cropped_region)
cv2.waitKey()
我不知道如何进行轮廓过滤器搜索表而不是文本行,因为我是新手。任何帮助,将不胜感激。编辑:这是我的Expected Output
最佳答案
如果图纸的比例是标准比例:
您得到这样的结果:
#=======================
# import libraries
#=======================
import numpy as np
import cv2
import matplotlib.pyplot as plt
#=======================
# Read Image
#=======================
img = cv2.imread('1.png',0)
#=======================
# Get internal max shape
#=======================
x00 = int(0.01*img.shape[1])
x01 = int(0.75*img.shape[1])
y00 = int(0.01*img.shape[0])
y01 = int(0.875*img.shape[0])
#=======================
# Crop Internal shape
#=======================
img2 = img[y00:y01,x00:x01]
#==========================
# get internal shape coords
#==========================
Y,X = np.where(img2 == 0)
#============================
# Get internal shape borders
#============================
x1 = X.min()
x2 = X.max()
y1 = Y.min()
y2 = Y.max()
# Tolerance arround the shape
tol = 100
#=======================
# Crop inner shape
#=======================
img3 = img2[y1-tol:y2+tol,x1-tol:x2+tol]
#=======================
# Visualize the Results
#=======================
plt.figure(num='Plot')
plt.subplot(121)
plt.imshow(img, cmap='gray')
plt.title('Original')
plt.subplot(122)
plt.imshow(img3, cmap='gray')
plt.title('Result')
plt.show()
关于python - 如何自动从工程图图像中裁剪图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64572525/