-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessCRT_SelectROIsComImagem.py
More file actions
164 lines (130 loc) · 5.44 KB
/
Copy pathprocessCRT_SelectROIsComImagem.py
File metadata and controls
164 lines (130 loc) · 5.44 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
import os
import pandas as pd
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema
import sys
import time
sys.path.append("C:/Users/raque/OneDrive/Documentos/GitHub/pyCRT")
from src.pyCRT import PCRT
# Caminho base onde estão as pastas P1, P2, ..., P31
base_path = "C:/Users/raque/OneDrive/Documentos/GitHub/pCRT_OthersMethods"
numero_pastas = 31
pastaInicio = 1
# Tamanhos diferentes de ROIs
roi_sizes = [(100, 100), (200, 200), (400, 400)]
resultados = []
def select_roi_center(frame):
"""Função para o usuário selecionar um único centro de ROI manualmente clicando no frame."""
roi_center = []
def click_event(event, x, y, flags, param):
if event == cv.EVENT_LBUTTONDOWN:
roi_center.append((x, y))
print(f"Centro da ROI selecionado: ({x}, {y})")
cv.imshow("Selecione o centro da ROI", frame)
cv.setMouseCallback("Selecione o centro da ROI", click_event)
while len(roi_center) < 1:
cv.waitKey(1)
cv.destroyAllWindows()
return roi_center[0]
def extract_roi_intensity(frame, center, size):
"""Extrai a média de intensidade de uma ROI definida pelo centro e tamanho"""
h, w = size
x, y = center
x1, y1 = max(0, x - w // 2), max(0, y - h // 2)
x2, y2 = min(frame.shape[1], x + w // 2), min(frame.shape[0], y + h // 2)
roi = frame[y1:y2, x1:x2]
return np.mean(roi, axis=(0, 1)) # Média dos canais BGR
def draw_rois(frame, center, roi_sizes):
"""Desenha as ROIs no frame e exibe a imagem."""
for size in roi_sizes:
h, w = size
x, y = center
x1, y1 = max(0, x - w // 2), max(0, y - h // 2)
x2, y2 = min(frame.shape[1], x + w // 2), min(frame.shape[0], y + h // 2)
cv.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2) # Azul
cv.imshow("ROIs Selecionadas", frame)
cv.waitKey(0)
cv.destroyAllWindows()
# Loop sobre os participantes (P1 até P31)
for i in range(pastaInicio, numero_pastas):
folder_name = f"P{i}"
folder_path = os.path.join(base_path, folder_name)
if not os.path.exists(folder_path):
print(f"Pasta {folder_name} não encontrada!")
continue
# Processar os vídeos ROI_CR1 até ROI_CR5
for j in range(1, 6):
video_name = f"CR{j}.wmv"
video_path = os.path.join(folder_path, video_name)
if not os.path.exists(video_path):
print(f"Vídeo {video_name} não encontrado na pasta {folder_name}!")
continue
cap = cv.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir o vídeo {video_name}")
continue
fps = cap.get(cv.CAP_PROP_FPS)
frame_count = 0
time_stamps = []
# Selecionar o centro da ROI para cada vídeo
cap.set(cv.CAP_PROP_POS_FRAMES, 400)
ret, frame = cap.read()
if not ret:
print(f"Erro ao capturar o frame 400 do vídeo {video_name}")
cap.release()
continue
roi_center = select_roi_center(frame) # Seleção manual do centro da ROI
draw_rois(frame, roi_center, roi_sizes) # Exibir ROIs desenhadas
# Inicializar listas para armazenar intensidades de cada tamanho de ROI
roi_intensities = {size: [] for size in roi_sizes}
# Resetar vídeo para o início
cap.set(cv.CAP_PROP_POS_FRAMES, 0)
while True:
ret, frame = cap.read()
if not ret:
break
for size in roi_sizes:
intensity = extract_roi_intensity(frame, roi_center, size)
roi_intensities[size].append(intensity[1]) # Canal verde
time_stamps.append(frame_count / fps)
frame_count += 1
cap.release()
# Processar cada ROI individualmente para cada tamanho
for size in roi_sizes:
start_time = time.time() # Início da contagem de tempo
intensity_arr = np.array(roi_intensities[size])
time_stamps = np.array(time_stamps)
try:
roi = (130, 122, 33, 450) # Definição da ROI específica
pcrt = PCRT.fromVideoFile(
video_path,
roi=roi,
displayVideo=False,
exclusionMethod="best fit",
exclusionCriteria=9999,
)
processing_time = time.time() - start_time # Tempo total de processamento
resultados.append(
{
"Pasta": folder_name,
"Video": video_name,
"Centro_ROI": f"({roi_center[0]}, {roi_center[1]})",
"Tamanho_ROI": f"{size[0]}x{size[1]}",
"pCRT": pcrt.pCRT[0],
"uncert_pCRT": pcrt.pCRT[1],
"CriticalTime": pcrt.criticalTime,
"Tempo_Processamento (s)": processing_time,
}
)
print(
f"Processado: {folder_name}/{video_name} (Centro: {roi_center}, {size[0]}x{size[1]}) | Tempo: {processing_time:.2f}s"
)
except Exception as e:
print(
f"Erro ao processar {folder_name}/{video_name} (Centro: {roi_center}, {size[0]}x{size[1]}): {e}"
)
# Salvar resultados
df = pd.DataFrame(resultados)
df.to_excel("Resultados_pCRT_3ROIs_Tamanhos.xlsx", index=False)