移除图像的轮廓

2024-04-29 03:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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  ? 

Tags: path方法图像imagethresholdcv2color轮廓
1条回答
网友
1楼 · 发布于 2024-04-29 03:33:43

按图像大小创建空掩码:
mask = np.zeros(image.shape[:2], dtype=image.dtype)

接下来绘制要保留在该蒙版上的所有轮廓/边界矩形:
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() 

相关问题 更多 >