从图像中去除轮廓

时间:2019-02-01 18:50:16

标签: python opencv image-processing

我有要从图像中删除的轮廓,什么是最好的方法?

image = cv2.imread(path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
retr , thresh = cv2.threshold(gray_image, 190, 255, cv2.THRESH_BINARY_INV)
contours, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    if cv2.contourArea(c) > 20:
        x, y, w, h = cv2.boundingRect(c)
         ##### how to continue from here  ? 

1 个答案:

答案 0 :(得分:0)

创建一个与图像大小相同的空蒙版:
mask = np.zeros(image.shape[:2], dtype=image.dtype)

接下来,在此蒙版上绘制要保留的所有轮廓/ boundingrect:
cv2.drawContours(mask, [cnt], 0, (255), -1)
或者,也可以代替吸引你的想的轮廓和逆掩模(这可能是更适合在某些情况下):
mask= cv2.bitwise_not(mask)

在主图像上使用遮罩: result = cv2.bitwise_and(image,image, mask= mask)

编辑:在评论后添加了代码。

我以为这是关于另一个问题的图像,因此我将代码应用于该图像。

结果:

enter image description here

代码:

import numpy as np 
import cv2
# load image
image = cv2.imread('image.png')
# create grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# perform threshold
retr , thresh = cv2.threshold(gray_image, 190, 255, cv2.THRESH_BINARY_INV)
# find contours
ret, contours, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# create emtpy mask
mask = np.zeros(image.shape[:2], dtype=image.dtype)

# draw all contours larger than 20 on the mask
for c in contours:
    if cv2.contourArea(c) > 20:
        x, y, w, h = cv2.boundingRect(c)
        cv2.drawContours(mask, [c], 0, (255), -1)

# apply the mask to the original image
result = cv2.bitwise_and(image,image, mask= mask)

#show image
cv2.imshow("Result", result)
cv2.imshow("Image", image)

cv2.waitKey(0)
cv2.destroyAllWindows()