如何将图像裁剪到仅使用Python OpenCV的文本部分?
我想裁剪图像以仅提取文本部分。有成千上万的尺寸不同,所以我无法硬码坐标。我试图删除左侧和底部的不需要线。我该怎么做?
原始 | 预期 |
---|---|
|
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我想裁剪图像以仅提取文本部分。有成千上万的尺寸不同,所以我无法硬码坐标。我试图删除左侧和底部的不需要线。我该怎么做?
原始 | 预期 |
---|---|
|
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(2)
通过查找图像中的所有非零点来确定最小跨度的边界框。最后,使用此边界框裁剪您的图像。在这里找到轮廓是耗时且不必要的,尤其是因为您的文本是与轴线一致的。您可以通过组合
cv2.findnonzero
和cv2.BoundingRect
来实现目标。希望这会起作用! :
在上面的代码中,代码是我将阈值设置为50以下以使深文本为白色的地方。但是,由于这输出了二进制图像,因此我将其转换为
uint8
,然后缩放255。文本有效地倒置。然后,使用
cv2.findnonzero,
我们发现了此图像的所有非零位置。然后,我们将其传递给cv2.BoundingRect
,它返回了左上角边界框以及其宽度和高度。最后,我们可以利用它来裁剪图像。这是在原始图像上完成的,而不是倒版本。Determine the least spanning bounding box by finding all the non-zero points in the image. Finally, crop your image using this bounding box. Finding the contours is time-consuming and unnecessary here, especially because your text is axis-aligned. You may accomplish your goal by combining
cv2.findNonZero
andcv2.boundingRect
.Hope this will work ! :
in above code from forth line of code is where I set the threshold below 50 to make the dark text white. However, because this outputs a binary image, I convert to
uint8
, then scale by 255. The text is effectively inverted.Then, using
cv2.findNonZero,
we discover all of the non-zero locations for this image.We then passed this tocv2.boundingRect
, which returns the top-left corner of the bounding box, as well as its width and height. Finally, we can utilise this to crop the image. This is done on the original image, not the inverted version.这是一种简单的方法:
获取二进制图像。 加载图像,,,然后 OTSU的阈值获得二进制黑色/白色图像。
卸下水平线。由于我们只是尝试提取文本,因此我们删除水平线以帮助我们下一步,因此不正确的轮廓不会合并在一起。
将文本合并到一个轮廓中。这个想法是,彼此相邻的字符是文本墙的一部分。因此,我们可以
查找轮廓并提取ROI。 noreferrer“>查找轮廓,按区域排序轮廓,然后使用numpy切片提取最大的轮廓ROI。
这是每个步骤的可视化:
中的水平线
- >
绿色1扩张以组合成单个轮廓
- /code>检测到的ROI在绿色
结果
代码
Here's a simple approach:
Obtain binary image. Load the image, grayscale, Gaussian blur, then Otsu's threshold to obtain a binary black/white image.
Remove horizontal lines. Since we're trying to only extract text, we remove horizontal lines to aid us in our next step so incorrect contours will not merge together.
Merge text into a single contour. The idea is that characters which are adjacent to each other are part of the wall of text. So we can dilate individual contours together to obtain a single contour to extract.
Find contours and extract ROI. We find contours, sort contours by area, then extract the largest contour ROI using Numpy slicing.
Here's the visualization of each step:
Binary image
->
Removed horizontal lines in greenDilate to combine into a single contour
->
Detected ROI to extract in greenResult
Code