【发布时间】:2020-05-26 07:05:13
【问题描述】:
我在删除不需要的轮廓时遇到了一些问题。
检测到轮廓的图像:
我不想要如下图所示的轮廓(蓝色标记的区域):
但我似乎无法摆脱它们。 我的代码:
img = cv2.imread(img_path)
edges = cv2.Canny(img, 240, 240)
#cv2.imshow('', edges)
thresh = cv2.threshold(edges,150, 255,cv2.THRESH_BINARY_INV)[1]
cnts, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Show and Write Threshold Image
#cv2.imshow('thresh', thresh)
#cv2.imwrite('Thresholded_labeled_image.jpg', thresh)
# Find and Draw Contours
contours, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
img_contours = cv2.drawContours(thresh, contours, -1, (0,255,0), 3)
cv2.imshow('contours', img_contours)
# Remove Noise
kernel = np.ones((5,5),np.float32)/25
dst = cv2.filter2D(img_contours,-1,kernel)
plt.subplot(121),plt.imshow(img_contours),plt.title('Image_Contours')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(dst),plt.title('Averaging')
plt.xticks([]), plt.yticks([])
plt.show()
我尝试了形态学:
kernel = np.ones((5,5),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
cv2.imshow('closing', closing)
我尝试更改内核的大小,但它仍然不起作用。我仍然看到那些不需要的轮廓。
有什么我可以尝试的吗?
编辑 1:使用 boundingRect
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4,2))
dilate = cv2.dilate(thresh, kernel, iterations=2)
# Find contours, highlight text areas, and extract ROIs
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
ROI_number = 0
ROI_images = []
for c in cnts:
area = cv2.contourArea(c)
print("Area is: ", area)
x,y,w,h = cv2.boundingRect(c)
print("Height: ", h)
if area > 100 and 0<h<300:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 3)
ROI = img[y:y+h, x:x+w]
# cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
ROI_number += 1
ROI_images.append(ROI)
输出:
【问题讨论】:
-
然后尝试通过长度和面积属性过滤轮廓。
-
对不起,你是什么意思?我以前没有这样做过。
-
是的,您也可以通过使用
cv2.boundingrect()获得x,y,w,h,只需创建您自己的阈值条件。 -
这是您的过滤方式:stackoverflow.com/a/61358554/6660373
-
我投的是 boundinrect 而不是轮廓长度