OpenCV矩形填充整个屏幕

时间:2020-07-18 04:42:45

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

我正在尝试在一些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(这应该绘制填充的矩形)时,它会用填充的矩形填充整个图像。

没有填充,您可以看到什么是彩色的: no fill

填充: fill

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

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);

我们将不胜感激!

1 个答案:

答案 0 :(得分:0)

pytesseract还在制作完整图像的边界框。要进行查看,请使用厚度1,制作一个(0,255,0)颜色的矩形。因此,当您通过厚度= -1时,图像的边界框也会被着色,因此竞争图像也会被着色。为了避免这种情况,请拒绝该矩形。