import torch import torch.nn as nn import torch.nn.functional as F class ColumnFeatureExtractor(nn.Module): """ Input : (B, 1, H, W) – single‑channel image Output : (B, W, 2) – per‑column [mean, var] features """ def __init__(self): super().__init__() def forward(self, x): # x is already grayscale: (B, 1, H, W) mean = x.mean(dim=2) # (B, 1, W) var = x.var(dim=2, unbiased=False) # (B, 1, W) feat = torch.cat([mean, var], dim=1) # (B, 2, W) return feat.permute(0, 2, 1) # (B, W, 2) class ImageSequenceClassifier(nn.Module): """ RGB/gray image ➜ convert to gray ➜ column stats ➜ GRU/LSTM ➜ sigmoid """ GRAY_WEIGHTS = torch.tensor([0.2989, 0.5870, 0.1140]).view(1, 3, 1, 1) def __init__(self, rnn_hidden: int = 128, rnn_type: str = "GRU", # "GRU" or "LSTM" cls_hidden: int = 128, dropout: float = 0.0): super().__init__() self.register_buffer("gray_w", self.GRAY_WEIGHTS) # moved to device automatically self.feature_extractor = ColumnFeatureExtractor() # always outputs 2‑D features rnn_cls = nn.GRU if rnn_type.upper() == "GRU" else nn.LSTM self.rnn = rnn_cls(input_size=2, # [mean, var] hidden_size=rnn_hidden, batch_first=True) self.head = nn.Sequential( nn.Linear(rnn_hidden, cls_hidden), nn.ReLU(), nn.Dropout(dropout), nn.Linear(cls_hidden, 1), nn.Sigmoid() ) # ───────────────────────────────────────────────────────── def rgb_to_gray(self, x: torch.Tensor) -> torch.Tensor: """ Accepts (B,3,H,W) or (B,1,H,W) and returns (B,1,H,W) without changing the original dtype/range. """ if x.shape[1] == 3: w = self.gray_w.to(dtype=x.dtype, device=x.device) x = (x * w).sum(dim=1, keepdim=True) return x # ───────────────────────────────────────────────────────── def forward(self, x): """ x : (B, C, H, W) where C is 1 or 3 """ x_gray = self.rgb_to_gray(x) # (B, 1, H, W) seq = self.feature_extractor(x_gray) # (B, W, 2) seq_out, _ = self.rnn(seq) # (B, W, hidden) last = seq_out[:, -1, :] # final column’s hidden state return self.head(last) # (B, 1) # ----------------------------------------------------------- # quick smoke‑test def main(): torch.manual_seed(0) B, H, W = 2, 128, 128 imgs_rgb = torch.rand(B, 3, H, W) # random RGB batch imgs_gray = torch.rand(B, 1, H, W) # random grayscale batch model = ImageSequenceClassifier(rnn_hidden=64, cls_hidden=32, dropout=0.2) model.eval() with torch.no_grad(): p_rgb = model(imgs_rgb) p_gray = model(imgs_gray) for i, p in enumerate(p_rgb.squeeze(1)): print(f"[RGB ] image {i}: sigmoid = {p:.4f}") for i, p in enumerate(p_gray.squeeze(1)): print(f"[Gray] image {i}: sigmoid = {p:.4f}") if __name__ == "__main__": main()