我有一个带有白色背景上的文字的图像,另一个我想将此文字覆盖在上面。
我已经计算出两个图像之间的吸收差,现在有了可用于混合两个图像的遮罩。
img1 * mask + img2 * (1-mask)
我所遇到的问题是文本的轮廓为黑色,但文本的中心为白色。但是,图像的某些背景也是白色。
所以我生成的遮罩当前是这样的。
这是我的目标。
有人建议用纯白色填充数字吗?
我已经尝试将文本的颜色设置为浅灰色,并使用np.where,但我似乎无法将其打起来。
编辑-我的图像是:
matplotlib中的空白轴(如果需要)
更新的BARS转换为图像。 (背景图像)-请忽略它们仅用于测试的图像! HA
我需要在BARS图像上叠加的文本框架。 (图像叠加在上面)
这是使用Python / OpenCV呈现的图像的一种实现方法。
输入:
import cv2
import numpy as np
# read image
img = cv2.imread('1970.png')
# convert gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# threshold saturation image
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
# get outer contours and draw filled ones as white on black background
cntrs = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
result1 = np.zeros_like(img)
for c in cntrs:
cv2.drawContours(result1, [c], 0, (255,255,255), -1)
# invert thresh
thresh2 = 255 - thresh
hh, ww = thresh2.shape
# floodfill thresh2 with black then white then black again
mask = np.zeros([hh + 2, ww + 2], np.uint8)
thresh2 = cv2.floodFill(thresh2, mask, (0,0), 0, 0, 0, flags=8)[1]
mask = np.zeros([hh + 2, ww + 2], np.uint8)
thresh2 = cv2.floodFill(thresh2, mask, (0,0), 255, 0, 0, flags=8)[1]
mask = np.zeros([hh + 2, ww + 2], np.uint8)
thresh2 = cv2.floodFill(thresh2, mask, (0,0), 0, 0, 0, flags=8)[1]
# get outer contours of these holes and draw filled ones as black
cntrs2 = cv2.findContours(thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs2 = cntrs2[0] if len(cntrs2) == 2 else cntrs2[1]
result2 = result1.copy()
for c in cntrs2:
cv2.drawContours(result2, [c], 0, (0,0,0), -1)
# save output image
cv2.imwrite('1970_thresh1.png', thresh)
cv2.imwrite('1970_thresh2.png', thresh2)
cv2.imwrite('1970_result1.png', result1)
cv2.imwrite('1970_result2.png', result2)
# display IN and OUT images
cv2.imshow('thresh', thresh)
cv2.imshow('thresh2', thresh2)
cv2.imshow('result1', result1)
cv2.imshow('result2', result2)
cv2.waitKey(0)
cv2.destroyAllWindows()
阈值:
白色填充轮廓:
注水后的反转阈值(内孔):
最终结果: