我想根据图像形状绘制轮廓蒙版(形状)。 我正在使用 opencv-python 版本 4.9.0.80.
所以当我们有这样的图像时。
我们想要这样的输出,里面没有图像。避免灰色背景。
我已经尝试了
cv.convexHull()
但是结果没有达到预期的效果。
我正在尝试这段代码。
import cv2 as cv
import numpy as np
path = '/opt/boundary-remover/SW_test2-01.png'
# path = '/opt/boundary-remover/scaled_2x.png'
# Load image
src = cv.imread(cv.samples.findFile(path))
cv.imwrite('1_original.png', src)
# Convert image to gray and blur it
src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.imwrite('2_gray.png', src_gray)
# Detect edges using Canny
canny_output = cv.Canny(src_gray, 100, 200)
cv.imwrite('3_canny.png', canny_output)
# Find contours
contours, _ = cv.findContours(canny_output, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
# Combine all contours into a single contour
all_contours = np.concatenate(contours)
# Find the convex hull object for the combined contour
hull = cv.convexHull(all_contours)
# Draw the combined contour and its convex hull
drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)
color = (0, 255, 0) # Green color
# cv.drawContours(drawing, [all_contours], 0, color)
# cv.imwrite('4_all_contours.png', drawing)
cv.drawContours(drawing, [hull], 0, color)
cv.imwrite('5_hull.png', drawing)
cv.drawContours(drawing, [hull], -1, color, thickness=cv.FILLED)
cv.imwrite('7_filled.png', drawing)
如果我根据您在这里所说的内容正确理解了您的问题:避免灰色背景,那么这是一种方法:
def replaceGrayWithWhite(im):
imGray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
mask = (imGray>250).astype(np.uint8)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
maskFilled = cv2.drawContours(mask.copy(), contours, -1, 1, -1)
maskFilledInv = cv2.bitwise_not(maskFilled) - 254
'''
Took this from here: https://stackoverflow.com/a/38493075/16815358
'''
foreground = cv2.bitwise_or(im, im, mask=maskFilled)
background = 255*np.ones_like(im)
background = cv2.bitwise_and(background, background, mask=maskFilledInv)
final = cv2.bitwise_or(foreground, background)
return final
导入 numpy 和 opencv,结果如下: