python - 如何在文档中找到最大的空白(白色)正方形区域并返回其坐标和面积?
问题描述
我需要在文档中找到最大的空白区域并显示其坐标、中心点和区域,使用 python 将 QR 码放在那里。我认为 OpenCV 和 Numpy 应该足以完成这项任务。
@Mark Setchell 谢谢!此代码适用于所有具有白色背景的文档,但是当我在背景中使用带有颜色的 smth 时,它会发现一个完全不同的区域。此外,为了在文档中保持细线,我在阈值处理后使用了 Erode。尝试更改阈值和侵蚀参数,仍然无法正常工作。编辑帖子,添加彩色图片。
解决方案
这是一种可能的方法:
#!/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
笔记:
我编辑了你的红色注释,所以它不会干扰我的算法。
我做了 Otsu 阈值处理以获得纯黑色和白色 - 这可能适合也可能不适合您的用例。这将取决于您的扫描和纸张背景等。
我将图像缩小到 100x100,这样就不需要一整天的时间来运行。您需要将结果缩放回原始图像的大小,但我认为您可以轻松做到这一点。
关键词:图像处理、图像、Python、OpenCV、最大的白色方块、最大的空白空间。
推荐阅读
- r - 在 R 中使用“ddply”和“glm”进行 k 值估计(双曲线延迟折扣)时出错
- python - 如何导入修改后的库而不是以前安装的库?
- hosting - 错误:X-Content-Type-Options: nosniff , MIME („text/html") after using hosting
- api - 在颤振中热重载后显示restcountries api
- python-3.x - 使用 Pillow / Python 对齐文本
- tampermonkey - 本地开发用户脚本(Tampermonkey)可以实现浏览器同步测试吗?
- powershell - 从 cmd 运行 Powershell 脚本
- github - 在 github 操作中使用 openssl
- python - 增加轴上的 xticks 数量
- c++ - 如何告诉函子模板类用户他必须编写什么函子 operator() 签名?