ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

使用Python删除字母图像中的遗留物

2019-06-27 08:53:24  阅读:330  来源: 互联网

标签:python image-processing opencv outliers cv2


我有一组图像,表示从单词图像中提取的字母.在一些图像中有相邻字母的遗骸,我想消除它们,但我不知道如何.

一些样品

我正在使用openCV,我尝试了两种方法,但没有一种方法可行.

使用findContours:

def is_contour_bad(c):
    return len(c) < 50

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(gray, 50, 100)

contours = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if imutils.is_cv2() else contours[1]

mask = np.ones(image.shape[:2], dtype="uint8") * 255

for c in contours:
    # if the c  ontour is bad, draw it on the mask
    if is_contour_bad(c):
        cv2.drawContours(mask, [c], -1, 0, -1)

# remove the contours from the image and show the resulting images
image = cv2.bitwise_and(image, image, mask=mask)
cv2.imshow("After", image)
cv2.waitKey(0)

我认为它不起作用,因为图像在边缘cv2.drawContours无法正确计算面积并且不消除内部点

使用connectedComponentsWithStats:

cv2.imshow("Image", img)
cv2.waitKey(0)
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(img)
sizes = stats[1:, -1];
nb_components = nb_components - 1

min_size = 150

img2 = np.zeros((output.shape))
for i in range(0, nb_components):
    if sizes[i] >= min_size:
        img2[output == i + 1] = 255

cv2.imshow("After", img2)
cv2.waitKey(0)

在这种情况下,我不知道为什么侧面的小元素不会将它们识别为连接组件

嗯..我非常感谢任何帮助!

解决方法:

在问题的最开始,你提到过字母是从一个单词的图像中提取出来的.

所以我认为,你可以正确地完成提取.那么你就不会遇到像这样的问题.我可以给你一个解决方案,适用于从原始图像中提取字母或从你给出的图像中提取和分离字母.

解:

您可以使用凸包坐标来分隔这样的字符.

码:

import cv2
import numpy as np

img = cv2.imread('test.png', 0)
cv2.bitwise_not(img,img)
img2 = img.copy()

ret, threshed_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(threshed_img, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

#--- Black image to be used to draw individual convex hull ---
black = np.zeros_like(img)
contours = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0])

for cnt in contours:
    hull = cv2.convexHull(cnt)

    img3 = img.copy()
    black2 = black.copy()

    #--- Here is where I am filling the contour after finding the convex hull ---
    cv2.drawContours(black2, [hull], -1, (255, 255, 255), -1)
    r, t2 = cv2.threshold(black2, 127, 255, cv2.THRESH_BINARY)
    masked = cv2.bitwise_and(img2, img2, mask = t2)
    cv2.imshow("masked.jpg", masked)
    cv2.waitKey(0)

cv2.destroyAllWindows()

输出:

  

因此,正如我所建议的那样,更好的方法是在从原始图像中提取字符时使用此解决方案,而不是在提取后删除噪声.

标签:python,image-processing,opencv,outliers,cv2
来源: https://codeday.me/bug/20190627/1303251.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有