Advertisement
jarekmor

VisionAI_2

Mar 5th, 2023
825
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. import io, os
  2. from google.cloud import vision
  3. from PIL import Image
  4.  
  5. def crop_image(image, text_area):
  6.     """Crops an image to a specified area."""
  7.     return image.crop(text_area)
  8.  
  9. def detect_text(image_file, credentials_file, text_area):
  10.     """Detects text in an image."""
  11.     os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_file                 # Authenticates the client
  12.  
  13.     # Open the image file
  14.     try:
  15.         with open(image_file, 'rb') as f:
  16.             image_data = f.read()
  17.     except FileNotFoundError:
  18.         print(f"Error: File not found: {image_file}")
  19.         return None
  20.  
  21.     # Crop the image
  22.     image = Image.open(io.BytesIO(image_data))
  23.     cropped_image = crop_image(image, text_area)
  24.  
  25.     # Send the cropped image to the Google Cloud Vision API for text detection
  26.     client = vision.ImageAnnotatorClient()
  27.     content = io.BytesIO()
  28.     cropped_image.save(content, format='JPEG')
  29.     image = vision.Image(content=content.getvalue())
  30.     response = client.text_detection(image=image)
  31.     texts = response.text_annotations
  32.  
  33.     # Handle errors
  34.     if response.error.message:
  35.         raise Exception(response.error.message)
  36.  
  37.     # Return the first detected text as a float
  38.     try:
  39.         print(float(texts[0].description))                                          # Print the detected text
  40.         return float(texts[0].description)
  41.     except IndexError:
  42.         print("No text detected in the image.")
  43.         return None
  44.  
  45. detect_text('meter_digits.jpg', 'GoogleVisionKeys.json', (270, 195, 720, 280))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement