【问题标题】:OpenCV Rectangle Fills Entire ScreenOpenCV 矩形填充整个屏幕
【发布时间】:2020-07-18 04:42:45
【问题描述】:

我正在尝试在一些 OCR 文本周围绘制一个填充矩形。

    d = pytesseract.image_to_data(image, output_type=Output.DICT)
    os.remove(filename);

    n_boxes = len(d['level'])
    for i in range(n_boxes):
        (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 0), 1)

    cv2.imwrite("./output/{}.png".format("blurred_" + str(os.getpid())), image);

这行似乎是问题所在: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 0), 1)

当我将 1 替换为 -1 时,它应该绘制填充的矩形,而是用填充的矩形填充整个图像。

没有填充,您可以看到应该着色的内容:

有填充:

如果需要,这是完整的代码:

from PIL import Image
import pytesseract
from pytesseract import Output
import argparse, cv2, os
import numpy as np

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
    help="path of image to be blurrified")
ap.add_argument("-b", "--blurtype", required=True,
    help="blur [words] or [character]s")
ap.add_argument("-p", "--preprocess", type=str, default="thresh",
    help="preprocess type")
args = vars(ap.parse_args())

image = cv2.imread(args["image"])
h, w, _ = image.shape
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

if args["preprocess"] == "thresh":
    gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
elif args["preprocess"] == "blur":
    gray = cv2.medianBlur(gray, 3)

filename = "./temp/{}.png".format("grayscale_" + str(os.getpid()))
cv2.imwrite(filename, gray)

if args["blurtype"] == "character":
    
    text = pytesseract.image_to_boxes(Image.open(filename))
    os.remove(filename);

    for b in text.splitlines():
        b = b.split(' ')
        image = cv2.rectangle(image, (int(b[1]), h - int(b[2])), (int(b[3]), h - int(b[4])), (0, 0, 0), -1)

    cv2.imwrite("./output/{}.png".format("blurred_" + str(os.getpid())), image);
elif args["blurtype"]== "words":

    d = pytesseract.image_to_data(image, output_type=Output.DICT)
    os.remove(filename);

    n_boxes = len(d['level'])
    for i in range(n_boxes):
        (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 0), 1)

    cv2.imwrite("./output/{}.png".format("blurred_" + str(os.getpid())), image);

我们将不胜感激!

【问题讨论】:

    标签: python python-3.x opencv tesseract rectangles


    【解决方案1】:

    pytesseract 也在制作完整图像的边界框。要查看这一点,厚度为 1,制作 (0, 255, 0) 颜色的矩形。因此,当您传递厚度 = -1 时,图像的边界框也会被着色,因此完整图像也会被着色。为避免这种情况,请拒绝该矩形。

    【讨论】:

    • 啊,非常感谢!我什至没有注意到有一个边框。
    猜你喜欢
    • 2019-03-01
    • 2012-07-29
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多