floodFill 反向填充

问题描述 投票:0回答:1

编辑:我只想将船体外部的黑色像素更改为白色,同时保留船体内部的黑色像素。

contours, hierarchy = cv.findContours(morph, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
    mask = np.zeros_like(frame)

    
    for hull in [cv.convexHull(cnt) for cnt in contours]:
        cv.drawContours(mask, [hull], -1, (255, 255, 255), -1)

   
    inverted= cv.bitwise_not(mask)
    k = cv.bitwise_or(mask, inverted)

    return k

example

就像这个例子img一样,我想将船体的外部更改为白色并保留内部的黑色。就像上图一样。但是当我尝试时,它显示所有白色像素,并且船体内部的黑色像素也变白

python opencv image-processing flood-fill
1个回答
0
投票

就像这个例子img一样,我想将船体的外部更改为 白色并保留黑色在里面。就像上图一样。

问题可以解决。

  • 阈值
  • 查找轮廓
  • 填充聚

只有 23 行。

片段:

import cv2;
import numpy as np;
 
# Load the image
img = cv2.imread('hand.jpg')

# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply thresholding
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Fill the contours
for contour in contours:
    cv2.fillPoly(img, pts=[contour], color=(255, 255, 255))

# Display the image
cv2.imshow('Filled Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
© www.soinside.com 2019 - 2024. All rights reserved.