Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 2 additions & 31 deletions torchvision/datasets/_optical_flow.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import itertools
import os
import re
from abc import ABC, abstractmethod
from glob import glob
from pathlib import Path
Expand All @@ -10,7 +9,7 @@
from PIL import Image

from ..io.image import _read_png_16
from .utils import verify_str_arg
from .utils import verify_str_arg, read_pfm
from .vision import VisionDataset


Expand Down Expand Up @@ -376,7 +375,7 @@ def __getitem__(self, index):
return super().__getitem__(index)

def _read_flow(self, file_name):
return _read_pfm(file_name)
return read_pfm(file_name)


class HD1K(FlowDataset):
Expand Down Expand Up @@ -472,31 +471,3 @@ def _read_16bits_png_with_flow_and_valid_mask(file_name):

# For consistency with other datasets, we convert to numpy
return flow.numpy(), valid_flow_mask.numpy()


def _read_pfm(file_name):
"""Read flow in .pfm format"""

with open(file_name, "rb") as f:
header = f.readline().rstrip()
if header != b"PF":
raise ValueError("Invalid PFM file")

dim_match = re.match(rb"^(\d+)\s(\d+)\s$", f.readline())
if not dim_match:
raise Exception("Malformed PFM header.")
w, h = (int(dim) for dim in dim_match.groups())

scale = float(f.readline().rstrip())
if scale < 0: # little-endian
endian = "<"
scale = -scale
else:
endian = ">" # big-endian

data = np.fromfile(f, dtype=endian + "f")

data = data.reshape(h, w, 3).transpose(2, 0, 1)
data = np.flip(data, axis=1) # flip on h dimension
data = data[:2, :, :]
return data.astype(np.float32)
37 changes: 37 additions & 0 deletions torchvision/datasets/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from typing import Any, Callable, List, Iterable, Optional, TypeVar, Dict, IO, Tuple, Iterator
from urllib.parse import urlparse

import numpy as np
import requests
import torch
from torch.utils.model_zoo import tqdm
Expand Down Expand Up @@ -483,3 +484,39 @@ def verify_str_arg(
raise ValueError(msg)

return value


def read_pfm(file_name: str, slice_channels: int = 2) -> np.ndarray:
Copy link
Member

Choose a reason for hiding this comment

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

Let's keep it private, we don't really need to expose it to users

Suggested change
def read_pfm(file_name: str, slice_channels: int = 2) -> np.ndarray:
def _read_pfm(file_name: str, slice_channels: int = 2) -> np.ndarray:

"""Read file in .pfm format. Might contain
Copy link
Member

Choose a reason for hiding this comment

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

Looks like this sentence is unfinished?


Args:
file_name (str): Path to the file.
slice_channels (int): Number of channels to slice out of the file.
Useful for reading different data formats stored in .pfm files: Optical Flows, Stereo Disparity Maps, etc.
Copy link
Member

Choose a reason for hiding this comment

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

Skipping a line in a parameter description requires to indent it to the right (otherwise sphinx doesn't render it properly):

Suggested change
Useful for reading different data formats stored in .pfm files: Optical Flows, Stereo Disparity Maps, etc.
Useful for reading different data formats stored in .pfm files: Optical Flows, Stereo Disparity Maps, etc.

"""

with open(file_name, "rb") as f:
header = f.readline().rstrip()
if header not in [b"PF", b"Pf"]:
raise ValueError("Invalid PFM file")

dim_match = re.match(rb"^(\d+)\s(\d+)\s$", f.readline())
if not dim_match:
raise Exception("Malformed PFM header.")
w, h = (int(dim) for dim in dim_match.groups())

scale = float(f.readline().rstrip())
if scale < 0: # little-endian
endian = "<"
scale = -scale
else:
endian = ">" # big-endian

data = np.fromfile(f, dtype=endian + "f")

pfm_channels = 3 if header == b"PF" else 1

data = data.reshape(h, w, pfm_channels).transpose(2, 0, 1)
data = np.flip(data, axis=1) # flip on h dimension
data = data[:slice_channels, :, :]
return data.astype(np.float32)