0% encontró este documento útil (0 votos)
11 vistas7 páginas

Propuesta de Proyecto

Descargar como pdf o txt
Descargar como pdf o txt
Descargar como pdf o txt
Está en la página 1/ 7

APUNTES DEL PROYECTO

18/09/2024

Andrés. A Socorro.
Universidad del Zulia.
Maracaibo.
1

Descripción general:
El programa se inicia creando una ventana gráfica donde el usuario puede interactuar con
varias funcionalidades relacionadas con la lectura de códigos QR. La interfaz incluye botones
para iniciar la lectura, mostrar instrucciones y créditos, y un control para habilitar o deshabilitar
el sonido.

- La función initialize_camera se encarga de abrir la cámara del dispositivo. Utiliza


OpenCV para capturar video en tiempo real. Si la cámara no se puede abrir, se muestra
un mensaje de error y el programa se cierra.

def initialize_camera():

cap = cv2.VideoCapture(0)

if not cap.isOpened():

messagebox.showerror("Error", "No se pudo abrir la cámara.")

exit()

return cap

- La función is_connected realiza una solicitud a Google para comprobar si hay


conexión a Internet. Si no se puede conectar, devuelve False.

def is_connected():

try:

requests.get('http://www.google.com', timeout=5)

return True

except requests.ConnectionError:

return False
2

- La función play_sound emite un sonido (beep) al escanear un nuevo código QR, pero
solo si la opción de sonido está habilitada. Utiliza la biblioteca winsound para generar
el sonido.

def play_sound(frequency=500, duration=500):

if sound_enabled.get(): # Verifica si el sonido está habilitado

winsound.Beep(frequency, duration)

- La función read_qr_codes es la función principal que captura frames de vídeo,


decodifica los códigos QR y maneja la lógica de escaneo. Se configura una conexión
serial con un dispositivo Arduino y se inicia un bucle infinito que:

-Captura un frame de la cámara.


-Decodifica cualquier código QR presente en el frame.
-Si se detecta un código QR nuevo, se agrega a un conjunto de códigos escaneados y se
guarda en un historial.
-Se emite un sonido y se envía un comando al Arduino.
-Si el código QR es una URL, se abre en el navegador web (si hay conexión a Internet).

Además, dibuja un polígono alrededor del código QR en el video y muestra el contenido del
código en la pantalla.

def read_qr_codes():
# Configura la conexión serial
puerto = 'COM9' # Cambia esto si es necesario
baud_rate = 9600
ser = serial.Serial(puerto, baud_rate, timeout=1)
time.sleep(2) # Espera a que se establezca la conexión

cap = initialize_camera()
scanned_codes = set()
3

history = []

while True:
ret, frame = cap.read()
if not ret:
print("Error: No se pudo leer el frame de la cámara.")
ser.write(b'N') # Marca un error
break

decoded_objects = decode(frame)

for obj in decoded_objects:


qr_data = obj.data.decode('utf-8')

if qr_data not in scanned_codes:


scanned_codes.add(qr_data)
history.append(qr_data) # Guarda el código escaneado en el historial
play_sound()

# Enviar 'P' al Arduino


ser.write(b'P')
print("Enviado: P")

if is_connected() and (qr_data.startswith('http://') or qr_data.startswith('https://')):


try:
webbrowser.open(qr_data)
except Exception as e:
print(f"Error al abrir la URL: {e}")
4

points = obj.polygon
if len(points) == 4:
cv2.polylines(frame, [np.array(points)], isClosed=True, color=(0, 255, 0), thickness=2)
cv2.putText(frame, qr_data, (points[0].x, points[0].y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

cv2.imshow('Lector de Códigos QR', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):


break

cap.release()
cv2.destroyAllWindows()
messagebox.showinfo("Finalizado", "Programa finalizado correctamente.")
show_history(history) # Muestra el historial al finalizar

- Al finalizar la lectura, la función show_history muestra un mensaje con el historial de


códigos escaneados. Si no se escanearon códigos, informa al usuario.

def show_history(history):
if history:
history_message = "Historial de Códigos Escaneados:\n\n" + "\n".join(history)
else:
history_message = "No se han escaneado códigos."
messagebox.showinfo("Historial", history_message)

- La función create_interface configura la ventana principal de la


aplicación utilizando Tkinter. Incluye:

def create_interface():
global sound_enabled
root = tk.Tk()
5

root.title("Lector de Códigos QR LUZ")


root.geometry("800x600")
root.configure(bg="#f0f0f0")

# Inicializar la variable para habilitar/deshabilitar sonido


sound_enabled = StringVar(value='1')

# Logo o imagen de fondo


logo = PhotoImage(file="C:/Users/USUARIO/Documents/prueba/Escaner qr
pruebas/imagenes/mi_logo.png")
logo_label = tk.Label(root, image=logo, bg="#f0f0f0")
logo_label.pack(pady=10)

# Label para animación de inicio


startup_label = tk.Label(root, text="Cargando...", font=("Arial", 16, "bold"),
bg="#f0f0f0")
startup_label.pack(pady=20)

# Iniciar animación de inicio


root.after(0, animate_startup, startup_label)

label = tk.Label(root, text="Presiona el botón para iniciar la lectura de códigos QR",


wraplength=350, bg="#f0f0f0", font=("Arial", 12))
label.pack(pady=20)

button_frame = tk.Frame(root, bg="#f0f0f0")


button_frame.pack(pady=10)

start_button = tk.Button(button_frame, text="Iniciar Lectura", command=start_reading,


bg="#0066b3", fg="white", font=("Arial", 12, "bold"))
start_button.grid(row=0, column=0, padx=5)
6

instructions_button = tk.Button(button_frame, text="Instrucciones de uso",


command=show_instructions, bg="#0066b3", fg="white", font=("Arial", 12, "bold"))
instructions_button.grid(row=0, column=1, padx=5)

credits_button = tk.Button(button_frame, text="Créditos", command=show_credits,


bg="#0066b3", fg="white", font=("Arial", 12, "bold"))
credits_button.grid(row=0, column=2, padx=5)

# Botón para habilitar/deshabilitar sonido


sound_button = tk.Checkbutton(root, text="Activar Sonido", variable=sound_enabled,
onvalue='1', offvalue='0', bg="#f0f0f0", font=("Arial", 12))
sound_button.pack(pady=10)

exit_button = tk.Button(root, text="Salir", command=root.quit, bg="#f44336",


fg="white", font=("Arial", 12, "bold"))
exit_button.pack(pady=10)

root.mainloop()

También podría gustarte