由于给出的图片已经是二值化的图片了,所以只需在白色区域叠加一个被线条填充的图片即可。如果没有二值化的图片,需要使用cv2.findContours()函数获取掩膜,然后叠加掩膜和背景。以下为代码及详细步骤。1.生成背景图片获取输入图像的大小,生成相同大小的空白图片,然后使用cv2.line函数做直线填充。2.叠加两幅图片两幅图片直接相加并减去255参考程序:import cv2 import numpy as np pic = cv2.imread("try.jpeg") # 绘制背景 width = pic.shape[1] height = pic.shape[0] backGround = np.zeros((height, width, 3), np.uint8) + 255 drawWidth = 0 while drawWidth < width: backGround = cv2.line(backGround, (drawWidth, 0), (drawWidth, height), (0, 0, 255), 1) drawWidth += 10 # 生成掩膜 img = pic gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转为灰度图 ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 转为二值图 contours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # 寻找轮廓 mask = np.zeros(img.shape, np.uint8) # 生成黑背景,即全为0 mask = cv2.drawContours(mask, contours, -1, (255, 255, 255), -1) # 绘制轮廓,形成掩膜 cv2.imshow("mask", mask) # 显示掩膜 cv2.waitKey(0) cv2.imshow('image', backGround) # 显示背景 cv2.waitKey(0) # 叠加 cv2.imshow('image', backGround + mask - 255) cv2.waitKey(0)参考链接:利用CV2.FINDCONTOURS()进行物体轮廓检测
1.生成背景图片
2.叠加两幅图片
参考程序:
参考链接: