• bitcoinBitcoin(BTC)$77,861.000.63%
  • ethereumEthereum(ETH)$2,262.550.50%
  • tetherTether(USDT)$1.00-0.04%
  • binancecoinBNB(BNB)$707.200.71%
  • rippleXRP(XRP)$1.25-0.07%
  • usd-coinUSDC(USDC)$1.00-0.03%
  • solanaSolana(SOL)$94.26-1.38%
  • tronTRON(TRX)$0.3128782.74%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.082.99%
  • HyperliquidHyperliquid(HYPE)$87.06-0.97%
  • zcashZcash(ZEC)$1,219.86-3.89%
  • dogecoinDogecoin(DOGE)$0.075250-0.60%
  • moneroMonero(XMR)$595.85-0.35%
  • USDSUSDS(USDS)$1.00-0.05%
  • whitebitWhiteBIT Coin(WBT)$74.700.53%
  • chainlinkChainlink(LINK)$11.37-3.63%
  • leo-tokenLEO Token(LEO)$9.370.43%
  • cardanoCardano(ADA)$0.192017-0.34%
  • stellarStellar(XLM)$0.167358-1.38%
  • bitcoin-cashBitcoin Cash(BCH)$281.57-0.99%
  • nearNEAR Protocol(NEAR)$4.27-3.37%
  • RainRain(RAIN)$0.00700611.71%
  • daiDai(DAI)$1.00-0.04%
  • Ethena USDeEthena USDe(USDE)$1.00-0.06%
  • uniswapUniswap(UNI)$7.150.40%
  • litecoinLitecoin(LTC)$55.52-0.53%
  • CantonCanton(CC)$0.0977800.27%
  • USD1USD1(USD1)$1.00-0.04%
  • avalanche-2Avalanche(AVAX)$8.681.32%
  • suiSui(SUI)$0.89-0.56%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.210.95%
  • hedera-hashgraphHedera(HBAR)$0.071296-1.35%
  • tether-goldTether Gold(XAUT)$3,874.240.05%
  • Global DollarGlobal Dollar(USDG)$1.00-0.03%
  • quant-networkQuant(QNT)$199.760.24%
  • paypal-usdPayPal USD(PYUSD)$1.00-0.05%
  • shiba-inuShiba Inu(SHIB)$0.0000050.11%
  • BittensorBittensor(TAO)$232.88-1.66%
  • crypto-com-chainCronos(CRO)$0.051090-0.89%
  • Ripple USDRipple USD(RLUSD)$1.00-0.03%
  • EthenaEthena(ENA)$0.181262-4.10%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.15-0.13%
  • okbOKB(OKB)$113.923.38%
  • Circle USYCCircle USYC(USYC)$1.140.00%
  • aaveAave(AAVE)$133.820.12%
  • pepePepe(PEPE)$0.000005-1.82%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • OndoOndo(ONDO)$0.401955-1.80%
  • MemeCoreMemeCore(M)$0.84-7.34%
  • Pump.funPump.fun(PUMP)$0.004136-1.43%
TradePoint.io
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop
No Result
View All Result
TradePoint.io
No Result
View All Result

How to Build a Multilingual OCR AI Agent in Python with EasyOCR and OpenCV

