|
import streamlit as st |
|
from streamlit_webrtc import webrtc_streamer, WebRtcMode, RTCConfiguration |
|
from PIL import Image |
|
import av |
|
import os |
|
import numpy as np |
|
|
|
st.title("Captura y sube una imagen desde tu cámara") |
|
|
|
|
|
SAVE_DIR = "uploaded_images" |
|
if not os.path.exists(SAVE_DIR): |
|
os.makedirs(SAVE_DIR) |
|
|
|
|
|
def contar_imagenes(directorio): |
|
return len([f for f in os.listdir(directorio) if os.path.isfile(os.path.join(directorio, f))]) |
|
|
|
|
|
def eliminar_imagenes(directorio): |
|
for f in os.listdir(directorio): |
|
file_path = os.path.join(directorio, f) |
|
try: |
|
if os.path.isfile(file_path): |
|
os.unlink(file_path) |
|
except Exception as e: |
|
st.error(f"No se pudo eliminar {file_path}. Error: {e}") |
|
|
|
|
|
MAX_IMAGENES = 2 |
|
num_imagenes_actuales = contar_imagenes(SAVE_DIR) |
|
|
|
|
|
RTC_CONFIGURATION = RTCConfiguration( |
|
{"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]} |
|
) |
|
|
|
class VideoProcessor: |
|
def __init__(self): |
|
self.frame = None |
|
|
|
def recv(self, frame): |
|
self.frame = frame.to_ndarray(format="bgr24") |
|
return av.VideoFrame.from_ndarray(self.frame, format="bgr24") |
|
|
|
if num_imagenes_actuales < MAX_IMAGENES: |
|
webrtc_ctx = webrtc_streamer( |
|
key="example", |
|
mode=WebRtcMode.SENDRECV, |
|
rtc_configuration=RTC_CONFIGURATION, |
|
video_processor_factory=VideoProcessor, |
|
media_stream_constraints={"video": True, "audio": False}, |
|
async_processing=True, |
|
) |
|
|
|
if webrtc_ctx.video_processor: |
|
video_processor = webrtc_ctx.video_processor |
|
if video_processor.frame is not None: |
|
st.image(video_processor.frame, caption='Captura de la cámara en vivo', use_column_width=True) |
|
|
|
if st.button('Guardar Imagen'): |
|
|
|
image = Image.fromarray(video_processor.frame) |
|
file_path = os.path.join(SAVE_DIR, f"captura_{num_imagenes_actuales + 1}.png") |
|
image.save(file_path) |
|
st.success(f"Imagen guardada con éxito en {file_path}.") |
|
num_imagenes_actuales += 1 |
|
st.experimental_rerun() |
|
|
|
|
|
uploaded_file = st.file_uploader("O sube una imagen...", type=["jpg", "jpeg", "png"]) |
|
|
|
if uploaded_file is not None: |
|
|
|
image = Image.open(uploaded_file) |
|
|
|
|
|
st.image(image, caption='Imagen subida.', use_column_width=True) |
|
st.write("") |
|
st.write("Guardando la imagen...") |
|
|
|
|
|
file_path = os.path.join(SAVE_DIR, f"subida_{num_imagenes_actuales + 1}.{uploaded_file.type.split('/')[1]}") |
|
image.save(file_path) |
|
st.success(f"Imagen guardada con éxito en {file_path}.") |
|
num_imagenes_actuales += 1 |
|
st.experimental_rerun() |
|
else: |
|
st.warning(f"Has alcanzado el límite máximo de {MAX_IMAGENES} imágenes. No puedes subir más imágenes.") |
|
if st.button('Eliminar todas las imágenes'): |
|
eliminar_imagenes(SAVE_DIR) |
|
st.success("Todas las imágenes han sido eliminadas.") |
|
st.experimental_rerun() |
|
|
|
|