我有一组表示从单词图像中提取的字母的图像。在一些图像中有相邻字母的残留物,我想消除它们,但我不知道如何消除。
一些 sample
我正在使用 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)
在这种情况下我不知道为什么侧面的小元素不会将它们识别为连接组件
好吧..我将不胜感激任何帮助!
最佳答案
在问题的最开始,您提到已经从单词的图像中提取了字母。
所以我认为,你可以正确地完成提取。那你就不会遇到这样的问题了。我可以给你一个解决方案,它适用于从原始图像中提取字母或从你提供的图像中提取和分离字母。
解决方案:
您可以使用 convex hull
坐标来分隔这样的字符。
代码:
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 - 使用 Python 删除字母图像中的残留物,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53504738/