-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlousa.py
More file actions
567 lines (487 loc) · 20.3 KB
/
lousa.py
File metadata and controls
567 lines (487 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
import cv2
from cvzone.HandTrackingModule import HandDetector
import mediapipe as mp
import numpy as np
import json
import os
import time
from jogo_similaridade import (
desenhar_quadrado_contorno,
calcular_similaridade,
salvar_nome_jogador,
salvar_pontuacao,
carrega_ranking,
)
from datetime import datetime
class LousaDigital:
def __init__(self):
# Configurações da câmera
self.video = cv2.VideoCapture(0)
self.video.set(3, 1280)
self.video.set(4, 720)
self.largura = 1280
self.altura = 720
# Hand tracking
self.detector = HandDetector(detectionCon=0.8)
self.desenho = []
# Máscara separada para o desenho do jogador (para o cálculo de similaridade)
self.imgCanvas = np.zeros((self.altura, self.largura, 3), np.uint8)
# Configurações iniciais
self.cor = (0, 0, 255)
self.espessura = 20
self.modo_atual = "desenho" # desenho, apresentacao
self.button_cooldown = 0
self.last_position = None
self.jogo_ativo = False
self.salvar_pontuacao_ativo = False
self.similaridade = 0
self.mostrar_ranking = False
# Cores disponíveis
self.cores = {
"Vermelho": (0, 0, 255),
"Verde": (0, 255, 0),
"Azul": (255, 0, 0),
"Preto": (0, 0, 0),
"Branco": (255, 255, 255),
"Amarelo": (0, 255, 255),
"Rosa": (255, 0, 255),
"Ciano": (255, 255, 0),
}
# Botões organizados em abas
self.setup_buttons()
def setup_buttons(self):
# Botões de cores (primeira linha)
self.botoes_cores = []
x_start = 50
for i, (nome, cor) in enumerate(
list(self.cores.items())[:6]
): # Primeiras 6 cores
x = x_start + i * 120
self.botoes_cores.append([x, 20, x + 100, 60, cor, nome])
# Botões de ferramentas (segunda linha)
self.botoes_ferramentas = [
[40, 150, 130, 190, (128, 128, 128), "Limpar"],
[40, 200, 130, 240, (128, 128, 128), "Salvar"],
[40, 250, 130, 290, (128, 128, 128), "Carregar"],
[40, 300, 130, 340, (128, 128, 128), "+"],
[40, 350, 130, 390, (128, 128, 128), "-"],
[40, 400, 130, 440, (128, 128, 128), "Desfazer"],
[780, 20, 920, 60, (0, 200, 0), "Iniciar Jogo"],
[930, 20, 1060, 60, (0, 200, 0), "Ver ranking"],
]
self.botao_salvar_pontuacao = [
[1000, 500, 1200, 550, (20, 150, 20), "Salvar Pontuacao?"]
]
# Combinando todos os botões
self.botoes = (
self.botoes_cores + self.botoes_ferramentas + self.botao_salvar_pontuacao
)
def smooth_drawing(self, current_pos):
if self.last_position is None:
self.last_position = current_pos
return [current_pos]
points = []
x1, y1 = self.last_position
x2, y2 = current_pos
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
if distance > 5:
steps = int(distance / 3)
for i in range(steps + 1):
t = i / max(steps, 1)
x = int(x1 + (x2 - x1) * t)
y = int(y1 + (y2 - y1) * t)
points.append((x, y))
else:
points.append(current_pos)
self.last_position = current_pos
return points
def salvar_desenho(self):
if not self.desenho:
return
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"desenho_{timestamp}.json"
desenho_serializado = []
for ponto in self.desenho:
x, y, cor, espessura = ponto
desenho_serializado.append(
{"x": x, "y": y, "cor": cor, "espessura": espessura}
)
try:
with open(filename, "w") as f:
json.dump(desenho_serializado, f)
print(f"Desenho salvo como {filename}")
except Exception as e:
print(f"Erro ao salvar: {e}")
def carregar_desenho(self):
arquivos = [
f
for f in os.listdir(".")
if f.startswith("desenho_") and f.endswith(".json")
]
if not arquivos:
print("Nenhum desenho salvo encontrado")
return
arquivo_recente = max(arquivos)
try:
with open(arquivo_recente, "r") as f:
desenho_carregado = json.load(f)
self.desenho = []
for ponto in desenho_carregado:
self.desenho.append(
(ponto["x"], ponto["y"], tuple(ponto["cor"]), ponto["espessura"])
)
print(f"Desenho carregado: {arquivo_recente}")
except Exception as e:
print(f"Erro ao carregar: {e}")
def desfazer_ultimo(self):
if not self.desenho:
return
while self.desenho and self.desenho[-1][0] != 0:
self.desenho.pop()
if self.desenho and self.desenho[-1][0] == 0:
self.desenho.pop()
def processar_botoes(self, x_flip, y):
"""Processa cliques nos botões com cooldown"""
if self.button_cooldown > 0:
return
for bx1, by1, bx2, by2, bcor, texto in self.botoes:
if bx1 < x_flip < bx2 and by1 < y < by2:
self.button_cooldown = 15
if texto in self.cores:
self.cor = self.cores[texto]
elif texto == "+":
self.espessura = min(self.espessura + 5, 50)
elif texto == "-":
self.espessura = max(self.espessura - 5, 5)
elif texto == "Limpar":
self.desenho = []
self.imgCanvas = np.zeros((self.altura, self.largura, 3), np.uint8)
elif texto == "Salvar":
self.salvar_desenho()
elif texto == "Carregar":
self.carregar_desenho()
elif texto == "Desfazer":
self.desfazer_ultimo()
if self.jogo_ativo:
self.desenho = []
self.imgCanvas = np.zeros(
(self.altura, self.largura, 3), np.uint8
)
elif texto == "Iniciar Jogo":
self.jogo_ativo = not self.jogo_ativo
self.desenho = []
self.imgCanvas = np.zeros((self.altura, self.largura, 3), np.uint8)
print(f"Jogo: {'ATIVO' if self.jogo_ativo else 'INATIVO'}")
elif texto == "Salvar Pontuacao?":
nome_jogador = salvar_nome_jogador()
salvar_pontuacao(nome_jogador, self.similaridade)
print("Pontuacao salva!")
self.salvar_pontuacao_ativo = not self.salvar_pontuacao_ativo
self.desenho = []
self.imgCanvas = np.zeros((self.altura, self.largura, 3), np.uint8)
if self.jogo_ativo:
self.jogo_ativo = not self.jogo_ativo
elif texto == "Ver ranking":
self.mostrar_ranking = not self.mostrar_ranking
break
def desenhar_interface(self, img):
# Botões de cores
for bx1, by1, bx2, by2, bcor, texto in self.botoes_cores:
if texto in self.cores and self.cores[texto] == self.cor:
cv2.rectangle(
img, (bx1 - 3, by1 - 3), (bx2 + 3, by2 + 3), (0, 255, 0), 3
)
cv2.rectangle(img, (bx1, by1), (bx2, by2), bcor, cv2.FILLED)
cv2.rectangle(img, (bx1, by1), (bx2, by2), (255, 255, 255), 2)
text_size = cv2.getTextSize(texto, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)[0]
text_x = bx1 + (bx2 - bx1 - text_size[0]) // 2
text_y = by1 + (by2 - by1 + text_size[1]) // 2
text_color = (255, 255, 255)
if texto == "Branco":
text_color = (0, 0, 0)
cv2.putText(
img,
texto,
(text_x, text_y),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
text_color,
2,
)
# Botões de ferramentas
for bx1, by1, bx2, by2, bcor, texto in self.botoes_ferramentas:
cv2.rectangle(img, (bx1, by1), (bx2, by2), bcor, cv2.FILLED)
cv2.rectangle(img, (bx1, by1), (bx2, by2), (50, 50, 50), 2)
if texto == "Iniciar Jogo" and self.jogo_ativo:
cv2.rectangle(img, (bx1, by1), (bx2, by2), (0, 255, 0), 4)
text_size = cv2.getTextSize(texto, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)[0]
text_x = bx1 + (bx2 - bx1 - text_size[0]) // 2
text_y = by1 + (by2 - by1 + text_size[1]) // 2
cv2.putText(
img,
texto,
(text_x, text_y),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
(255, 255, 255),
2,
)
if self.salvar_pontuacao_ativo:
for bx1, by1, bx2, by2, bcor, texto in self.botao_salvar_pontuacao:
cv2.rectangle(img, (bx1, by1), (bx2, by2), bcor, cv2.FILLED)
cv2.rectangle(img, (bx1, by1), (bx2, by2), (50, 50, 50), 2)
text_size = cv2.getTextSize(texto, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)[0]
text_x = bx1 + (bx2 - bx1 - text_size[0]) // 2
text_y = by1 + (by2 - by1 + text_size[1]) // 2
cv2.putText(
img,
texto,
(text_x, text_y),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
(255, 255, 255),
2,
)
# Informações na tela
info_y = 150
cv2.putText(
img,
f"Espessura: {self.espessura}",
(50, info_y - 20),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(0, 0, 255),
2,
)
cv2.putText(
img,
f"Pontos: {len(self.desenho)}",
(50, info_y - 50),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(0, 0, 255),
2,
)
# Instruções
instrucoes = ["1 dedo: Desenhar", "3 dedos: Limpar tudo", "ESC: Sair"]
for i, instrucao in enumerate(instrucoes):
cv2.putText(
img,
instrucao,
(50, img.shape[0] - 80 + i * 25),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(200, 200, 200),
1,
)
def renderizar_desenho(self, img, draw_on_canvas=False):
"""Renderiza o desenho e, opcionalmente, o armazena no imgCanvas para cálculo"""
# Cria uma cópia temporária do canvas para não modificar o original
if draw_on_canvas:
self.imgCanvas = np.zeros((self.altura, self.largura, 3), np.uint8)
cor_canvas = (255, 255, 255)
for id, ponto in enumerate(self.desenho):
x, y, cor_p, esp_p = ponto
if draw_on_canvas:
target_img = self.imgCanvas
p_cor = cor_canvas
else:
target_img = img
p_cor = cor_p
if x != 0:
cv2.circle(target_img, (x, y), esp_p // 2, p_cor, cv2.FILLED)
if id >= 1:
ax, ay, _, _ = self.desenho[id - 1]
if x != 0 and ax != 0:
cv2.line(target_img, (x, y), (ax, ay), p_cor, esp_p)
def executar(self):
"""Loop principal da aplicação"""
similaridade_texto_display = None
x_jogo_inicio = None
y_jogo_inicio = None
while True:
check, img = self.video.read()
if not check:
break
self.altura, self.largura, _ = img.shape
# Reduz cooldown
if self.button_cooldown > 0:
self.button_cooldown -= 1
# Hand tracking (Feito no frame original)
resultado = self.detector.findHands(img, draw=True)
hands = resultado[0]
dedosLev = 0
if hands:
hand = hands[0]
lmlist = hand["lmList"]
dedos = self.detector.fingersUp(hand)
dedosLev = dedos.count(1)
x, y = lmlist[8][0], lmlist[8][1]
x_flip = img.shape[1] - x
self.processar_botoes(x_flip, y)
# Desenho. A cor original é usada para armazenar o ponto, mas o render será corrigido.
if dedosLev == 1:
pontos_suavizados = self.smooth_drawing((x, y))
for px, py in pontos_suavizados:
self.desenho.append((px, py, self.cor, self.espessura))
cv2.circle(img, (x, y), self.espessura // 2, self.cor, 2)
if (
self.jogo_ativo
and x_jogo_inicio is None
and y_jogo_inicio is None
):
x_jogo_inicio, y_jogo_inicio = self.last_position
momento_jogo_inicio = time.time()
print(x_jogo_inicio)
print(y_jogo_inicio)
elif dedosLev != 1 and dedosLev != 3:
if self.desenho and self.desenho[-1][0] != 0:
self.desenho.append((0, 0, self.cor, self.espessura))
self.last_position = None
elif dedosLev == 3:
self.desenho = []
self.imgCanvas = np.zeros((self.altura, self.largura, 3), np.uint8)
self.last_position = None
limites_forma = [0, 0, 0, 0]
# 1. Desenha o Contorno ALVO (na imagem real, para visualização)
if self.jogo_ativo:
limites_forma = desenhar_quadrado_contorno(img)
# 2. Cria a MÁSCARA ALVO para o cálculo
mascara_alvo_bgr = np.zeros((self.altura, self.largura, 3), np.uint8)
x1, y1, x2, y2 = limites_forma
margem_erro = self.espessura + 5
cv2.rectangle(
mascara_alvo_bgr, (x1, y1), (x2, y2), (255, 255, 255), margem_erro
)
mascara_alvo = cv2.cvtColor(mascara_alvo_bgr, cv2.COLOR_BGR2GRAY)
# 3. Desenha a linha do jogador na imgCanvas (Máscara Desenho)
self.renderizar_desenho(img, draw_on_canvas=True)
mascara_desenho = cv2.cvtColor(self.imgCanvas, cv2.COLOR_BGR2GRAY)
# 4. Calcula e ARMAZENA O TEXTO apenas quando o desenho estiver finalizado
if (
x_jogo_inicio is not None
and y_jogo_inicio is not None
and x_jogo_inicio - 20 <= x <= x_jogo_inicio + 20
and y_jogo_inicio - 20 <= y <= y_jogo_inicio + 20
and time.time() > momento_jogo_inicio + 3
and len(self.desenho) > 0
):
self.similaridade, similar = calcular_similaridade(
mascara_alvo, mascara_desenho, limite_minimo=0.75
)
cor_texto = (0, 255, 0) if similar else (0, 0, 255)
similaridade_texto_display = {
"texto": f"Similaridade: {self.similaridade*100:.2f}% ({'OK' if similar else 'TENTE NOVAMENTE'})",
"cor": cor_texto,
}
self.salvar_pontuacao_ativo = True
# Renderiza desenho
self.renderizar_desenho(img, draw_on_canvas=False)
img = cv2.flip(img, 1)
# Desenha interface (Botões e texto de informações)
self.desenhar_interface(img)
if self.mostrar_ranking:
# 1. Carrega o ranking
ranking = carrega_ranking()
# 2. Cria a sobreposição (mesmo tamanho da imagem, totalmente preta)
overlay = img.copy()
# 3. Desenha um retângulo semi-transparente no centro (por exemplo, 80% da tela)
w_o = int(self.largura * 0.8)
h_o = int(self.altura * 0.8)
x_o = int((self.largura - w_o) / 2)
y_o = int((self.altura - h_o) / 2)
cv2.rectangle(
overlay, (x_o, y_o), (x_o + w_o, y_o + h_o), (0, 150, 0), cv2.FILLED
)
# Mescla a sobreposição preta com a imagem original (alfa=0.7 para transparência)
img = cv2.addWeighted(overlay, 0.8, img, 0.3, 0)
# 4. Desenha o título e instruções
center_x = self.largura // 2
# Título
title_text = "RANKING DE PONTUACAO"
(tw, th) = cv2.getTextSize(title_text, cv2.FONT_HERSHEY_SIMPLEX, 1, 3)[
0
]
cv2.putText(
img,
title_text,
(center_x - tw // 2, y_o + 60),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(255, 255, 255),
3,
)
# Instrução de saída
inst_text = "Use '3 dedos' ou pressione 'r' para voltar."
(iw, ih) = cv2.getTextSize(inst_text, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1)[
0
]
cv2.putText(
img,
inst_text,
(center_x - iw // 2, self.altura - 50),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
(200, 200, 200),
1,
)
# 5. Exibir as pontuações
y_pos = y_o + 120
if ranking:
# Exibe apenas os 10 melhores
top_ranking = {k: ranking[k] for k in list(ranking)[:10]}
for jogador, pontuacao in top_ranking.items():
texto_ranking = f"Jogador: {jogador}: {pontuacao*100:.2f}%"
cor_ranking = (255, 255, 255)
# Centraliza o texto do ranking na largura do retângulo
(rw, rh) = cv2.getTextSize(
texto_ranking, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2
)[0]
cv2.putText(
img,
texto_ranking,
(center_x - rw // 2, y_pos),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
cor_ranking,
2,
)
y_pos += 40
else:
cv2.putText(
img,
"Nenhuma pontuação encontrada.",
(center_x - 150, y_pos), # Posição centralizada aproximada
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(0, 0, 255),
2,
)
# Desenha o texto do jogo de simlaridade (se tivesse sido plotado antes, ia ficar espelhado)
if similaridade_texto_display:
cv2.putText(
img,
similaridade_texto_display["texto"],
(200, 100),
cv2.FONT_HERSHEY_SIMPLEX,
0.8,
similaridade_texto_display["cor"],
2,
)
# ----------------------------------------------------------
cv2.imshow("Lousa Digital", img)
# Teclas de atalho
key = cv2.waitKey(1) & 0xFF
if key == 27:
break
elif key == ord("s"):
self.salvar_desenho()
elif key == ord("l"):
self.carregar_desenho()
elif key == ord("c"):
self.desenho = []
self.imgCanvas = np.zeros((self.altura, self.largura, 3), np.uint8)
elif key == ord("z"):
self.desfazer_ultimo()
self.video.release()
cv2.destroyAllWindows()