Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Readimage png + jpeg #1632

Closed
wants to merge 35 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
11b79e3
Added PNG reading functions
ShahriarSS Aug 10, 2019
9633a49
Adds readpng features
r-zenine Dec 7, 2019
c4528e8
Adds Jpeg Reading Capabilities
r-zenine Dec 27, 2019
5ab970c
Fix type in error message following code review
r-zenine Jan 15, 2020
eed4947
Add's libjpeg-turbo and libpng as third party submodules
r-zenine Feb 9, 2020
ca2df6e
Updates setup.py
r-zenine Feb 9, 2020
be38d3e
update CI to initialize submodules
r-zenine Feb 9, 2020
f813ba9
Change Setup.py to compile third_party before_hand
r-zenine Feb 9, 2020
7b2a48e
fix type
r-zenine Feb 9, 2020
399fce3
add's zlib as a submodule to build libpng
r-zenine Feb 9, 2020
f47d33e
updates setup.py to build zlib with libpn
r-zenine Feb 9, 2020
566c88c
Fix setup.py to compile zlib and libpng correctly
r-zenine Feb 10, 2020
2daae2c
update zlib build options
r-zenine Feb 10, 2020
36371af
Add's cmake to makeos and windows builds
r-zenine Feb 10, 2020
84a3b1b
Fix conda cmake install for macos pipeline
r-zenine Feb 10, 2020
9668086
Deactivating SIMD support for macOS (nasm failing)
r-zenine Feb 10, 2020
181353e
fix cmake path for mac_os_wheel pipeline
r-zenine Feb 10, 2020
b56fdec
Deactivates simd for jpegturbo for macos
r-zenine Feb 10, 2020
6f41c5b
Disable ninja for CI
r-zenine Feb 11, 2020
27fb720
Installing cmake using choco
r-zenine Feb 11, 2020
b5c8274
Updates to fix windows CI.
r-zenine Feb 11, 2020
9bb2d63
fix setup.py cmake
r-zenine Feb 11, 2020
2e63e47
fix setup.py
r-zenine Feb 11, 2020
5019f7b
Use vs2019 as a generator for cmake
r-zenine Feb 11, 2020
46d25d9
Fix quotes for windows
r-zenine Feb 11, 2020
d4af63a
Fix type for cmake in windows
r-zenine Feb 11, 2020
e5f6a06
Fix environment variable for mac build
r-zenine Feb 11, 2020
ee6b182
Fix windown libpng build
r-zenine Feb 11, 2020
0993c1d
linking statically against zlib
r-zenine Feb 12, 2020
317ca14
compiling libpng with -fPIC on linux
r-zenine Feb 12, 2020
d6011fe
Revert "linking statically against zlib"
r-zenine Feb 12, 2020
d03ccfc
Update conda dependencies
r-zenine Feb 12, 2020
9e7b042
fix windows zlib
r-zenine Feb 12, 2020
86aa926
Increase timeout for conda_macos
r-zenine Feb 12, 2020
1ed3ed3
Fix windows
r-zenine Feb 12, 2020
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
12 changes: 11 additions & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ commands:
description: "checkout merge branch"
steps:
- checkout
- run: git submodule update --init --recursive
# - run:
# name: Checkout merge branch
# command: |
Expand Down Expand Up @@ -128,7 +129,7 @@ jobs:
ca-certificates \
curl \
gnupg-agent \
software-properties-common
software-properties-common

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Expand Down Expand Up @@ -184,10 +185,13 @@ jobs:
- checkout_merge
- run:
command: |
choco install cmake --installargs 'ADD_CMAKE_TO_PATH=System'
RefreshEnv.cmd
choco install miniconda3
(& "C:\tools\miniconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | Invoke-Expression
conda activate base
conda install -yq conda-build "conda-package-handling!=1.5.0"
conda install -yq -c anaconda cmake
bash packaging/build_conda.sh
shell: powershell.exe

Expand All @@ -198,10 +202,13 @@ jobs:
- checkout_merge
- run:
command: |
choco install cmake --installargs 'ADD_CMAKE_TO_PATH=System'
RefreshEnv.cmd
choco install miniconda3
(& "C:\tools\miniconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | Invoke-Expression
conda activate base
conda install -yq conda-build "conda-package-handling!=1.5.0"
conda install -yq -c anaconda cmake
bash packaging/build_conda.sh
shell: powershell.exe

Expand All @@ -219,6 +226,7 @@ jobs:
curl -o conda.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh
sh conda.sh -b
source $HOME/miniconda3/bin/activate
conda install -yq -c anaconda cmake
packaging/build_wheel.sh
- store_artifacts:
path: dist
Expand All @@ -239,7 +247,9 @@ jobs:
sh conda.sh -b
source $HOME/miniconda3/bin/activate
conda install -yq conda-build
conda install -yq -c anaconda cmake
packaging/build_conda.sh
no_output_timeout: 30m
- store_artifacts:
path: /Users/distiller/miniconda3/conda-bld/osx-64
- persist_to_workspace:
Expand Down
12 changes: 11 additions & 1 deletion .circleci/config.yml.in
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ commands:
description: "checkout merge branch"
steps:
- checkout
- run: git submodule update --init --recursive
# - run:
# name: Checkout merge branch
# command: |
Expand Down Expand Up @@ -128,7 +129,7 @@ jobs:
ca-certificates \
curl \
gnupg-agent \
software-properties-common
software-properties-common

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Expand Down Expand Up @@ -184,10 +185,13 @@ jobs:
- checkout_merge
- run:
command: |
choco install cmake --installargs 'ADD_CMAKE_TO_PATH=System'
RefreshEnv.cmd
choco install miniconda3
(& "C:\tools\miniconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | Invoke-Expression
conda activate base
conda install -yq conda-build "conda-package-handling!=1.5.0"
conda install -yq -c anaconda cmake
bash packaging/build_conda.sh
shell: powershell.exe

Expand All @@ -198,10 +202,13 @@ jobs:
- checkout_merge
- run:
command: |
choco install cmake --installargs 'ADD_CMAKE_TO_PATH=System'
RefreshEnv.cmd
choco install miniconda3
(& "C:\tools\miniconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | Invoke-Expression
conda activate base
conda install -yq conda-build "conda-package-handling!=1.5.0"
conda install -yq -c anaconda cmake
bash packaging/build_conda.sh
shell: powershell.exe

Expand All @@ -219,6 +226,7 @@ jobs:
curl -o conda.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh
sh conda.sh -b
source $HOME/miniconda3/bin/activate
conda install -yq -c anaconda cmake
packaging/build_wheel.sh
- store_artifacts:
path: dist
Expand All @@ -239,7 +247,9 @@ jobs:
sh conda.sh -b
source $HOME/miniconda3/bin/activate
conda install -yq conda-build
conda install -yq -c anaconda cmake
packaging/build_conda.sh
no_output_timeout: 30m
- store_artifacts:
path: /Users/distiller/miniconda3/conda-bld/osx-64
- persist_to_workspace:
Expand Down
9 changes: 9 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[submodule "third_party/libpng"]
path = third_party/libpng
url = https://github.com/glennrp/libpng
[submodule "third_party/libjpeg-turbo"]
path = third_party/libjpeg-turbo
url = https://github.com/libjpeg-turbo/libjpeg-turbo
[submodule "third_party/zlib"]
path = third_party/zlib
url = https://github.com/madler/zlib
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ matrix:

before_install:
- sudo apt-get update
- sudo apt-get install -y libpng16-16 libpng16-dev libjpeg-turbo8-dev libjpeg-turbo8
- wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh;
- bash miniconda.sh -b -p $HOME/miniconda
- export PATH="$HOME/miniconda/bin:$PATH"
Expand Down
13 changes: 13 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ if(WITH_CUDA)
add_definitions(-D__CUDA_NO_HALF_OPERATORS__)
endif()

add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/third_party/libpng)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/third_party/libjpeg-turbo)
find_package(Torch REQUIRED)
find_package(pybind11 REQUIRED)

Expand All @@ -21,7 +23,17 @@ endif()
file(GLOB MODELS_HEADERS torchvision/csrc/models/*.h)
file(GLOB MODELS_SOURCES torchvision/csrc/models/*.h torchvision/csrc/models/*.cpp)

file(GLOB IMAGE_HEADERS torchvision/csrc/image.h)
file(GLOB IMAGE_SOURCES torchvision/csrc/cpu/image/*.h torchvision/csrc/cpu/image/*.cpp)

add_library(${PROJECT_NAME} SHARED ${MODELS_SOURCES} ${IMAGE_SOURCES})

target_link_libraries(${PROJECT_NAME} PUBLIC "${PNG_LIBRARY}")
target_link_libraries(${PROJECT_NAME} PUBLIC "${LibJPEGTurbo}")
target_link_libraries(${PROJECT_NAME} PUBLIC "${TORCH_LIBRARIES}")

add_library(${PROJECT_NAME} SHARED ${MODELS_SOURCES} ${OPERATOR_SOURCES})

target_link_libraries(${PROJECT_NAME} PRIVATE ${TORCH_LIBRARIES} pybind11::pybind11)
set_target_properties(${PROJECT_NAME} PROPERTIES EXPORT_NAME TorchVision)

Expand Down Expand Up @@ -63,3 +75,4 @@ if(WITH_CUDA)
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/cuda)
endif()
install(FILES ${MODELS_HEADERS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/models)
include_directories(${PNG_INCLUDE_DIR})
3 changes: 3 additions & 0 deletions packaging/pkg_helpers.bash
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,15 @@ setup_build_version() {
else
export BUILD_VERSION="$BUILD_VERSION$VERSION_SUFFIX"
fi
export PATH="$PATH:/Users/distiller/miniconda3/bin"
}

# Set some useful variables for OS X, if applicable
setup_macos() {
if [[ "$(uname)" == Darwin ]]; then
export MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++
# Deactivation SIMD support for MacOS for jpegturbo as the nasm version provided with the CI is failing
export WITH_SIMD=0
fi
}

Expand Down
3 changes: 3 additions & 0 deletions packaging/torchvision/meta.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ source:
requirements:
build:
- {{ compiler('c') }} # [win]
- zlib

host:
- python
Expand All @@ -21,6 +22,8 @@ requirements:
- pillow >=4.1.1
- numpy >=1.11
- six
- libpng
- libjpeg-turbo
{{ environ.get('CONDA_PYTORCH_CONSTRAINT') }}
{{ environ.get('CONDA_CUDATOOLKIT_CONSTRAINT') }}

Expand Down
1 change: 0 additions & 1 deletion packaging/wheel/linux_manywheel.sh
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ rm -rf vision
git clone https://github.com/pytorch/vision

cd /tmp/vision

for PYDIR in "${python_installations[@]}"; do
export PATH=$PYDIR/bin:$OLD_PATH
pip install --upgrade pip
Expand Down
93 changes: 66 additions & 27 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import torch
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME


def read(*names, **kwargs):
with io.open(
os.path.join(os.path.dirname(__file__), *names),
Expand Down Expand Up @@ -76,16 +75,51 @@ def write_version_file():
pillow_req = 'pillow-simd' if get_dist('pillow-simd') is not None else 'pillow'
requirements.append(pillow_req + pillow_ver)

third_party_libraries = ['png', 'turbojpeg']
third_party_dir = os.path.join(cwd, "third_party")
third_party_lib_directories = ['libpng', 'libjpeg-turbo']
third_party_search_directories = [os.path.join(third_party_dir, directory) for directory in third_party_lib_directories]

def _build_cmake_dependency(directory, args=""):
os.chdir(directory)
if sys.platform == 'win32':
os.system("cmake.exe --clean .")
os.system('cmake.exe -G"Visual Studio 16 2019" -DCMAKE_BUILD_TYPE=Release {} .'.format(args) )
os.system("cmake.exe --build .")
else:
os.system("cmake --clean .")
os.system("cmake {} . ".format(args))
os.system("cmake --build .")
os.chdir(cwd)


def build_dependencies():
Copy link
Contributor

Choose a reason for hiding this comment

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

This is how PyTorch set this up in case you didn't see it. There might be some patterns that could be borrowed from this.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hi,
I took a look. I'll grab some code.
Thanks

zlib_path = os.path.join(third_party_dir, "zlib")
if sys.platform == "win32":
libpng_cmake_options="-DPNG_BUILD_ZLIB=ON -DZLIB_INCLUDE_DIR:PATH={zlib_path} -DZLIB_LIBRARY:FILEPATH={zlib_path}/Debug/zlibd.dll".format(zlib_path=zlib_path)
elif sys.platform == "darwin":
libpng_cmake_options="-DPNG_BUILD_ZLIB=ON -DZLIB_INCLUDE_DIR:PATH={zlib_path} -DZLIB_LIBRARY:FILEPATH={zlib_path}/libz.dylib".format(zlib_path=zlib_path)
else :
libpng_cmake_options="-DPNG_BUILD_ZLIB=ON -DZLIB_INCLUDE_DIR:PATH={zlib_path} -DZLIB_LIBRARY:FILEPATH={zlib_path}/libz.so".format(zlib_path=zlib_path)
_build_cmake_dependency("./third_party/zlib")
# Deactivate SIMD on macOS
jpeg_turbo_options = ""
if sys.platform == "darwin":
jpeg_turbo_options ="-DWITH_SIMD=0"
_build_cmake_dependency("./third_party/libpng", libpng_cmake_options)
_build_cmake_dependency("./third_party/libjpeg-turbo", jpeg_turbo_options)


def get_extensions():
this_dir = os.path.dirname(os.path.abspath(__file__))
extensions_dir = os.path.join(this_dir, 'torchvision', 'csrc')

main_file = glob.glob(os.path.join(extensions_dir, '*.cpp'))
source_cpu = glob.glob(os.path.join(extensions_dir, 'cpu', '*.cpp'))
source_image_cpu = glob.glob(os.path.join(extensions_dir, 'cpu', 'image', '*.cpp'))
source_cuda = glob.glob(os.path.join(extensions_dir, 'cuda', '*.cu'))

sources = main_file + source_cpu
sources = main_file + source_cpu + source_image_cpu
extension = CppExtension

compile_cpp_tests = os.getenv('WITH_CPP_MODELS_TEST', '0') == '1'
Expand Down Expand Up @@ -142,7 +176,9 @@ def get_extensions():
extension(
'torchvision._C',
sources,
include_dirs=include_dirs,
libraries= third_party_libraries,
include_dirs=include_dirs + third_party_search_directories,
library_dirs=third_party_search_directories,
define_macros=define_macros,
extra_compile_args=extra_compile_args,
)
Expand Down Expand Up @@ -196,29 +232,32 @@ def run(self):
# It's an old-style class in Python 2.7...
distutils.command.clean.clean.run(self)

def build_ext_with_dependencies(self):
build_dependencies()
return BuildExtension.with_options(no_python_abi_suffix=True, use_ninja=False )(self)

setup(
# Metadata
name=package_name,
version=version,
author='PyTorch Core Team',
author_email='[email protected]',
url='https://github.com/pytorch/vision',
description='image and video datasets and models for torch deep learning',
long_description=readme,
license='BSD',

# Package info
packages=find_packages(exclude=('test',)),

zip_safe=False,
install_requires=requirements,
extras_require={
"scipy": ["scipy"],
},
ext_modules=get_extensions(),
cmdclass={
'build_ext': BuildExtension.with_options(no_python_abi_suffix=True),
'clean': clean,
}
)
# Metadata
name=package_name,
version=version,
author='PyTorch Core Team',
author_email='[email protected]',
url='https://github.com/pytorch/vision',
description='image and video datasets and models for torch deep learning',
long_description=readme,
license='BSD',
# Package info
packages=find_packages(exclude=('test',)),
zip_safe=False,
install_requires=requirements,
extras_require={
"scipy": ["scipy"],
},
ext_modules=get_extensions(),
cmdclass={
'build_ext': build_ext_with_dependencies,
'clean': clean,
}
)
50 changes: 50 additions & 0 deletions test/test_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import os
import unittest

import torch
from PIL import Image
from torchvision.io.image import read_png, decode_png, decode_jpeg, read_jpeg
import numpy as np

IMAGE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "fakedata", "imagefolder")


def get_images(directory, img_ext):
assert os.path.isdir(directory)
for root, dir, files in os.walk(directory):
for fl in files:
_, ext = os.path.splitext(fl)
if ext == img_ext:
yield os.path.join(root, fl)


class ImageTester(unittest.TestCase):
def test_read_png(self):
for img_path in get_images(IMAGE_DIR, "png"):
img_pil = torch.from_numpy(np.array(Image.open(img_path)))
img_lpng = read_png(img_path)
self.assertTrue(torch.all(img_lpng == img_pil))
Copy link
Contributor

@cpuhrsch cpuhrsch Feb 11, 2020

Choose a reason for hiding this comment

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

It might be better to use assertEqual since it checks for matching dtypes, etc. etc. ; unless you have a specific reason not to?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good Catch Thanks


def test_decode_png(self):
for img_path in get_images(IMAGE_DIR, "png"):
img_pil = torch.from_numpy(np.array(Image.open(img_path)))
size = os.path.getsize(img_path)
img_lpng = decode_png(torch.from_file(img_path, dtype=torch.uint8, size=size))
self.assertTrue(torch.all(img_lpng == img_pil))

def test_read_jpeg(self):
for img_path in get_images(IMAGE_DIR, "jpg"):
img_pil = torch.from_numpy(np.array(Image.open(img_path)))
img_ljpeg = read_jpeg(img_path)
self.assertTrue(torch.all(img_ljpeg == img_pil))

def test_decode_jpeg(self):
for img_path in get_images(IMAGE_DIR, "jpg"):
img_pil = torch.from_numpy(np.array(Image.open(img_path)))
size = os.path.getsize(img_path)
img_ljpeg = decode_png(torch.from_file(img_path, dtype=torch.uint8, size=size))
self.assertTrue(torch.all(img_ljpeg == img_pil))


if __name__ == '__main__':
unittest.main()
1 change: 1 addition & 0 deletions third_party/libjpeg-turbo
Submodule libjpeg-turbo added at f81833
Loading