gpt4 book ai didi

python - 使用 OpenCV 清理文本图像以进行 OCR 阅读

转载 作者:行者123 更新时间:2023-12-02 15:54:24 25 4
gpt4 key购买 nike

我收到了一些需要处理的图像,以便对其中的一些信息进行 OCR。以下是原文:

原 1

original 1

原2

original 2

原3

original 3

原4

original 4

使用此代码处理它们后:

img = cv2.imread('original_1.jpg', 0) 
ret,thresh = cv2.threshold(img,55,255,cv2.THRESH_BINARY)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT,(2,2)))
cv2.imwrite('result_1.jpg', opening)

我得到这些结果:

结果 1

result 1

结果 2

result 2

结果 3

result 3

结果 4

result 4

正如您所看到的,一些图像在 OCR 读取方面获得了不错的结果,而另一些图像在背景中仍然保留了一些噪音。

关于如何清理背景的任何建议?

最佳答案

MH304 的回答非常好且直截了当。如果您无法使用形态学或模糊来获得更清晰的图像,请考虑使用“区域过滤器”。也就是说,过滤每个不显示最小面积的 blob。

使用opencv的 connectedComponentsWithStats ,这是一个 C++ 一个非常基本的区域过滤器的实现:

cv::Mat outputLabels, stats, img_color, centroids;

int numberofComponents = cv::connectedComponentsWithStats(bwImage, outputLabels,
stats, centroids, connectivity);

std::vector<cv::Vec3b> colors(numberofComponents+1);
colors[i] = cv::Vec3b(rand()%256, rand()%256, rand()%256);

//do not count the original background-> label = 0:
colors[0] = cv::Vec3b(0,0,0);

//Area threshold:
int minArea = 10; //10 px

for( int i = 1; i <= numberofComponents; i++ ) {

//get the area of the current blob:
auto blobArea = stats.at<int>(i-1, cv::CC_STAT_AREA);

//apply the area filter:
if ( blobArea < minArea )
{
//filter blob below minimum area:
//small regions are painted with (ridiculous) pink color
colors[i-1] = cv::Vec3b(248,48,213);

}

}

使用区域过滤器,我在最嘈杂的图像上得到了这个结果:

enter image description here

**附加信息:

基本上,算法是这样的:
  • 将二进制图像传递给 connectedComponentsWithStats .功能
    将计算连接组件的数量、标签矩阵和
    附加矩阵 统计 – 包括 Blob 区域。
  • 准备一个大小为“numberOfcomponents”的颜色向量,这将有助于可视化我们实际过滤的 Blob 。颜色由 rand 函数随机生成。范围为 0 – 255,每个像素有 3 个值:BGR。
  • 考虑到背景是黑色的,所以忽略这个“连接组件”及其颜色(黑色)。
  • 设置区域阈值。该区域下方的所有 Blob 或像素都将被涂上(可笑的)粉红色。
  • 循环遍历所有找到的连接组件(blob),通过统计矩阵检索当前 blob 的面积并将其与面积阈值进行比较。
  • 如果该区域低于阈值,则将 Blob 着色为粉红色(在这种情况下,但通常您想要黑色)。
  • 关于python - 使用 OpenCV 清理文本图像以进行 OCR 阅读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59863948/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com