假设我有一个字母图像,我想找到这些字母的区域。
我写了这段代码:
MIN_CONTOUR_AREA = 10
img = cv2.imread("alphabets.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blured = cv2.blur(gray, (5,5), 0)
img_thresh = cv2.adaptiveThreshold(blured, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
imgContours, Contours, Hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in Contours:
if cv2.contourArea(contour) > MIN_CONTOUR_AREA:
[X, Y, W, H] = cv2.boundingRect(contour)
cv2.rectangle(img, (X, Y), (X + W, Y + H), (0,0,255), 2)
cv2.imshow('contour', img)
但上面的代码有这个输出: 的结果
如何找到不像“我”或阿拉伯字母那样不连续的字母的轮廓?
答案 0 :(得分:6)
在找到轮廓之前,您可以使用一些分割方法:
rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 10))
threshed = cv2.morphologyEx(img_thresh, cv2.MORPH_CLOSE, rect_kernel)
在应用cv2.findContours
后,结果如下:
答案 1 :(得分:0)
我有这个问题。我将其固定为这种方式。 添加此代码:
dst = cv2.Canny(gray, 0, 150)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dst = cv2.Canny(gray, 0, 150)
blured = cv2.blur(dst, (5,5), 0)
img_thresh = cv2.adaptiveThreshold(blured, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
imgContours, Contours, Hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in Contours:
if cv2.contourArea(contour) > MIN_CONTOUR_AREA:
[X, Y, W, H] = cv2.boundingRect(contour)
cv2.rectangle(img, (X, Y), (X + W, Y + H), (0,0,255), 2)
cv2.imshow('contour', img)