【问题标题】:Matching a shape and make background white匹配形状并使背景变白
【发布时间】:2021-09-15 03:42:55
【问题描述】:

我正在尝试将文本与 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

我想得到以下结果:

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

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

感谢您的回复!

【问题讨论】:

  • 什么是没有标记的大图,你的模板图是什么?您可以使用 cv2.minMaxLoc() 获取最佳位置的坐标。
  • @fmw42 感谢您的回复!请找到我的更新。
  • 对不起,我还是不明白。您是否查看过有关 OpenCV 模板匹配和示例的文档。您可以通过 Google 搜索找到它们。您需要一个与大图像中的某些内容匹配的小图像作为模板图像。搜索模板图像以找到其最佳匹配位置。看起来您可能想要查找文本“LastSticker.com”。那是对的吗?你知道它已经在白色背景图像中的黑色矩形所指示的位置吗?还是您想删除除该文本之外的所有内容,并且您的输出是黑白图像?请解释
  • 请进一步解释。你的输入图像是什么?你有什么进一步的信息?你想要什么输出结果?请出示并识别image/10.jpg和matchedTxt_106.jpg。也许这篇文章会帮助stackoverflow.com/questions/68693430/…
  • 如果白色背景上的黑色矩形是你的最终结果,那么一旦你有了模板图像,你就可以得到它的尺寸,w和h。完成模板匹配后,您可以获得左上角 x,y。现在您可以创建一个与输入大小相同的白色背景图像,并在其 x,y,w,h 处绘制一个黑色填充矩形。请参阅 np.full_like() 以创建与输入图像大小相同的白色图像。

标签: python opencv opencv-python


【解决方案1】:

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

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:

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多