|
from fastapi import APIRouter, HTTPException, Query |
|
from fastapi.responses import JSONResponse |
|
import cv2 |
|
import numpy as np |
|
import requests |
|
from PIL import Image |
|
from io import BytesIO |
|
import base64 |
|
|
|
|
|
router = APIRouter() |
|
|
|
|
|
def remove_handwritten_content(image: np.ndarray) -> np.ndarray: |
|
""" |
|
Remove conteúdo manuscrito de uma imagem usando técnicas do OpenCV. |
|
""" |
|
|
|
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
|
|
|
|
|
_, thresh = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV) |
|
|
|
|
|
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) |
|
dilated = cv2.dilate(thresh, kernel, iterations=2) |
|
|
|
|
|
result = cv2.inpaint(image, dilated, inpaintRadius=3, flags=cv2.INPAINT_TELEA) |
|
|
|
return result |
|
|
|
|
|
@router.get("/image/remove-handwriting/") |
|
def process_image(image_url: str = Query(..., description="URL da imagem para ser processada")): |
|
""" |
|
Recebe uma URL de imagem, remove conteúdo manuscrito e retorna em base64. |
|
""" |
|
try: |
|
|
|
response = requests.get(image_url) |
|
if response.status_code != 200: |
|
raise HTTPException( |
|
status_code=400, detail="Não foi possível baixar a imagem da URL fornecida." |
|
) |
|
|
|
|
|
image_array = np.asarray(bytearray(response.content), dtype=np.uint8) |
|
image = cv2.imdecode(image_array, cv2.IMREAD_COLOR) |
|
if image is None: |
|
raise HTTPException(status_code=400, detail="A URL não contém uma imagem válida.") |
|
|
|
|
|
processed_image = remove_handwritten_content(image) |
|
|
|
|
|
_, buffer = cv2.imencode('.png', processed_image) |
|
img_base64 = base64.b64encode(buffer).decode('utf-8') |
|
|
|
return JSONResponse(content={ |
|
"image_url": image_url, |
|
"processed_image_base64": f"data:image/png;base64,{img_base64}" |
|
}) |
|
|
|
except requests.exceptions.RequestException as e: |
|
raise HTTPException(status_code=400, detail=f"Erro ao acessar a URL: {str(e)}") |
|
except Exception as e: |
|
raise HTTPException(status_code=500, detail=f"Erro interno do servidor: {str(e)}") |