2016-08-06 2 views
0

OCR에 대해 숫자와 문자가있는 이미지의 윤곽을 찾습니다. 그래서 윤곽선을 왼쪽에서 오른쪽으로 정렬하고 라인을 선으로, 즉 위에서 아래로 정렬해야합니다. 지금은 등고선이 그렇게 정렬되지 않았습니다.Python과 OpenCV를 사용하여 왼쪽에서 오른쪽으로 윤곽선을 정렬하는 방법

PIC: Contours is detected as shown here, including dots above i, full stop, comma, etc.

예를 들어, 상기 이미지의 윤곽선이 임의로 정렬된다.

내가 원하는 것은 D, O, Y, O, U, K, N, O, W, S, O, M, E, O, N, E, R,. (점) 나는 (점없이), c, h ... 등등. 나는 우리가 먼저 y 좌표를 관찰 한 다음 몇 가지 키와 x 좌표를 사용하는 몇 가지 방법을 시도했다. 지금과 마찬가지로 다음 정렬 코드가 있습니다. 처음 2 줄에서는 작동합니다. 그런 다음 3 행에서 어떻게 든 정렬이 발생하지 않습니다. 주된 문제는 i, j,?, (점), (쉼표) 등과 같은 문자 (같은 점에 속함에도 불구하고 (점)의 y 축이 다양 함)에있는 것처럼 보입니다. 그렇다면 이것에 대한 좋은 해결책은 무엇일까요?

for ctr in contours:  
    if cv2.contourArea(ctr) > maxArea * areaRatio: 
     rect.append(cv2.boundingRect(cv2.approxPolyDP(ctr,1,True))) 

#rect contains the contours 
for i in rect: 
    x = i[0] 
    y = i[1] 
    w = i[2] 
    h = i[3] 

    if(h>max_line_height): 
     max_line_height = h 

mlh = max_line_height*2 
max_line_width = raw_image.shape[1] #width of the input image 
mlw = max_line_width 
rect = np.asarray(rect) 
s = rect.astype(np.uint32) #prevent overflows 
order= mlw*(s[:,1]/mlh)+s[:,0] 
sort_order= np.argsort(order) 
rect = rect[ sort_order ] 
+0

pls는 3 행에서 작동하지 않는 것을 명확하게 보여줍니다. – jlarsch

+0

이미지의 세 번째 줄의 윤곽선이 stress.ed, hav..i, n, g로 정렬됩니다. 등등. 점들이 다른 문자의 위치에 무작위로 나타나서 다른 문자가 올바른 정렬 된 위치에서 떨어집니다. –

답변

0

단일 정렬로 문제를 해결하려는 것이 좋습니다. 하지만 각 줄의 y 변형은 알고리즘을 손상시킬 수 있습니다. max_line_height은 다른 입력을 기반으로 조정해야 할 것입니다.

그럼 대신 약간 다른 알고리즘을 제안 하겠지만 상당한 계산 복잡성을 제안합니다. 모든 상자를 가로로 보면 라인 N+1의 모든 상자는 1 ~ N 상자의 상자와 결코 교차하지 않지만 한 줄 안에 서로 교차합니다. 따라서 모든 상자를 먼저 y으로 정렬하고 하나씩 살펴보고 한 줄로 그룹화 한 다음 각 줄 내에서 x으로 정렬하십시오.

# sort all rect by their y 
rect.sort(key=lambda b: b[1]) 
# initially the line bottom is set to be the bottom of the first rect 
line_bottom = rect[0][1]+rect[0][3]-1 
line_begin_idx = 0 
for i in xrange(len(rect)): 
    # when a new box's top is below current line's bottom 
    # it's a new line 
    if rect[i][1] > line_bottom: 
     # sort the previous line by their x 
     rect[line_begin_idx:i] = sorted(rect[line_begin_idx:i], key=lambda b: b[0]) 
     line_begin_idx = i 
    # regardless if it's a new line or not 
    # always update the line bottom 
    line_bottom = max(rect[i][1]+rect[i][3]-1, line_bottom) 
# sort the last line 
rect[line_begin_idx:] = sorted(rect[line_begin_idx:], key=lambda b: b[0]) 

지금 rect이 원하는 방식으로 정렬해야합니다 여기

덜 파이썬 솔루션입니다.

관련 문제