Unable to extract text from image - Python

49 Views Asked by At

I am trying to get the Buy/Sell signals in a screenshot of a Tradingview chart. The image will look like this:

enter image description here

The code i've been using to do screenshot, read text, invert colors and get the latest signal:

import time
import pyautogui
from PIL import Image
from PIL import ImageOps
import pytesseract

capture_interval = 10 

crop_coordinates = (1548, 176, 1782, 870)  # (x_start, y_start, x_end, y_end)

while True:
    screenshot = pyautogui.screenshot()

    cropped_screenshot = screenshot.crop(crop_coordinates)
    inverted_screenshot = ImageOps.invert(cropped_screenshot)

    inverted_screenshot.save('cropped_screenshot.png')

    img = Image.open('cropped_screenshot.png')

    text_in_image = pytesseract.image_to_string(img)

    lines = text_in_image.split('\n')

    # Find the last line containing "buy" or "sell"
    last_signal = None
    for line in reversed(lines):
        if "Buy" in line.lower():
            last_signal = "Buy"
            break
        elif "Sell" in line.lower():
            last_signal = "Sell"
            break

    # Save the last signal to a text file
    if last_signal:
        with open('last_signal.txt', 'w') as file:
            file.write(last_signal)

        # Print the last signal
        print(f"Last signal detected: {last_signal}")
    else:
        print("No signals detected.")

    # Wait before the next screenshot
    time.sleep(capture_interval)

Doesn't seem to work. I've also tried adjusting, resizing, removing noise, using cv2, but unsuccessfully.

Can anyone help?

Thanks!

0

There are 0 best solutions below