September 12, 2025
in AI & Technology
Reading Time: 4 mins read
A A
How to Build a Multilingual OCR AI Agent in Python with EasyOCR and OpenCV
ShareShareShareShareShare
class AdvancedOCRAgent:
   """
   Advanced OCR AI Agent with preprocessing, multi-language support,
   and intelligent text extraction capabilities.
   """
  
   def __init__(self, languages: List[str] = ['en'], gpu: bool = True):
       """Initialize OCR agent with specified languages."""
       print("🤖 Initializing Advanced OCR Agent...")
       self.languages = languages
       self.reader = easyocr.Reader(languages, gpu=gpu)
       self.confidence_threshold = 0.5
       print(f"✅ OCR Agent ready! Languages: {languages}")
  
   def upload_image(self) -> Optional[str]:
       """Upload image file through Colab interface."""
       print("📁 Upload your image file:")
       uploaded = files.upload()
       if uploaded:
           filename = list(uploaded.keys())[0]
           print(f"✅ Uploaded: {filename}")
           return filename
       return None
  
   def preprocess_image(self, image: np.ndarray, enhance: bool = True) -> np.ndarray:
       """Advanced image preprocessing for better OCR accuracy."""
       if len(image.shape) == 3:
           gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
       else:
           gray = image.copy()
      
       if enhance:
           clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
           gray = clahe.apply(gray)
          
           gray = cv2.fastNlMeansDenoising(gray)
          
           kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
           gray = cv2.filter2D(gray, -1, kernel)
      
       binary = cv2.adaptiveThreshold(
           gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2
       )
      
       return binary
  
   def extract_text(self, image_path: str, preprocess: bool = True) -> Dict:
       """Extract text from image with advanced processing."""
       print(f"🔍 Processing image: {image_path}")
      
       image = cv2.imread(image_path)
       if image is None:
           raise ValueError(f"Could not load image: {image_path}")
      
       if preprocess:
           processed_image = self.preprocess_image(image)
       else:
           processed_image = image
      
       results = self.reader.readtext(processed_image)
      
       extracted_data = {
           'raw_results': results,
           'filtered_results': [],
           'full_text': '',
           'confidence_stats': {},
           'word_count': 0,
           'line_count': 0
       }
      
       high_confidence_text = []
       confidences = []
      
       for (bbox, text, confidence) in results:
           if confidence >= self.confidence_threshold:
               extracted_data['filtered_results'].append({
                   'text': text,
                   'confidence': confidence,
                   'bbox': bbox
               })
               high_confidence_text.append(text)
               confidences.append(confidence)
      
       extracted_data['full_text'] = ' '.join(high_confidence_text)
       extracted_data['word_count'] = len(extracted_data['full_text'].split())
       extracted_data['line_count'] = len(high_confidence_text)
      
       if confidences:
           extracted_data['confidence_stats'] = {
               'mean': np.mean(confidences),
               'min': np.min(confidences),
               'max': np.max(confidences),
               'std': np.std(confidences)
           }
      
       return extracted_data
  
   def visualize_results(self, image_path: str, results: Dict, show_bbox: bool = True):
       """Visualize OCR results with bounding boxes."""
       image = cv2.imread(image_path)
       image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
      
       plt.figure(figsize=(15, 10))
      
       if show_bbox:
           plt.subplot(2, 2, 1)
           img_with_boxes = image_rgb.copy()
          
           for item in results['filtered_results']:
               bbox = np.array(item['bbox']).astype(int)
               cv2.polylines(img_with_boxes, [bbox], True, (255, 0, 0), 2)
              
               x, y = bbox[0]
               cv2.putText(img_with_boxes, f"{item['confidence']:.2f}",
                          (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)
          
           plt.imshow(img_with_boxes)
           plt.title("OCR Results with Bounding Boxes")
           plt.axis('off')
      
       plt.subplot(2, 2, 2)
       processed = self.preprocess_image(image)
       plt.imshow(processed, cmap='gray')
       plt.title("Preprocessed Image")
       plt.axis('off')
      
       plt.subplot(2, 2, 3)
       confidences = [item['confidence'] for item in results['filtered_results']]
       if confidences:
           plt.hist(confidences, bins=20, alpha=0.7, color="blue")
           plt.xlabel('Confidence Score')
           plt.ylabel('Frequency')
           plt.title('Confidence Score Distribution')
           plt.axvline(self.confidence_threshold, color="red", linestyle="--",
                      label=f'Threshold: {self.confidence_threshold}')
           plt.legend()
      
       plt.subplot(2, 2, 4)
       stats = results['confidence_stats']
       if stats:
           labels = ['Mean', 'Min', 'Max']
           values = [stats['mean'], stats['min'], stats['max']]
           plt.bar(labels, values, color=['green', 'red', 'blue'])
           plt.ylabel('Confidence Score')
           plt.title('Confidence Statistics')
           plt.ylim(0, 1)
      
       plt.tight_layout()
       plt.show()
  
   def smart_text_analysis(self, text: str) -> Dict:
       """Perform intelligent analysis of extracted text."""
       analysis = {
           'language_detection': 'unknown',
           'text_type': 'unknown',
           'key_info': {},
           'patterns': []
       }
      
       email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
       phone_pattern = r'(\+\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}'
       url_pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
       date_pattern = r'\b\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b'
      
       patterns = {
           'emails': re.findall(email_pattern, text, re.IGNORECASE),
           'phones': re.findall(phone_pattern, text),
           'urls': re.findall(url_pattern, text, re.IGNORECASE),
           'dates': re.findall(date_pattern, text)
       }
      
       analysis['patterns'] = {k: v for k, v in patterns.items() if v}
      
       if any(patterns.values()):
           if patterns.get('emails') or patterns.get('phones'):
               analysis['text_type'] = 'contact_info'
           elif patterns.get('urls'):
               analysis['text_type'] = 'web_content'
           elif patterns.get('dates'):
               analysis['text_type'] = 'document_with_dates'
      
       if re.search(r'[а-яё]', text.lower()):
           analysis['language_detection'] = 'russian'
       elif re.search(r'[àáâãäåæçèéêëìíîïñòóôõöøùúûüý]', text.lower()):
           analysis['language_detection'] = 'romance_language'
       elif re.search(r'[一-龯]', text):
           analysis['language_detection'] = 'chinese'
       elif re.search(r'[ひらがなカタカナ]', text):
           analysis['language_detection'] = 'japanese'
       elif re.search(r'[a-zA-Z]', text):
           analysis['language_detection'] = 'latin_based'
      
       return analysis
  
   def process_batch(self, image_folder: str) -> List[Dict]:
       """Process multiple images in batch."""
       results = []
       supported_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff')
      
       for filename in os.listdir(image_folder):
           if filename.lower().endswith(supported_formats):
               image_path = os.path.join(image_folder, filename)
               try:
                   result = self.extract_text(image_path)
                   result['filename'] = filename
                   results.append(result)
                   print(f"✅ Processed: {filename}")
               except Exception as e:
                   print(f"❌ Error processing {filename}: {str(e)}")
      
       return results
  
   def export_results(self, results: Dict, format: str="json") -> str:
       """Export results in specified format."""
       if format.lower() == 'json':
           output = json.dumps(results, indent=2, ensure_ascii=False)
           filename="ocr_results.json"
       elif format.lower() == 'txt':
           output = results['full_text']
           filename="extracted_text.txt"
       else:
           raise ValueError("Supported formats: 'json', 'txt'")
      
       with open(filename, 'w', encoding='utf-8') as f:
           f.write(output)
      
       print(f"📄 Results exported to: {filename}")
       return filename

Credit: Source link

YOU MAY ALSO LIKE

This Hidden Windows 11 Menu Can Save You Valuable Time When Troubleshooting

Which Is Better for Turning Videos Into Shorts? – Unite.AI

ShareTweetSendSharePin

Related Posts

This Hidden Windows 11 Menu Can Save You Valuable Time When Troubleshooting
AI & Technology

This Hidden Windows 11 Menu Can Save You Valuable Time When Troubleshooting

November 1, 2026
Which Is Better for Turning Videos Into Shorts? – Unite.AI
AI & Technology

Which Is Better for Turning Videos Into Shorts? – Unite.AI

November 1, 2026
Affle Signs Definitive Agreement to Acquire Ad Tech Company Perion – Unite.AI
AI & Technology

Affle Signs Definitive Agreement to Acquire Ad Tech Company Perion – Unite.AI

November 1, 2026
Here’s What Your Fitbit Heart Rate Variability Actually Tells You
AI & Technology

Here’s What Your Fitbit Heart Rate Variability Actually Tells You

November 1, 2026
Next Post
Winklevoss’ Gemini stock jumps 32% in Nasdaq debut after pricing IPO above range

Winklevoss' Gemini stock jumps 32% in Nasdaq debut after pricing IPO above range

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

No Result
View All Result
Trump responds to potential U.S. involvement after Saudi attack

Trump responds to potential U.S. involvement after Saudi attack

October 28, 2026
Trump faces ‘bipartisan pushback’ on diesel deal with Russia as he tries to lower prices

Trump faces ‘bipartisan pushback’ on diesel deal with Russia as he tries to lower prices

October 27, 2026
What Is Chunking in RAG? How Document Splitting Shapes Answer Quality – Unite.AI

What Is Chunking in RAG? How Document Splitting Shapes Answer Quality – Unite.AI

November 1, 2026

About

Learn more

Our Services

Legal

Privacy Policy

Terms of Use

Bloggers

Learn more

Article Links

Contact

Advertise

Ask us anything

©2020- TradePoint.io - All rights reserved!

Tradepoint.io, being just a publishing and technology platform, is not a registered broker-dealer or investment adviser. So we do not provide investment advice. Rather, brokerage services are provided to clients of Tradepoint.io by independent SEC-registered broker-dealers and members of FINRA/SIPC. Every form of investing carries some risk and past performance is not a guarantee of future results. “Tradepoint.io“, “Instant Investing” and “My Trading Tools” are registered trademarks of Apperbuild, LLC.

This website is operated by Apperbuild, LLC. We have no link to any brokerage firm and we do not provide investment advice. Every information and resource we provide is solely for the education of our readers. © 2020 Apperbuild, LLC. All rights reserved.

No Result
View All Result
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop

© 2023 - TradePoint.io - All Rights Reserved!