2013-10-04 2 views
3

텍스트가있는 이미지가 있습니다. OCR로 이미지를 보내고 싶지만 이미지에 약간의 흰색 노이즈가있어 OCR 결과가 그렇게 좋지 않습니다. 나는 이미지를 침식/팽창 시키려고 노력했지만 완벽한 임계 값을 얻지 못했습니다. 이미지의 모든 텍스트가 완벽하게 수평이 될 것이므로 Hough Transform을 시도했습니다.opencv에서 이미지 자르기

다음은 OpenCV에 번들 된 샘플 변형 프로그램을 실행할 때의 이미지입니다.

상담자 블랙 아웃 제외한 모든 빨간색 선은 어떻게

  • ? 또는 빨간색 선으로 강조 표시된 영역 각각에 대해 별도의 이미지를자를 수 있습니까?

  • 나는 수평선에만 집중하고 싶다. 나는 대각선을 버릴 수있다.

OCR로 보낼 때 두 가지 옵션 중 하나를 사용할 수 있습니다. 그러나 어느 것이 가장 좋은 결과를 가져올 지 알아보기 위해 노력하고 싶습니다. 출력

답변

2

하우투/s의

  • 어떻게 붉은 선은 제외 블랙 아웃 모든입니다 수 있습니까?
  • dotess2()
  • ['Footel text goes he: e\n', 'Some mole hele\n', 'Some Text Here\n']
    • 또는 어떻게 빨간색 선으로 강조 각 영역에 대해 별도의 이미지를자를 수 있습니다?
    • ['Foolel text goes he: e\n', 'Some mole hele\n', 'Some Text Here\n', 'Directions\n']
      • dotess1()

    코드

    # -*- coding: utf-8 -*- 
    import cv2 
    import numpy as np 
    import math 
    import subprocess 
    import os 
    import operator 
    
    #some clean up/init blah blah 
    junk='\/,-‘’“ ”?.\';!{§[email protected]#$%^&*()_+-|:}»£[]¢€¥°><' 
    tmpdir='./tmp' 
    if not os.path.exists(tmpdir): 
        os.makedirs(tmpdir) 
    for path, subdirs, files in os.walk(tmpdir): 
        for name in files: 
         os.remove(os.path.join(path, name))  
    
    #when the preprocessor is not pefect, there will be junk in the result. this is a crude mean of ridding them off 
    def resfilter(res): 
        rd = dict() 
        for l in set(res): 
         rd[l]=0. 
    
        for l in rd: 
         for i in l: 
          if i in junk: 
           rd[l]-=1 
          elif i.isdigit(): 
           rd[l]+=.5 
          else: 
           rd[l]+=1 
        ret=[] 
        for v in sorted(rd.iteritems(), key=operator.itemgetter(1), reverse=True): 
         ret.append(v[0]) 
        return ret 
    
    def dotess1(): 
        res =[] 
        for path, subdirs, files in os.walk(tmpdir): 
         for name in files: 
          fpath = os.path.join(path, name) 
          img = cv2.imread(fpath) 
          gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 
    
          ''' 
          #if the text is too small/contains noise etc, resize and maintain aspect ratio 
          if gray.shape[1]<100: 
           gray=cv2.resize(gray,(int(100/gray.shape[0]*gray.shape[1]),100)) 
          '''  
          cv2.imwrite('tmp.jpg',gray) 
          args = ['tesseract.exe','tmp.jpg','tessres','-psm','7', '-l','eng'] 
          subprocess.call(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
          with open('tessres.txt') as f: 
            for line in f: 
             if line.strip() != '': 
              res.append(line) 
        print resfilter(res) 
    
    
    def dotess2(): 
        res =[] 
        args = ['tesseract.exe','clean.jpg','tessres','-psm','3', '-l','eng'] 
        subprocess.call(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
        with open('tessres.txt') as f: 
          for line in f: 
           if line.strip() != '': 
            res.append(line) 
        print resfilter(res) 
    
    ''' 
    start of code 
    ''' 
    img = cv2.imread('c:/data/ocr3.png') 
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 
    canny=cv2.Canny(gray,50,200,3) 
    cv2.imshow('canny',canny) 
    
    #remove the actual horizontal lines so that hough wont detect them 
    linek = np.zeros((11,11),dtype=np.uint8) 
    linek[5,...]=1 
    x=cv2.morphologyEx(canny, cv2.MORPH_OPEN, linek ,iterations=1) 
    canny-=x 
    cv2.imshow('canny no horizontal lines',canny) 
    
    #draw a fat line so that you can box it up 
    lines = cv2.HoughLinesP(canny, 1, math.pi/2, 50,50, 50, 20) 
    linemask = np.zeros(gray.shape,gray.dtype) 
    for line in lines[0]: 
        if line[1]==line[3]:#check horizontal 
         pt1 = (line[0],line[1]) 
         pt2 = (line[2],line[3]) 
         cv2.line(linemask, pt1, pt2, (255), 30) 
    
    cv2.imshow('linemask',linemask) 
    
    ''' 
    * two methods of doing ocr,line mode and page mode 
    * boxmask is used to so that a clean image can be saved for page mode 
    * for every detected boxes, the roi are cropped and saved so that tess3 can be run in line mode 
    ''' 
    
    boxmask = np.zeros(gray.shape,gray.dtype) 
    contours,hierarchy = cv2.findContours(linemask,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) 
    idx=0 
    for cnt in contours: 
        idx+=1 
        area = cv2.contourArea(cnt) 
        x,y,w,h = cv2.boundingRect(cnt) 
        roi=img[y:y+h,x:x+w].copy() 
        cv2.imwrite('%s/%s.jpg'%(tmpdir,str(idx)),roi) 
        cv2.rectangle(boxmask,(x,y),(x+w,y+h),(255),-1) 
    
    
    cv2.imshow('clean',img&cv2.cvtColor(boxmask,cv2.COLOR_GRAY2BGR)) 
    cv2.imwrite('clean.jpg',img&cv2.cvtColor(boxmask,cv2.COLOR_GRAY2BGR)) 
    cv2.imshow('img',img) 
    
    dotess1() 
    dotess2() 
    cv2.waitKey(0) 
    
  • +1

    당신이 (위키하지, 그 끔찍한 엉망) 사진을 포함하는 온라인 문서를 읽을 수 있습니다. 이것 같이 http://www.cs.ukzn.ac.za/~sviriri/COMP702/COMP702-6.pdf. diff struct 요소로 opencv에서 morph op를 시도해보십시오.이 경우에는 선만 남기를 원하므로 구조체 요소에는 a @ line이 있어야합니다. 그럴 필요는 없습니다 (11,11). (11,9), (15,11) 가운데 한 줄로 모든 것이 작동해야합니다. 행렬의 최소 너비를 행렬 크기로 지정합니다. 더 두꺼운 줄은'linek [4, ...] = 1; linek [5, ...] = 1; linek [6, ...] = 1'과 같이 두꺼운 줄을 지정함으로써 감지 될 수있다. –