匹配形状并使背景变白

Matching a shape and make background white

我正在尝试将文本与 opencv 匹配,并将所提供图像的背景设为白色,并将文本替换为黑色矩形。

import cv2
import numpy as np


img_rgb = cv2.imread('./image/10.jpg')
template = cv2.imread('./image/matchedTxt_106.jpg')
w, h = template.shape[:-1]

res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
threshold = .5
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):  
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 0), -1)

cv2.imwrite('result1.png', img_rgb)

目前,我得到以下结果:

在这里找到我的 google colab 示例:

Notebook

初始图像 10.jpg 如下所示:

我的模板matchedTxt_106.jpg:

我想得到以下结果:

在结果图片上,水印的位置是一个黑色的文本框,结果图片的背景是白色的。结果图像应与上一张图像大小相同。

对我做错了什么有什么建议吗?此外,如何获取图像文本在初始图像上的坐标?

感谢您的回复!

您的主要问题是替换宽度和高度。

w, h = template.shape[:-1]替换为:

h, w = template.shape[:-1]

在 NumPy 数组中shape,高度在前。


这是在白色背景上生成黑色矩形的代码示例:

import cv2
import numpy as np


img_rgb = cv2.imread('./image/10.png')  # ./image/10.jpg
template = cv2.imread('./image/matchedTxt_106.png')  # ./image/matchedTxt_106.jpg
h, w = template.shape[:-1]  # Height first.

img_bw = np.full(img_rgb.shape[:-1], 255, np.uint8)  # Initialize white image

res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
threshold = .5
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):  
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 0), -1)
    cv2.rectangle(img_bw, pt, (pt[0] + w, pt[1] + h), 0, -1)  # Draw black (filled) rectangle on img_bw

cv2.imwrite('result1.png', img_rgb)
cv2.imwrite('result_bw.png', img_bw)

结果:

result_bw.png:

result1.png: