Advertisement
jarekmor

Google_Vision_AI

Mar 7th, 2023 (edited)
1,021
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.36 KB | None | 0 0
  1. import io, os
  2. from google.cloud import vision
  3. from PIL import Image, ImageEnhance
  4.  
  5. def detect_text(image_file, credentials_file, text_area):
  6.     """Detects text in an image."""
  7.        
  8.     os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_file                 # Authenticates the client
  9.    
  10.     try:        
  11.         with Image.open(image_file, 'r') as img:        
  12.             # Crop the image    
  13.             img_cropped = img.crop(text_area)
  14.            
  15.             img_rgb = img_cropped.convert('RGB')
  16.  
  17.             # Convert the image to grayscale mode
  18.             img_gray = img_rgb.convert("L")
  19.  
  20.             # Apply thresholding to convert gray pixels to white
  21.             img_bw = img_gray.convert('L')
  22.  
  23.             # Reduce the brightness of the image
  24.             enhancer = ImageEnhance.Brightness(img_bw)
  25.             img_low_brightness = enhancer.enhance(1.5)
  26.  
  27.             # Enhance the contrast of the image
  28.             enhancer = ImageEnhance.Contrast(img_low_brightness)
  29.             img_contrast = enhancer.enhance(3)
  30.            
  31.             # Rotate the image
  32.             img_rotated = img_contrast.rotate(0, expand=True)
  33.  
  34.             # Save the modified image
  35.             img_rotated.save("contrast_image.png")
  36.        
  37.     except FileNotFoundError:
  38.             print(f"Error: File not found: {image_file}")
  39.             return None
  40.    
  41.     # Send the cropped image to the Google Cloud Vision API for text detection
  42.     client = vision.ImageAnnotatorClient()  
  43.     content = io.BytesIO()
  44.     img_contrast.save(content, format='PNG')
  45.                                            
  46.     image = vision.Image(content=content.getvalue())
  47.     response = client.text_detection(image=image)
  48.     texts = response.text_annotations
  49.  
  50.     # Handle errors
  51.     if response.error.message:
  52.         raise Exception(response.error.message)
  53.  
  54.     # Return the first detected text as a float
  55.     try:
  56.         print(float(texts[0].description))                                          # Prints the detected text (optional)                                          
  57.         return float(texts[0].description)
  58.     except IndexError:
  59.         print("No text detected in the image.")
  60.         return None
  61.  
  62. detect_text(image_file='meter.jpg', credentials_file='GoogleVisionKeys.json', text_area=(340, 135, 580, 200))      # text_area = (left, top, right, bottom)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement