OpenCV:分解组件之间的单个像素桥

时间:2018-12-13 09:25:50

标签: python opencv cv2

我想对单词图像进行阈值处理并将其拆分为连接的组件(字母)。由于先前的透视变换或分辨率差,可能会在字母之间形成单个像素桥。

组件可能相对较薄,这就是为什么简单的腐蚀+膨胀会破坏它们的原因。

有没有一种简单的方法可以腐蚀单个像素的电桥,而又不对电桥的腐蚀核产生任何可能的排列?

示例1:单词是Pflegt,字母Pfl已连接

enter image description here enter image description here

示例2:这更严重,而且CCL似乎也标记了甚至不碰到脸部的区域(尽管是4位连接的)。

enter image description here enter image description here

来源:

# Label image
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
connectivity = 4
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity, cv2.CV_32S)

# Map component labels to hue val
label_hue = np.uint8(179 * labels / np.max(labels))
blank_ch = 255 * np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

# cvt to BGR for display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)

1 个答案:

答案 0 :(得分:4)

因此,要实现此目标有些棘手,尤其是更严重的图像,但是以我的经验,在处理此类 pixelated 图像时,unsharp mask始终帮助。所以这就是我尝试过的:

import numpy as np
import cv2

image = cv2.imread("U:/SO/cca.png")
imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Unsharp mask here
gaussian = cv2.GaussianBlur(imgray, (7, 7), 10.0)
unsharp_image = cv2.addWeighted(imgray, 2.5, gaussian, -1.5, 0, imgray)
cv2.imwrite("cca_2_unsharp.jpg", unsharp_image)

unsharp_image = cv2.erode(unsharp_image, np.ones((3,3), np.uint8), iterations=1)

ret,thresh = cv2.threshold(unsharp_image, 127, 255, cv2.THRESH_BINARY + 
cv2.THRESH_OTSU)
cv2.imwrite("cca_2_thresh.jpg", thresh)

connectivity = 4
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, 
connectivity, cv2.CV_32S)


# Map component labels to hue val
label_hue = np.uint8(179 * labels / np.max(labels))
blank_ch = 255 * np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

# cvt to BGR for display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
cv2.imwrite("cca_2_res.jpg", labeled_img)

结果:

Result 1

Result 2

如您所见,更严重的图像仍然不能很好地工作。在我的试验中,我不需要腐蚀第一张图像,但是它对结果的影响不大。我将尝试其他方法并更新答案。让我知道您的想法!