{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyN3sXgjcD0FwZNPr2Ilj90g"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["#Taller de OCR"],"metadata":{"id":"FsxoUo9VNTtq"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"q4E8kncQNR3P"},"outputs":[],"source":["# ============================================================\n","# OCR de una imagen almacenada en Google Drive usando Tesseract\n","# ============================================================\n","\n","# 1. Montar Google Drive\n","from google.colab import drive\n","drive.mount('/content/drive')"]},{"cell_type":"code","source":["# 2. Instalar Tesseract y librerías necesarias\n","\n","!apt-get update\n","!apt-get install -y tesseract-ocr\n","!apt-get install -y tesseract-ocr-spa\n","!pip install pytesseract pillow opencv-python matplotlib"],"metadata":{"id":"LFBrpTfvYq9f"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 3. Importar librerías\n","\n","from PIL import Image\n","import pytesseract\n","import cv2\n","import matplotlib.pyplot as plt\n","import os"],"metadata":{"id":"v6amrOi1Yzi6"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 4. Definir la ruta de la imagen en Google Drive\n","# Cambia esta ruta por la localización real de tu archivo\n","\n","image_path = \"/content/drive/MyDrive/Colab Notebooks/Taller OCR/Bases de Datos/Scan_Doc1LQ.jpg\"\n","\n","# Comprobar que el archivo existe\n","if not os.path.exists(image_path):\n","    raise FileNotFoundError(f\"No se ha encontrado el archivo: {image_path}\")\n","\n","print(\"Archivo encontrado:\", image_path)"],"metadata":{"id":"3HU8LuiuY7fF"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 5. Abrir y visualizar la imagen original\n","\n","img = Image.open(image_path)\n","\n","plt.figure(figsize=(10, 12))\n","plt.imshow(img)\n","plt.axis(\"off\")\n","plt.title(\"Imagen original\")\n","plt.show()"],"metadata":{"id":"-0U_xrKyY-8c"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 6. Aplicar OCR directamente con Tesseract\n","\n","texto_ocr = pytesseract.image_to_string(\n","    img,\n","    lang=\"spa\"\n",")\n","\n","print(\"===== TEXTO EXTRAÍDO =====\\n\")\n","print(texto_ocr)"],"metadata":{"id":"qMb8t4yHZQ2B"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 7. Guardar el resultado en un archivo TXT en Google Drive\n","\n","output_path = \"/content/drive/MyDrive/Colab Notebooks/Taller OCR/resultado_ocr.txt\"\n","\n","with open(output_path, \"w\", encoding=\"utf-8\") as f:\n","    f.write(texto_ocr)\n","\n","print(\"Texto guardado en:\")\n","print(output_path)"],"metadata":{"id":"SwuZVqjfZUx3"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# ============================================================\n","# OCR con preprocesado básico de imagen\n","# ============================================================\n","\n","# Leer imagen con OpenCV\n","img_cv = cv2.imread(image_path)\n","\n","# Convertir a escala de grises\n","gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)\n","\n","# Binarización automática con Otsu\n","_, thresh = cv2.threshold(\n","    gray,\n","    0,\n","    255,\n","    cv2.THRESH_BINARY + cv2.THRESH_OTSU\n",")\n","\n","# Visualizar imagen preprocesada\n","plt.figure(figsize=(10, 12))\n","plt.imshow(thresh, cmap=\"gray\")\n","plt.axis(\"off\")\n","plt.title(\"Imagen preprocesada\")\n","plt.show()"],"metadata":{"id":"EEBHLSM7ZY9j"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Aplicar OCR sobre la imagen preprocesada\n","\n","texto_ocr_preprocesado = pytesseract.image_to_string(\n","    thresh,\n","    lang=\"spa\"\n",")\n","\n","print(\"===== TEXTO EXTRAÍDO CON PREPROCESADO =====\\n\")\n","print(texto_ocr_preprocesado)"],"metadata":{"id":"c6vDT1gMZbye"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Guardar resultado preprocesado\n","\n","output_path_pre = \"/content/drive/MyDrive/Colab Notebooks/Taller OCR/resultado_ocr_preprocesado.txt\"\n","\n","with open(output_path_pre, \"w\", encoding=\"utf-8\") as f:\n","    f.write(texto_ocr_preprocesado)\n","\n","print(\"Texto preprocesado guardado en:\")\n","print(output_path_pre)"],"metadata":{"id":"CcZX3WpLZhP9"},"execution_count":null,"outputs":[]}]}