将附近的边界框合并为一个

8

我刚接触Python,正在使用《计算机视觉》中的快速入门指南:使用REST API和Python提取印刷文字(OCR)进行文本检测。因此,这个算法会给定Ymin、XMax、Ymin和Xmax坐标,并为每行文本绘制一个边界框,如下图所示。

enter image description here

但是我希望将靠近的文本分组以获得一个单独的边界框。因此,对于上面图片的情况,它将有2个包含最近文本的边界框。

以下代码提供了Ymin、XMax、Ymin和Xmax坐标,并为每行文本绘制一个边界框。

import requests
# If you are using a Jupyter notebook, uncomment the following line.
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from PIL import Image
from io import BytesIO

# Replace <Subscription Key> with your valid subscription key.
subscription_key = "f244aa59ad4f4c05be907b4e78b7c6da"
assert subscription_key

vision_base_url = "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/"

ocr_url = vision_base_url + "ocr"

# Set image_url to the URL of an image that you want to analyze.
image_url = "https://cdn-ayb.akinon.net/cms/2019/04/04/e494dce0-1e80-47eb-96c9-448960a71260.jpg"

headers = {'Ocp-Apim-Subscription-Key': subscription_key}
params  = {'language': 'unk', 'detectOrientation': 'true'}
data    = {'url': image_url}
response = requests.post(ocr_url, headers=headers, params=params, json=data)
response.raise_for_status()

analysis = response.json()

# Extract the word bounding boxes and text.
line_infos = [region["lines"] for region in analysis["regions"]]
word_infos = []
for line in line_infos:
    for word_metadata in line:
        for word_info in word_metadata["words"]:
            word_infos.append(word_info)
word_infos

# Display the image and overlay it with the extracted text.
plt.figure(figsize=(100, 20))
image = Image.open(BytesIO(requests.get(image_url).content))
ax = plt.imshow(image)
texts_boxes = []
texts = []
for word in word_infos:
    bbox = [int(num) for num in word["boundingBox"].split(",")]
    text = word["text"]
    origin = (bbox[0], bbox[1])
    patch  = Rectangle(origin, bbox[2], bbox[3], fill=False, linewidth=3, color='r')
    ax.axes.add_patch(patch)
    plt.text(origin[0], origin[1], text, fontsize=2, weight="bold", va="top")
#     print(bbox)
    new_box = [bbox[1], bbox[0], bbox[1]+bbox[3], bbox[0]+bbox[2]]
    texts_boxes.append(new_box)
    texts.append(text)
#     print(text)
plt.axis("off")
texts_boxes = np.array(texts_boxes)
texts_boxes

输出边界框

