Skip to content

[WIP] Fix NumPy compatibility error in video segmentation#3

Merged
NickScherbakov merged 1 commit intomainfrom
copilot/fix-numpy-compatibility-issue
Dec 20, 2025
Merged

[WIP] Fix NumPy compatibility error in video segmentation#3
NickScherbakov merged 1 commit intomainfrom
copilot/fix-numpy-compatibility-issue

Conversation

Copy link
Contributor

Copilot AI commented Dec 20, 2025

Fix NumPy 2.x Compatibility Issue in Video Segmentation

Problem: TypeError: expected np.ndarray (got numpy.ndarray) when using torchvision.transforms.ToTensor() with NumPy 2.x

Plan:

  • Update _preprocess_frame() method in src/segmentation.py to use manual tensor conversion instead of ToTensor()
  • Remove the self.transform definition from __init__() since it will no longer be used
  • Verify torch import is present (already confirmed at line 3)
  • Remove unused imports if any (check transforms import)
  • Test the changes work on both CPU and GPU
  • Run existing tests to ensure no regressions
Original prompt

Проблема

При запуске сегментации видео возникает ошибка совместимости NumPy 2.x с torchvision:

TypeError: expected np.ndarray (got numpy.ndarray)

Ошибка возникает в torchvision.transforms.functional.to_tensor() даже при передаче PIL Image.

Полный traceback

File /tf/darachubarova/defliker/notebooks/../src/segmentation.py:185, in VideoSegmenter.segment_video
    batch_tensors = torch.stack([
        self._preprocess_frame(frame) for frame in batch_frames
    ]).to(self.device)

File src/segmentation.py:74, in VideoSegmenter._preprocess_frame
    input_tensor = self.transform(pil_image)

File torchvision/transforms/functional.py:168, in to_tensor
    img = torch.from_numpy(np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True))

TypeError: expected np.ndarray (got numpy.ndarray)

Окружение

  • Python 3.12
  • NumPy 2.2.6
  • PyTorch 2.8.0
  • torchvision (latest)

Требуемое решение

Заменить использование torchvision.transforms.ToTensor() на ручную конвертацию в методе _preprocess_frame() в файле src/segmentation.py:

def _preprocess_frame(self, frame):
    """Preprocess a single frame for the model."""
    import torch
    
    # Convert BGR to RGB
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    
    # Manual conversion instead of ToTensor() for NumPy 2.x compatibility
    img = frame_rgb.astype('float32') / 255.0
    img = img.transpose((2, 0, 1))  # HWC -> CHW
    input_tensor = torch.from_numpy(img.copy())
    
    # Apply normalization manually (ImageNet mean/std)
    mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
    std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
    input_tensor = (input_tensor - mean) / std

    return input_tensor

Дополнительно

  1. Убедиться, что self.transform больше не используется в _preprocess_frame
  2. Проверить, что импорт torch присутствует в начале файла или в методе
  3. Удалить неиспользуемые импорты если они есть
  4. Код должен работать как на CPU, так и на GPU

This pull request was created from Copilot chat.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@NickScherbakov NickScherbakov marked this pull request as ready for review December 20, 2025 21:40
Copilot AI review requested due to automatic review settings December 20, 2025 21:40
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review any files in this pull request.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@NickScherbakov NickScherbakov merged commit 21a9c41 into main Dec 20, 2025
1 check failed
Copilot AI requested a review from NickScherbakov December 20, 2025 21:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants