Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- import pytesseract
- from PIL import ImageGrab
- def ExtractText(img):
- return pytesseract.image_to_string(img, config='-c tessedit_char_whitelist=WASD --psm 13')
- def GetBoxStartPos(img):
- for x in range(0, 50):
- for y in range(0, 50):
- r, g, b = img[x, y]
- color = int(r) + int(g) + int(b)
- if color < pixel_color_threshold:
- return (x+8, y+7)
- return (8, 7)
- def ProcessImage(ind):
- # USE BELOW TO GET FILE FROM DISK
- # img_ori = cv2.imread('images/bdo_letters{0}.jpg'.format(ind))
- # img_ori = img_ori[330:430, 750:1160]
- # USE BELOW FOR SCREENSHOT
- img_ori = ImageGrab.grab().crop(image_areas['letters']).convert('RGB') # crop image from screenshot
- img_ori = np.array(img_ori) # convert to cv2 image
- img_ori = img_ori[:, :, ::-1].copy()
- pos = GetBoxStartPos(img_ori) # get start pos of letters
- box = img_ori[pos[0]:pos[0]+y_len, pos[1]:pos[1]+x_len]
- # join letters to remove gaps between
- letters = []
- for i in range(0, 10):
- x_pos = i*l_len + i*gap_len
- letter = box[:, x_pos:x_pos+l_len]
- letters.append(letter)
- box_format = cv2.hconcat(letters)
- # box_format = cv2.cvtColor(box_format, cv2.COLOR_BGR2GRAY) # convert to grayscale
- # img1 = cv2.threshold(box_format,128,255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)[1]
- # img_gauss = cv2.GaussianBlur(box_format,(3,3),0) # gaussian filter (optional)
- # img2 = cv2.threshold(img_gauss,128,255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)[1]
- cv2.imwrite('img_original_{0}.jpg'.format(ind), box_format)
- # cv2.imwrite('img_processed2_{0}.jpg'.format(ind), img2)
- text = ExtractText(box_format)
- print(text)
- # text = ExtractText(img2)
- # print(text)
- image_areas = {
- 'bite': (720, 55, 890, 80),
- 'letters': (750, 330, 1160, 430),
- }
- pixel_color_threshold = 200
- x_len = 355
- y_len = 22
- l_len = 18
- gap_len = 19
- pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract'
- # ProcessImage(8)
- for i in range(1, 9):
- print('-- PROCESSING IMAGE {0} --'.format(i))
- ProcessImage(i)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement