如何使用OpenCV从图像中删除内部轮廓和边框轮廓?

时间:2019-08-09 10:46:44

标签: python opencv image-processing opencv-contour

我使用OpenCv中的findContours()函数绘制轮廓线。 我想从中消除边框和内部轮廓

enter image description here

这是我用来绘制轮廓的代码

import numpy as np
import cv2 as cv

im = cv.imread('0.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
#ret, thresh = cv.threshold(imgray, 127, 255, 0)
blur = cv.GaussianBlur(imgray,(5,5),0)
ret3,thresh = cv.threshold(blur,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, 
cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(im, contours, -1 ,(0,0,255), 1)
cv.imwrite('image.jpg',im)

1 个答案:

答案 0 :(得分:1)

函数findContours检测非零像素周围的轮廓。在您的示例中,背景为白色,而您要检测的对象为黑色,因此轮廓是在背景周围检测到的,而不是您期望的对象。您可以简单地使用cv2.bitwise_not函数对图像进行否定以使背景变黑,假设背景颜色为255。

现在,当您正确定义了对象和背景时,可以将标志CV_RETR_EXTERNAL用于findContours函数,以仅检测外部轮廓。请注意,如果背景为白色,则此标志将不起作用,因为所有这些字母都是图像边框上这个大轮廓的内部轮廓。

这是固定代码:

import numpy as np
import cv2 as cv

im = cv.imread('0.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
blur = cv.GaussianBlur(imgray, (5, 5), 0)
ret3, thresh = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
thresh_inverse = cv.bitwise_not(imgray)
contours, hierarchy = cv.findContours(thresh_inverse, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(im, contours, -1, (0, 0, 255), 1)
cv.imwrite('image.jpg', im)

更新

作为使用cv2.bitwise_not的替代方法,您可以更改阈值函数,该函数将255的值分配给深色字母而不是背景:

ret3, thresh = cv.threshold(blur, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)