array([[  68,   82,  138,  321],
       [ 202,   81,  252,  327],
       [ 261,   81,  308,  327],
       [ 364,  112,  389,  182],
       [ 362,  192,  389,  305],
       [ 404,   98,  421,  317],
       [  92,  421,  146,  725],
       [  80,  738,  134, 1060],
       [ 209,  399,  227,  456],
       [ 233,  399,  250,  444],
       [ 257,  400,  279,  471],
       [ 281,  399,  298,  440],
       [ 286,  446,  303,  458],
       [ 353,  394,  366,  429]]

但我希望通过接近的距离合并它们。


你的意思是将完全包含在B中的A合并,还是只要它们有交集就合并它们? - recnac
谢谢您的回复。不完全是那样,我的意思是将相邻的盒子合并成一个更大的盒子,这个新的盒子应该包含所有相邻的盒子。 - Baron
所以你想合并足够接近的盒子吗?我认为你应该定义规则。哪些情况应该绑在一起,哪些情况应该保持分开。 - recnac
准确地说,规则是只有距离接近的盒子才应该合并。 - Baron
5个回答

6

感谢 @recnac 的算法,它帮助我解决了这个问题。

我的解决方案是这样的。 生成一个新的框,将距离接近的文本框合并成一个新框。其中包含接近的文本。

#Distance definition  between text to be merge
dist_limit = 40

#Copy of the text and object arrays
texts_copied = copy.deepcopy(texts)
texts_boxes_copied = copy.deepcopy(texts_boxes)


#Generate two text boxes a larger one that covers them
def merge_boxes(box1, box2):
    return [min(box1[0], box2[0]), 
         min(box1[1], box2[1]), 
         max(box1[2], box2[2]),
         max(box1[3], box2[3])]



#Computer a Matrix similarity of distances of the text and object
def calc_sim(text, obj):
    # text: ymin, xmin, ymax, xmax
    # obj: ymin, xmin, ymax, xmax
    text_ymin, text_xmin, text_ymax, text_xmax = text
    obj_ymin, obj_xmin, obj_ymax, obj_xmax = obj

    x_dist = min(abs(text_xmin-obj_xmin), abs(text_xmin-obj_xmax), abs(text_xmax-obj_xmin), abs(text_xmax-obj_xmax))
    y_dist = min(abs(text_ymin-obj_ymin), abs(text_ymin-obj_ymax), abs(text_ymax-obj_ymin), abs(text_ymax-obj_ymax))

    dist = x_dist + y_dist
    return dist

#Principal algorithm for merge text 
def merge_algo(texts, texts_boxes):
    for i, (text_1, text_box_1) in enumerate(zip(texts, texts_boxes)):
        for j, (text_2, text_box_2) in enumerate(zip(texts, texts_boxes)):
            if j <= i:
                continue
            # Create a new box if a distances is less than disctance limit defined 
            if calc_sim(text_box_1, text_box_2) < dist_limit:
            # Create a new box  
                new_box = merge_boxes(text_box_1, text_box_2)            
             # Create a new text string 
                new_text = text_1 + ' ' + text_2

                texts[i] = new_text
                #delete previous text 
                del texts[j]
                texts_boxes[i] = new_box
                #delete previous text boxes
                del texts_boxes[j]
                #return a new boxes and new text string that are close
                return True, texts, texts_boxes

    return False, texts, texts_boxes


need_to_merge = True

#Merge full text 
while need_to_merge:
    need_to_merge, texts_copied, texts_boxes_copied = merge_algo(texts_copied, texts_boxes_copied)

texts_copied

非常感谢,它运行得非常好。如果您知道其他资源,请分享。仍然有一些框对我没有合并。 - Aravind R

2

您可以检查两个框的边界(x_minx_maxy_miny_max),如果它们之间的差小于close_dist,则应将它们合并为一个新框。然后在两个for循环中连续执行此操作:


from itertools import product

close_dist = 20

# common version
def should_merge(box1, box2):
    for i in range(2):
        for j in range(2):
            for k in range(2):
                if abs(box1[j * 2 + i] - box2[k * 2 + i]) <= close_dist:
                    return True, [min(box1[0], box2[0]), min(box1[1], box2[1]), max(box1[2], box2[2]),
                                  max(box1[3], box2[3])]
    return False, None


# use product, more concise
def should_merge2(box1, box2):
    a = (box1[0], box1[2]), (box1[1], box1[3])
    b = (box2[0], box2[2]), (box2[1], box2[3])

    if any(abs(a_v - b_v) <= close_dist for i in range(2) for a_v, b_v in product(a[i], b[i])):
        return True, [min(*a[0], *b[0]), min(*a[1], *b[1]), max(*a[0], *b[0]), max(*a[1], *b[1])]

    return False, None

def merge_box(boxes):
    for i, box1 in enumerate(boxes):
        for j, box2 in enumerate(boxes[i + 1:]):
            is_merge, new_box = should_merge(box1, box2)
            if is_merge:
                boxes[i] = None
                boxes[j] = new_box
                break

    boxes = [b for b in boxes if b]
    print(boxes)

test code:

boxes = [[68, 82, 138, 321],
         [202, 81, 252, 327],
         [261, 81, 308, 327],
         [364, 112, 389, 182],
         [362, 192, 389, 305],
         [404, 98, 421, 317],
         [92, 421, 146, 725],
         [80, 738, 134, 1060],
         [209, 399, 227, 456],
         [233, 399, 250, 444],
         [257, 400, 279, 471],
         [281, 399, 298, 440],
         [286, 446, 303, 458],
         [353, 394, 366, 429]]

print(merge_box(boxes))

输出:

[[286, 394, 366, 458], [261, 81, 421, 327], [404, 98, 421, 317], [80, 738, 134, 1060], [353, 394, 366, 429]]

无法进行可视化测试,请代为测试。

希望这对您有所帮助,如果您有进一步的问题,请在评论中提出。:)


