【问题标题】:Extracting and saving characters from an image从图像中提取和保存字符
【发布时间】:2020-06-16 07:20:09
【问题描述】:

我正在跟进这篇文章:How to extract only characters from image?

这个解决方案非常适合我(通过一些调整)达到其预期目的。但是,我试图通过保存每个字符来更进一步。因此,在这篇文章的示例中,我希望将字符 KNM 保存为它们自己的单独图像。我尝试使用带有 rect 对象的cv2.imwrite 函数迭代嵌套的 if 循环,尽管最终输出是 7 个包含整个图像的图像,并且每次只添加一个矩形来突出显示下一个轮廓。

【问题讨论】:

  • 您可以添加示例示例图像吗?
  • @nathancy 是的,当然,我现在已经对其进行了编辑。在这种图像情况下,它只有 3 个图像而不是 7 个
  • 看看How to crop each character on an image using Python OpenCV?。如果您仍有问题,请告诉我
  • 乍一看很完美,我会尝试一下。非常感谢!
  • 如果该链接不适合您,请查看我在下面发布的解决方案

标签: python image image-processing computer-vision contour


【解决方案1】:

这是一个简单的方法:

  1. 获取二值图像。加载图像,灰度,Otsu's threshold

  2. 提取 ROI。 Find contours 并从左到右排序,以确保我们使用imutils.contours.sort_contours 以正确的顺序排列轮廓。我们使用contour area 进行过滤,然后使用 Numpy 切片提取并保存每个 ROI。


输入

二值图像

检测到的字符以绿色突出显示

提取的 ROI

代码

import cv2
from imutils import contours

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)[1]

# Find contours, sort from left-to-right, then crop
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts, _ = contours.sort_contours(cnts, method="left-to-right")

# Filter using contour area and extract ROI
ROI_number = 0
for c in cnts:
    area = cv2.contourArea(c)
    if area > 10:
        x,y,w,h = cv2.boundingRect(c)
        ROI = image[y:y+h, x:x+w]
        cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
        cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
        ROI_number += 1

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()

【讨论】:

  • 嗨,nathancy,我知道我的这条评论会被版主删除。但是在得到它之前,请您建议我一些学习opencv的资源,我现在在大多数OCV问题中都看到了您的答案。我是初学者,请你帮我解决这个问题。
  • @HimanshuPoddar 我也是初学者,大约 10 个月前我才开始使用 CV。我刚刚阅读了文档并构建了一些应用程序来学习。我的第一个项目是构建a real-time fedex logo detector。随手学习一项新技术
猜你喜欢
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 2013-02-03
  • 2015-02-03
  • 1970-01-01
相关资源
最近更新 更多