从最低点到作物的水平线。

问题描述 投票:0回答:1

我试图用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)

input image我目前的蒙板得到的正是黑框,这将有助于我裁剪图像。

mask image我想将图像裁剪4次(顶部,两侧,底部),方法是将该侧的最低点作一条水平线。我的预期输出是 output image

python opencv
1个回答
2
投票

下面是PythonOpenCV中的一种方法。

  • 读取输入
  • 转换为灰度
  • 阈值
  • 应用形态学打开去掉薄薄的外线,再应用形态学关闭连接左右两半。
  • 找出最大的等高线
  • 获取等值线框
  • 裁剪图像
  • 在输入图像上绘制轮廓
  • 保存结果

输入。

enter image description here

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

阈值的图像。

enter image description here

形态学清洗掩模图像。

enter image description here

输入图像的轮廓:

enter image description here

Cropped image:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.