Original Answer翻译成"最初的回答"

兄弟,非常感谢您的回复。我已经尝试了您的代码,它运行良好,但是当使用大型销售传单时,您的算法会在没有文本的地方创建一个分隔框。我想请您查看这张图片,在文本上我画了一些带有紧密距离的分隔绿色框,这正是我想要获得的结果。 https://i.ibb.co/c1ttrkb/Capture.png 因为如我之前所解释的,我的算法通过部分检测文本,我想将距离较近的文本合并到一个单一的边界框中。 - Baron
哦,如果我使用你的解决方案,_很多_边界框会丢失:https://imgur.com/a/mv9HGaW - Mike 'Pomax' Kamermans

1

在运行代码之前,您可以使用openCV和应用dilation和黑帽变换来处理图像


请注意,如果您想在需要未膨胀差分的精度的同时缩小轮廓列表,则此解决方案不可行。 - Mike 'Pomax' Kamermans

0
制作了一个易于阅读的解决方案:
contours = get_contours(frame)
boxes = [cv2.boundingRect(c) for c in contours]
boxes = merge_boxes(boxes, x_val=40, y_val=20) # Where x_val and y_val are axis thresholds

def get_contours(frame):  # Returns a list of contours
    contours = cv2.findContours(frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contours = imutils.grab_contours(contours)
    return contours


def merge_boxes(boxes, x_val, y_val):
    size = len(boxes)
    if size < 2:
        return boxes

    if size == 2:
        if boxes_mergeable(boxes[0], boxes[1], x_val, y_val):
            boxes[0] = union(boxes[0], boxes[1])
            del boxes[1]
        return boxes

    boxes = sorted(boxes, key=lambda r: r[0])
    i = size - 2
    while i >= 0:
        if boxes_mergeable(boxes[i], boxes[i + 1], x_val, y_val):
            boxes[i] = union(boxes[i], boxes[i + 1])
            del boxes[i + 1]
        i -= 1
    return boxes


def boxes_mergeable(box1, box2, x_val, y_val):
    (x1, y1, w1, h1) = box1
    (x2, y2, w2, h2) = box2
    return max(x1, x2) - min(x1, x2) - minx_w(x1, w1, x2, w2) < x_val \
        and max(y1, y2) - min(y1, y2) - miny_h(y1, h1, y2, h2) < y_val


def minx_w(x1, w1, x2, w2):
    return w1 if x1 <= x2 else w2


def miny_h(y1, h1, y2, h2):
    return h1 if y1 <= y2 else h2


def union(a, b):
    x = min(a[0], b[0])
    y = min(a[1], b[1])
    w = max(a[0] + a[2], b[0] + b[2]) - x
    h = max(a[1] + a[3], b[1] + b[3]) - y
    return x, y, w, h

新手请查看以下解决方案:https://dev59.com/K7_qa4cB1Zd3GeqPOsEO - Sybghatallah Marwat

-5

嗨,我认为你的问题可以用 easyocr 解决

import easyocr

reader = easyocr.Reader(['en']) 

result = reader.readtext('image_name.jpg',paragraph=True)

print(result)

你的答案可以通过添加更多支持信息来改进。请[编辑]以添加更多细节,例如引用或文献,以便他人确认您的答案正确。您可以在帮助中心中找到有关编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接