2017-05-11 30 views
0

내가하려는 것은 pyautogui로 숫자의 스크린 샷을 만들고 pytesseract를 사용하여 숫자를 문자열로 변환하는 것입니다. 코드 : 수입 pyautogui 수입 시간 수입 PIL PIL 가져 오기 이미지 수입 pytesseractPytesseract는 pyautogui 스크린 샷을 허용하지 않습니다. Windows, Python 3.6

pytesseract.pytesseract.tesseract_cmd = 'C://Program Files (x86)//Tesseract-OCR//tesseract' 

# Create image 
time.sleep(5) 
image = pyautogui.screenshot('projects/output.png', region=(1608, 314, 57, 41)) 

# Resize image 
basewidth = 2000 
img = Image.open('projects/output.png') 
wpercent = (basewidth/float(img.size[0])) 
hsize = int((float(img.size[1])*float(wpercent))) 
img = img.resize((basewidth,hsize), PIL.Image.ANTIALIAS) 
img.save('projects/output.png') 

col = Image.open('projects/output.png') 
gray = col.convert('L') 
bw = gray.point(lambda x: 0 if x<128 else 255, '1') 
bw.save('projects/output.png') 

# Image to string 
screen = Image.open('projects/output.png') 

print(pytesseract.image_to_string(screen, config='tessedit_char_whitelist=')) 

에서 지금은 스크린 샷 pyautogui을 허용하지 않는 pytesseract (가) 작성하는 것 같다. 코드는 문제없이 잘 실행되지만 빈 문자열을 인쇄합니다. 그러나 만약 페인트로 이미지를 만들고 그것을 마치 'screens.png'과 같은 정확한 폴더에 저장하면 제대로 동작합니다.

Image output after resize and adjustments

사람은 내가 뭔가를 누락 아이디어가있다?

답변

0

경로를 수정하고 다음과 같은 시도 :

import numpy as np 
from numpy import * 
from PIL import Image 
from PIL import * 
import pytesseract 
import cv2 


src_path = "C:\\Users\\USERNAME\\Documents\\OCR\\" 

def get_region(box): 
    #Grabs the region of the box coordinates 
    im = ImageGrab.grab(box) 
    #Change size of image to 200% of the original size 
    a, b, c, d = box 
    doubleX = (c - a) * 2 
    doubleY = (d - b) * 2 
    im.resize((doubleX, doubleY)).save(os.getcwd() + "\\test.png", 'PNG') 

def get_string(img_path): 
    # Read image with opencv 
    img = cv2.imread(img_path) 
    # Convert to gray 
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    # Apply dilation and erosion to remove some noise 
    kernel = np.ones((1, 1), np.uint8) 
    img = cv2.dilate(img, kernel, iterations=1) 
    img = cv2.erode(img, kernel, iterations=1) 
    # Write image after removed noise 
    cv2.imwrite(src_path + "removed_noise.png", img) 
    # Apply threshold to get image with only black and white 
    #img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2) 
    # Write the image after apply opencv to do some ... 
    cv2.imwrite(src_path + "thres.png", img) 
    # Recognize text with tesseract for python 

    result = pytesseract.image_to_string(Image.open(src_path + "thres.png")) 

    return result 

def main(): 
    #Grab the region of the screenshot (box area) 
    region = (1354,630,1433,648) 
    get_region(region) 

    #Output results 
    print ("OCR Output: ") 
    print (get_string(src_path + "test.png"))