首页 > 解决方案 > 如何在文档中找到最大的空白(白色)正方形区域并返回其坐标和面积?

问题描述

我需要在文档中找到最大的空白区域并显示其坐标、中心点和区域,使用 python 将 QR 码放在那里。我认为 OpenCV 和 Numpy 应该足以完成这项任务。

@Mark Setchell 谢谢!此代码适用于所有具有白色背景的文档,但是当我在背景中使用带有颜色的 smth 时,它会发现一个完全不同的区域。此外,为了在文档中保持细线,我在阈值处理后使用了 Erode。尝试更改阈值和侵蚀参数,仍然无法正常工作。编辑帖子,添加彩色图片。 在此处输入图像描述 在此处输入图像描述

标签: pythonopencvimage-processingdocument

解决方案


这是一种可能的方法:

#!/usr/bin/env python3

import cv2
import numpy as np

def largestSquare(im): 
    # Make image square of 100x100 to simplify and speed up
    s = 100
    work = cv2.resize(im, (s,s), interpolation=cv2.INTER_NEAREST)

    # Make output accumulator - uint16 is ok because...
    # ... max value is 100x100, i.e. 10,000 which is less than 65,535
    # ... and you can make a PNG of it too
    p = np.zeros((s,s), np.uint16)
  
    # Find largest square
    for i in range(1, s): 
        for j in range(1, s): 
            if (work[i][j] > 0 ): 
                p[i][j] = min(p[i][j-1], p[i-1][j], p[i-1][j-1]) + 1
            else: 
                p[i][j] = 0

    # Save result - just for illustration purposes
    cv2.imwrite("result.png",p)

    # Work out what the actual answer is
    ind = np.unravel_index(np.argmax(p, axis=None), p.shape)
    print(f'Location: {ind}')
    print(f'Length of side: {p[ind]}')
      
# Load image and threshold
im  = cv2.imread('page.png', cv2.IMREAD_GRAYSCALE)
_, thr = cv2.threshold(im,127,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)

# Get largest white square
largestSquare(thr) 

输出

Location: (21, 77)
Length of side: 18

在此处输入图像描述

笔记:

  1. 我编辑了你的红色注释,所以它不会干扰我的算法。

  2. 我做了 Otsu 阈值处理以获得纯黑色和白色 - 这可能适合也可能不适合您的用例。这将取决于您的扫描和纸张背景等。

  3. 我将图像缩小到 100x100,这样就不需要一整天的时间来运行。您需要将结果缩放回原始图像的大小,但我认为您可以轻松做到这一点。

关键词:图像处理、图像、Python、OpenCV、最大的白色方块、最大的空白空间。


推荐阅读