mirror of
https://github.com/barkeser2002/ocr-img.git
synced 2026-09-25 02:30:06 +03:00
251 lines
9.1 KiB
Python
251 lines
9.1 KiB
Python
"""
|
||
OCR Projesi - Resimlerden Metin Çıkarma
|
||
Türkçe ve İngilizce destekli, GPU optimizasyonlu
|
||
Koordinatlı PDF çıktı ile birlikte TXT formatında sonuç verir
|
||
"""
|
||
|
||
import easyocr
|
||
import os
|
||
from pathlib import Path
|
||
import cv2
|
||
import numpy as np
|
||
from PIL import Image, ImageEnhance
|
||
import logging
|
||
from fpdf import FPDF
|
||
from reportlab.pdfgen import canvas
|
||
from reportlab.lib.pagesizes import A4
|
||
from reportlab.lib import colors
|
||
from reportlab.lib.units import inch
|
||
|
||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||
|
||
print("="*60)
|
||
print(" OCR PROJESİ - METIN ÇIKARMA ARACI")
|
||
print("="*60)
|
||
print("Türkçe ve İngilizce destekli OCR sistemi")
|
||
print("Çıkış formatları: TXT, PDF (koordinatlı)")
|
||
print("="*60)
|
||
|
||
images_dir = './images'
|
||
output_dir = './out-txt'
|
||
pdf_output_dir = './out-pdf'
|
||
|
||
os.makedirs(output_dir, exist_ok=True)
|
||
os.makedirs(pdf_output_dir, exist_ok=True)
|
||
|
||
try:
|
||
import torch
|
||
gpu_available = torch.cuda.is_available()
|
||
print(f"GPU durumu: {'Kullanılıyor' if gpu_available else 'Kullanılmıyor (CPU modu)'}")
|
||
except:
|
||
gpu_available = False
|
||
print("GPU durumu: Kullanılmıyor (CPU modu)")
|
||
|
||
reader = easyocr.Reader(['tr', 'en'], gpu=gpu_available)
|
||
|
||
def optimize_image_for_ocr(image_path):
|
||
"""Görüntüyü OCR için basit optimizasyon"""
|
||
try:
|
||
image = Image.open(image_path)
|
||
|
||
if image.mode in ('RGBA', 'LA'):
|
||
background = Image.new('RGB', image.size, (255, 255, 255))
|
||
if image.mode == 'RGBA':
|
||
background.paste(image, mask=image.split()[-1])
|
||
else:
|
||
background.paste(image)
|
||
image = background
|
||
elif image.mode != 'RGB':
|
||
image = image.convert('RGB')
|
||
|
||
width, height = image.size
|
||
max_size = 2000
|
||
if width > max_size or height > max_size:
|
||
if width > height:
|
||
new_width = max_size
|
||
new_height = int(height * (max_size / width))
|
||
else:
|
||
new_height = max_size
|
||
new_width = int(width * (max_size / height))
|
||
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
||
|
||
enhancer = ImageEnhance.Contrast(image)
|
||
image = enhancer.enhance(1.1)
|
||
|
||
return image
|
||
|
||
except Exception as e:
|
||
logging.warning(f"Görüntü optimizasyonu başarısız {image_path}: {e}")
|
||
return None
|
||
|
||
def extract_text_with_coordinates(image_path):
|
||
"""Koordinatlı metin çıkarma - PDF için"""
|
||
try:
|
||
optimized_image = optimize_image_for_ocr(image_path)
|
||
if optimized_image:
|
||
img_array = np.array(optimized_image)
|
||
result_optimized = reader.readtext(img_array, detail=1)
|
||
|
||
if len(result_optimized) > 3:
|
||
logging.info(f"Optimize edilmiş görüntü kullanıldı")
|
||
return result_optimized, img_array
|
||
|
||
result_original = reader.readtext(str(image_path), detail=1)
|
||
logging.info(f"Orijinal görüntü kullanıldı")
|
||
|
||
orig_image = Image.open(image_path)
|
||
if orig_image.mode in ('RGBA', 'LA'):
|
||
background = Image.new('RGB', orig_image.size, (255, 255, 255))
|
||
if orig_image.mode == 'RGBA':
|
||
background.paste(orig_image, mask=orig_image.split()[-1])
|
||
else:
|
||
background.paste(orig_image)
|
||
orig_image = background
|
||
elif orig_image.mode != 'RGB':
|
||
orig_image = orig_image.convert('RGB')
|
||
|
||
return result_original, np.array(orig_image)
|
||
|
||
except Exception as e:
|
||
logging.error(f"OCR işlemi hatası {image_path}: {e}")
|
||
return [], None
|
||
|
||
def create_pdf_from_ocr(ocr_results, image_shape, output_path, original_image_path):
|
||
"""OCR sonuçlarından PDF oluştur"""
|
||
try:
|
||
from reportlab.pdfgen import canvas
|
||
from reportlab.lib.pagesizes import A4
|
||
from reportlab.pdfbase import pdfmetrics
|
||
from reportlab.pdfbase.ttfonts import TTFont
|
||
from reportlab.lib.colors import black
|
||
|
||
pdf_width, pdf_height = A4
|
||
|
||
img_height, img_width = image_shape[:2]
|
||
|
||
scale_x = pdf_width / img_width
|
||
scale_y = pdf_height / img_height
|
||
|
||
scale = min(scale_x, scale_y) * 0.9
|
||
|
||
c = canvas.Canvas(str(output_path), pagesize=A4)
|
||
|
||
try:
|
||
font_paths = [
|
||
"C:/Windows/Fonts/arial.ttf",
|
||
"C:/Windows/Fonts/calibri.ttf",
|
||
"C:/Windows/Fonts/tahoma.ttf"
|
||
]
|
||
for font_path in font_paths:
|
||
if os.path.exists(font_path):
|
||
pdfmetrics.registerFont(TTFont('CustomFont', font_path))
|
||
break
|
||
except:
|
||
pass
|
||
|
||
c.setFont("Helvetica-Bold", 12)
|
||
c.drawString(50, pdf_height - 50, f"OCR Çıktısı: {Path(original_image_path).stem}")
|
||
|
||
for detection in ocr_results:
|
||
if len(detection) >= 2:
|
||
bbox, text, confidence = detection[0], detection[1], detection[2] if len(detection) > 2 else 1.0
|
||
|
||
if confidence > 0.3 and text.strip():
|
||
x_coords = [point[0] for point in bbox]
|
||
y_coords = [point[1] for point in bbox]
|
||
|
||
x = min(x_coords) * scale + 50
|
||
y = pdf_height - (min(y_coords) * scale + 100)
|
||
|
||
text_width = (max(x_coords) - min(x_coords)) * scale
|
||
text_height = (max(y_coords) - min(y_coords)) * scale
|
||
|
||
font_size = max(6, min(12, text_height * 0.7))
|
||
|
||
try:
|
||
c.setFont("CustomFont", font_size)
|
||
except:
|
||
c.setFont("Helvetica", font_size)
|
||
|
||
c.setFillColor(black)
|
||
|
||
try:
|
||
c.drawString(x, y, text[:100])
|
||
except:
|
||
safe_text = text.encode('latin-1', 'ignore').decode('latin-1')
|
||
c.drawString(x, y, safe_text[:100])
|
||
|
||
c.save()
|
||
logging.info(f"PDF başarıyla oluşturuldu: {output_path}")
|
||
return True
|
||
|
||
except Exception as e:
|
||
logging.error(f"PDF oluşturma hatası {output_path}: {e}")
|
||
return False
|
||
|
||
image_extensions = ['.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.tif']
|
||
image_files = []
|
||
|
||
for ext in image_extensions:
|
||
image_files.extend(Path(images_dir).glob(f'*{ext}'))
|
||
image_files.extend(Path(images_dir).glob(f'*{ext.upper()}'))
|
||
|
||
print(f"Toplam {len(image_files)} resim dosyası bulundu.")
|
||
|
||
if len(image_files) == 0:
|
||
print("⚠️ UYARI: 'images' klasöründe hiç resim dosyası bulunamadı!")
|
||
print(" Lütfen işlemek istediğiniz resimleri 'images' klasörüne koyun.")
|
||
print(" Desteklenen formatlar: PNG, JPG, JPEG, BMP, TIFF")
|
||
input(" Devam etmek için Enter tuşuna basın...")
|
||
exit()
|
||
|
||
for i, image_path in enumerate(image_files, 1):
|
||
try:
|
||
print(f"\n[{i}/{len(image_files)}] İşleniyor: {image_path.name}")
|
||
|
||
ocr_results, image_array = extract_text_with_coordinates(image_path)
|
||
|
||
extracted_text = []
|
||
for detection in ocr_results:
|
||
if len(detection) >= 2:
|
||
text = detection[1]
|
||
if isinstance(text, str) and text.strip():
|
||
extracted_text.append(text.strip())
|
||
|
||
|
||
cleaned_text = []
|
||
for text in extracted_text:
|
||
if text and len(text) > 1:
|
||
cleaned = ' '.join(text.split())
|
||
cleaned_text.append(cleaned)
|
||
|
||
output_filename = image_path.stem + '.txt'
|
||
output_path = Path(output_dir) / output_filename
|
||
|
||
with open(output_path, 'w', encoding='utf-8') as f:
|
||
f.write('\n'.join(cleaned_text))
|
||
|
||
pdf_filename = image_path.stem + '.pdf'
|
||
pdf_output_path = Path(pdf_output_dir) / pdf_filename
|
||
|
||
if image_array is not None and len(ocr_results) > 0:
|
||
pdf_success = create_pdf_from_ocr(ocr_results, image_array.shape, pdf_output_path, image_path)
|
||
else:
|
||
pdf_success = False
|
||
|
||
print(f"✓ Kaydedildi: {output_filename}")
|
||
print(f" Çıkarılan metin satırı sayısı: {len(cleaned_text)}")
|
||
|
||
if pdf_success:
|
||
print(f"✓ PDF oluşturuldu: {pdf_filename}")
|
||
else:
|
||
print(f"✗ PDF oluşturulamadı: {pdf_filename}")
|
||
if cleaned_text:
|
||
preview = cleaned_text[0][:100] + "..." if len(cleaned_text[0]) > 100 else cleaned_text[0]
|
||
print(f" Önizleme: {preview}")
|
||
|
||
except Exception as e:
|
||
print(f"✗ Hata oluştu {image_path.name}: {str(e)}")
|
||
logging.error(f"İşlem hatası {image_path.name}: {e}")
|
||
|
||
print(f"\n🎉 Tüm işlemler tamamlandı! Metin dosyaları '{output_dir}' klasöründe, PDF dosyaları '{pdf_output_dir}' klasöründe.") |