Commit f573c11c authored by Kai Chen's avatar Kai Chen
Browse files

draft documentation

parent ad98e856
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
\ No newline at end of file
API
====
fileio
--------------
.. automodule:: mmcv.fileio
:members:
image
--------------
.. automodule:: mmcv.image
:members:
video
--------------
.. automodule:: mmcv.video
:members:
:exclude-members: VideoWriter_fourcc
arraymisc
--------------
.. automodule:: mmcv.arraymisc
:members:
visualization
--------------
.. automodule:: mmcv.visualization
:members:
utils
--------------
.. automodule:: mmcv.utils
:members:
runner
--------------
.. automodule:: mmcv.runner
:members:
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import mmcv # noqa: E402
# -- Project information -----------------------------------------------------
project = 'mmcv'
copyright = '2018, Kai Chen'
author = 'Kai Chen'
# The short X.Y version
version = mmcv.__version__
# The full version, including alpha/beta/rc tags
release = mmcv.__version__
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
]
autodoc_mock_imports = ['cv2', 'torch']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = ['.rst', '.md']
source_parsers = {'.md': 'recommonmark.parser.CommonMarkParser'}
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'mmcvdoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'mmcv.tex', 'mmcv Documentation', 'Kai Chen', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, 'mmcv', 'mmcv Documentation', [author], 1)]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'mmcv', 'mmcv Documentation', author, 'mmcv',
'One line description of project.', 'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# -- Extension configuration -------------------------------------------------
## Image
This module provides some image processing methods.
### Read/Write/Show
To read or write images files, use `imread` or `imwrite`.
```python
import mmcv
img = mmcv.imread('test.jpg')
img = mmcv.imread('test.jpg', flag='grayscale')
img_ = mmcv.imread(img) # nothing will happen, img_ = img
mmcv.imwrite(img, 'out.jpg')
```
To read images from bytes
```python
with open('test.jpg', 'rb') as f:
data = f.read()
img = mmcv.imfrombytes(data)
```
To show an image file or a loaded image
```python
mmcv.imshow('tests/data/color.jpg')
for i in range(10):
img = np.random.randint(256, size=(100, 100, 3), dtype=np.uint8)
mmcv.imshow(img, win_name='test image', wait_time=200)
```
### Resize
There are three resize methods. All `imresize_*` methods have a parameter `return_scale`,
if this param is `False`, then the return value is merely the resized image, otherwise
is a tuple (resized_img, scale).
```python
# resize to a given size
mmcv.imresize(img, (1000, 600), return_scale=True)
# resize to the same size of another image
mmcv.imresize_like(img, dst_img, return_scale=False)
# resize by a ratio
mmcv.imrescale(img, 0.5)
# resize so that the max edge no longer than 1000, short edge no longer than 800
# without changing the aspect ratio
mmcv.imrescale(img, (1000, 800))
```
### Color space conversion
Supported conversion methods:
- bgr2gray
- gray2bgr
- bgr2rgb
- rgb2bgr
- bgr2hsv
- hsv2bgr
```python
img = mmcv.imread('tests/data/color.jpg')
img1 = mmcv.bgr2rgb(img)
img2 = mmcv.rgb2gray(img1)
img3 = mmcv.bgr2hsv(img)
```
### Crop
Support single/multiple crop.
```python
import mmcv
import numpy as np
img = mmcv.read_img('tests/data/color.jpg')
bboxes = np.array([10, 10, 100, 120]) # x1, y1, x2, y2
patch = mmcv.crop_img(img, bboxes)
bboxes = np.array([[10, 10, 100, 120], [0, 0, 50, 50]])
patches = mmcv.crop_img(img, bboxes)
```
Resizing cropped patches.
```python
# upsample patches by 1.2x
patches = mmcv.crop_img(img, bboxes, scale_ratio=1.2)
```
### Padding
Pad an image to specific size with given values.
```python
img = mmcv.read_img('tests/data/color.jpg')
img = mmcv.pad_img(img, (1000, 1200), pad_val=0)
img = mmcv.pad_img(img, (1000, 1200), pad_val=[100, 50, 200])
```
\ No newline at end of file
Welcome to mmcv's documentation!
==================================
.. toctree::
:maxdepth: 2
intro.md
io.md
image.md
video.md
visualization.md
utils.md
runner.md
api.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`search`
# Introduction
`mmcv` is a foundational python library for computer vision research and supports many
research projects in MMLAB, such as [mmdetection](https://github.com/open-mmlab/mmdetection).
It provides the following functionalities.
- Universal IO APIs
- Image processing
- Video processing
- Image and annotation visualization
- Useful utilities (progress bar, timer, ...)
- PyTorch runner with hooking machanism
- Various CNN architectures
See the [documentation](http://mmcv.readthedocs.io/en/latest) for more features and usage.
## Installation
Try and start with
```shell
pip install mmcv
```
If you want to install from source
```shell
git clone https://github.com/open-mmlab/mmcv.git
cd mmcv
pip install . # (add "-e" if you want to develop or modify the codes)
```
## File IO
This module provides two universal API to load and dump files of different formats.
### Load and dump data
`mmcv` provides a universal api for loading and dumping data, currently
supported formats are json, yaml and pickle.
```python
import mmcv
# load data from a file
data = mmcv.load('test.json')
data = mmcv.load('test.yaml')
data = mmcv.load('test.pickle')
# load data from a file-like object
with open('test.json', 'r') as f:
data = mmcv.load(f)
# dump data to a string
json_str = mmcv.dump(data, format='json')
# dump data to a file with a filename (infer format from file extension)
mmcv.dump(data, 'out.pickle')
# dump data to a file with a file-like object
with open('test.yaml', 'w') as f:
data = mmcv.dump(data, f, format='yaml')
```
### Load a text file as a list or dict
For example `a.txt` is a text file with 5 lines.
```
a
b
c
d
e
```
Then use `list_from_file` to load the list from a.txt.
```python
import mmcv
mmcv.list_from_file('a.txt')
# output ['a', 'b', 'c', 'd', 'e']
mmcv.list_from_file('a.txt', offset=2)
# output ['c', 'd', 'e']
mmcv.list_from_file('a.txt', max_num=2)
# output ['a', 'b']
mmcv.list_from_file('a.txt', prefix='/mnt/')
# output ['/mnt/a', '/mnt/b', '/mnt/c', '/mnt/d', '/mnt/e']
```
For example `b.txt` is a text file with 5 lines.
```
1 cat
2 dog cow
3 panda
```
Then use `dict_from_file` to load the list from a.txt.
```python
import mmcv
mmcv.dict_from_file('b.txt')
# output {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
mmcv.dict_from_file('b.txt', key_type=int)
# output {1: 'cat', 2: ['dog', 'cow'], 3: 'panda'}
```
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
:end
popd
## Runner
The runner module aims to help users to start training with less code, while stays
flexible and configurable.
## Utils
### Config
`Config` class is used for manipulating config and config files. It supports
loading configs from multiple file formats including python scripts, json file and yaml file.
It provides dict-like apis to get and set values.
Here is an example of the config file `test.py`.
```python
a = 1
b = {'b1': [0, 1, 2], 'b2': None}
c = (1, 2)
d = 'string'
```
To load and use configs
```python
cfg = Config.fromfile('test.py')
assert cfg.a == 1
assert cfg.b.b1 == [0, 1, 2]
cfg.c = None
assert cfg.c == None
```
### ProgressBar
If you want to apply a method to a list of items and track the progress, `track_progress`
is a good choice. It will display a progress bar to tell the progress and ETA.
```python
import mmcv
def func(item):
# do something
pass
tasks = [item_1, item_2, ..., item_n]
mmcv.track_progress(func, tasks)
```
The output is like the following.
![progress](_static/progress.gif)
There is another method `track_parallel_progress`, which wraps multiprocessing and
progress visualization.
```python
mmcv.track_parallel_progress(func, tasks, 8) # 8 workers
```
![progress](_static/parallel_progress.gif)
### Timer
It is convinient to compute the runtime of a code block with `Timer`.
```python
import time
with mmcv.Timer():
# simulate some code block
time.sleep(1)
```
or try with `since_start()` and `since_last_check()`. This former can
return the runtime since the timer starts and the latter will return the time
since the last time checked.
```python
timer = mmcv.Timer()
# code block 1 here
print(timer.since_start())
# code block 2 here
print(timer.since_last_check())
print(timer.since_start())
```
## Video
This module provides the following functionalities.
- A `VideoReader` class with friendly apis to read and convert videos.
- Some methods for editing (cut, concat, resize) videos.
- Optical flow read/write.
The `VideoReader` class provides sequence like apis to access video frames.
It will internally cache the frames which have been visited.
```python
video = mmcv.VideoReader('test.mp4')
# obtain basic information
print(len(video))
print(video.width, video.height, video.resolution, video.fps)
# iterate over all frames
for frame in video:
print(frame.shape)
# read the next frame
img = video.read()
# read a frame by index
img = video[100]
# read some frames
img = video[5:10]
```
To convert a video to images or generate a video from a image directory.
```python
# split a video into frames and save to a folder
video = mmcv.VideoReader('test.mp4')
video.cvt2frames('out_dir')
# generate video from frames
mmcv.frames2video('out_dir', 'test.avi')
```
There are also some methods for editing videos, which wraps the commands of ffmpeg.
```python
# cut a video clip
mmcv.cut_video('test.mp4', 'clip1.mp4', start=3, end=10, vcodec='h264')
# join a list of video clips
mmcv.concat_video(['clip1.mp4', 'clip2.mp4'], 'joined.mp4', log_level='quiet')
# resize a video with the specified size
mmcv.resize_video('test.mp4', 'resized1.mp4', (360, 240))
# resize a video with a scaling ratio of 2
mmcv.resize_video('test.mp4', 'resized2.mp4', ratio=2)
```
\ No newline at end of file
## Visualization
`mmcv` can show images and annotations (currently supported types include bounding boxes).
```python
# show an image file
mmcv.imshow('a.jpg')
# show a loaded image
img = np.random.rand(100, 100, 3)
mmcv.imshow(img)
# show image with bounding boxes
img = np.random.rand(100, 100, 3)
bboxes = np.array([[0, 0, 50, 50], [20, 20, 60, 60]])
mmcv.imshow_bboxes(img, bboxes)
```
`mmcv` can also visualize special images such as optical flows.
```python
flow = mmcv.flowread('test.flo')
mmcv.flowshow(flow)
```
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment