填充已过滤轮廓的内部OpenCV Python

填充已过滤轮廓的内部OpenCV Python,python,numpy,opencv,Python,Numpy,Opencv,我有一个绿色边框的图像,它封装了必须删除的项目。 我已经过滤了图像中唯一的绿色部分,所以我的下一步是用不同的颜色填充过滤后的轮廓内部,然后我将从图像中删除该部分?我很乐意接受任何建议。 这是我的密码 import cv2 import numpy as np import imageio ## Read img = cv2.imread("test.png",-1) img2 = imageio.imread("test.png") ## convert to hsv hsv = cv2.cv

我有一个绿色边框的图像,它封装了必须删除的项目。 我已经过滤了图像中唯一的绿色部分,所以我的下一步是用不同的颜色填充过滤后的轮廓内部,然后我将从图像中删除该部分?我很乐意接受任何建议。 这是我的密码

import cv2
import numpy as np
import imageio

## Read
img = cv2.imread("test.png",-1)
img2 = imageio.imread("test.png")
## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

## mask of green (36,25,25) ~ (86, 255,255)
# mask = cv2.inRange(hsv, (36, 25, 25), (86, 255,255))
mask = cv2.inRange(hsv, (36, 25, 25), (70, 255,255))

## slice the green
imask = mask>0
green = np.zeros_like(img, np.uint8)
green[imask] = img[imask]

green_filter=img[100,100,0]
print(green_filter)


## save 
cv2.imshow('image', green)
cv2.imshow('  ',img)
cv2.waitKey(0)
print(img)
print(green)
我的形象:
我目前看到的图片:

很抱歉这里的sudo代码又快又脏,但这通常是你应该做的

Load in image
Convert to grayscale
Find Contours
Find the index of the contour you want to fill
Use fillConvexPoly to fill the specific contour with the index found above.
这里有一些代码可以指导您正确的方向

#Read in the image
img = cv2.imread("test.png")

#Convert to grayscale
grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#Find contours
contours = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

#Find contour index that you want
#I didn't put code here because I don't know what index would work for your image,
#But you can manually find it by just drawing each contour found one by one until
#You get the contour you want, then use that index to fill it.

#Fill the contour
#NOTE: You will have to adjust this function for your own code
cv2.fillConvexPoly(img, contours[index], lineType=8, shift=0)
=>

我让你来看看这个片段,特别是如果你想删除你的绿色轮廓

如果要反转保留区域,则需要替换:
out[mask1==(255255255)]=img[mask1==255]

作者:
out[mask1==(0,0,0)]=img[mask1==0]

(见下图二)


我只是为了方便在这里进口的

使用
cv2.fillConvexPoly
填充轮廓。请提供示例cv2.DrawConvOutline可以填充轮廓。请参见将厚度设置为-1。
import cv2
import numpy as np
import matplotlib.pyplot as plt
import imageio

## Read
img = cv2.imread("test.png",-1)
## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

mask = cv2.inRange(hsv, (36, 25, 25), (70, 255,255))
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
idx = 0 
mask1 = np.zeros_like(img) 

cv2.drawContours(mask1, contours, idx, (255,255,255), -1) 
out = np.zeros_like(img)
out[mask1 == (255,255,255)] = img[mask1 == 255]

fig, axs = plt.subplots(1, 3, figsize=(16, 4))
for ax, image in zip(axs, ['img', 'mask1', 'out']):
    ax.imshow(eval(image))
    ax.set_title(image)
    ax.grid(True)

plt.show()