我试图用opencv去除图纸中的额外间距。我的目标是去除封闭图形中的额外部分。
import cv2
import numpy as np
name = '006.png'
img=cv2.imread(name)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = 255 - gray
thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)[1]
kernel = np.ones((75,75), np.uint8)
mask = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
#cv2.imwrite('mask.png',mask)
下面是PythonOpenCV中的一种方法。
输入。
import cv2
import numpy as np
# read image
img = cv2.imread('006.png')
hh, ww = img.shape[:2]
# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# invert gray image
gray = 255 - gray
# threshold
thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)[1]
# apply close and open morphology
kernel = np.ones((3,3), np.uint8)
mask = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
# get largest contour
contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
x,y,w,h = cv2.boundingRect(big_contour)
# draw contour on input
contour_img = img.copy()
cv2.drawContours(contour_img,[big_contour],0,(0,0,255),3)
# crop to bounding rectangle
crop = img[y:y+h, x:x+w]
# save cropped image
cv2.imwrite('006_thresh.png',thresh)
cv2.imwrite('006_mask.png',mask)
cv2.imwrite('006_contour.png',contour_img)
cv2.imwrite('006_cropped.png',crop)
# show the images
cv2.imshow("THRESH", thresh)
cv2.imshow("MASK", mask)
cv2.imshow("CONTOUR", contour_img)
cv2.imshow("CROP", crop)
cv2.waitKey(0)
cv2.destroyAllWindows()
阈值的图像。
形态学清洗掩模图像。
输入图像的轮廓:
Cropped image: