Skip to content
Commits on Source (9)
[bumpversion]
current_version = 0.1.0
current_version = 0.2.0
commit = True
tag = True
......
linters:
flake8:
python: 3
fixer: true
max-line-length: 120
fixers:
enable: true
language: python
python:
- "2.7"
- "3.6"
- "3.7"
install:
- pip install codecov pytest pytest-cov trollimage xarray dask[array]
- pip install -e .
script:
- pytest --cov=./
after_success:
- codecov
......@@ -2,6 +2,85 @@ Changelog
=========
v0.2.0 (2019-09-19)
-------------------
- update changelog. [Martin Raspaud]
- Bump version: 0.1.0 → 0.2.0. [Martin Raspaud]
- Merge pull request #18 from mraspaud/fix-user-home-path. [Martin
Raspaud]
Fix user home path
- Fix travis to improve coverage. [Martin Raspaud]
- Expand the config filename in case ~ is used. [Martin Raspaud]
- Merge pull request #17 from mraspaud/fix-python3-configparser. [Martin
Raspaud]
Fix python2-only configparser import
- Fix python2-only configparser import. [Martin Raspaud]
- Merge pull request #16 from mraspaud/fix-tests. [Martin Raspaud]
Fix test dependencies
- Fix area definitions in the tests. [Martin Raspaud]
- Add pyresample to setup dependencies. [Martin Raspaud]
- Add pyproj to setup dependencies. [Martin Raspaud]
- Fix dask array dependencies. [Martin Raspaud]
- Fix test dependencies. [Martin Raspaud]
- Fix .travis.yml file. [Martin Raspaud]
- Merge pull request #14 from pytroll/feature-python3. [Martin Raspaud]
Support for python3 and unittests
- Fix P test. [Martin Raspaud]
- Add draft test for P mode. [Martin Raspaud]
- Use _FillValue to mask integer arrays. [Martin Raspaud]
- Add trollimage to test dependencies. [Martin Raspaud]
- Add codecov to travis. [Martin Raspaud]
- Fix channel in vis tests. [Martin Raspaud]
- Fix stickler line length. [Martin Raspaud]
- Fixing style errors. [stickler-ci]
- Add tests. [Martin Raspaud]
- Fix scaling bw images. [Martin Raspaud]
- Fix style. [Martin Raspaud]
- Fixing style errors. [stickler-ci]
- Start supporting python3. [Martin Raspaud]
- Merge pull request #13 from pytroll/add-stickler-config. [Martin
Raspaud]
Adding .stickler.yml configuration file
- Adding .stickler.yml. [stickler-ci]
- Merge pull request #9 from pytroll/develop. [David Hoese]
Merge the develop branch in to master
- Merge pull request #3 from goodsonr/compatability-python3. [Martin
Raspaud]
change all occurences of xrange to range for compatability with Python3
- change all occurences of xrange to range for compatability with
Python3. [ron goodson]
- Add zero seconds option to zero the seconds of the DateID. [Martin
Raspaud]
- Fix package description. [Martin Raspaud]
- Merge pull request #5 from loreclem/master. [David Hoese]
WIP|PCW: first attempt to make pyninjotiff xarray compatible.
- Merge pull request #2 from vgiuffrida/master. [lorenzo clementi]
fix not assigned fill_value and a config file loader issue
- fix not assigned fill_value and config file loader. [root]
- fix fill_value and config file loader. [root]
- Merge pull request #1 from vgiuffrida/master. [lorenzo clementi]
Add new parameter to configure the ninjotiff config file to use
- Add ninjotiff configuration file loading. [root]
- Typos corrected and removed is_masked. [cll]
- Bugfix (is_masked computed twice) [cll]
- WIP Improvements here and there. [cll]
- Using finalize instead of fill_or_alpha. [cll]
- It now can handle also RGB images. [cll]
- WIP: first attempt to make pyninjotiff xarray compatible. For the
moment, only the 'L' case (1 band) has been upgraded. Still to be
verified. [cll]
v0.1.0 (2017-10-16)
-------------------
- update changelog. [Martin Raspaud]
......
pyninjotiff (0.1.0-2) UNRELEASED; urgency=medium
pyninjotiff (0.2.0-1) unstable; urgency=medium
* Team upload.
[ Bas Couwenberg ]
* Update gbp.conf to use --source-only-changes by default.
* Bump Standards-Version to 4.4.0, no changes.
-- Bas Couwenberg <sebastic@debian.org> Sun, 07 Jul 2019 09:40:37 +0200
[ Antonio Valentino ]
* New upstream release.
* Bump debhelper from old 11 to 12.
* Remove obsolete fields Name from debian/upstream/metadata.
* Update copyright file.
* debian/patches:
- remove all patches (no longer needed)
* Enable testing (add dependencies on pytest, xarray and trollimage).
-- Antonio Valentino <antonio.valentino@tiscali.it> Sat, 21 Sep 2019 09:38:30 +0000
pyninjotiff (0.1.0-1) unstable; urgency=medium
......
......@@ -4,15 +4,19 @@ Uploaders: Antonio Valentino <antonio.valentino@tiscali.it>
Section: python
Priority: optional
Testsuite: autopkgtest-pkg-python
Build-Depends: debhelper (>= 11),
Build-Depends: debhelper-compat (= 12),
dh-python,
python3-all,
python3-dask,
python3-matplotlib,
python3-numpy,
python3-pyproj,
python3-pyresample,
python3-pytest,
python3-setuptools,
python3-six
python3-six,
python3-trollimage,
python3-xarray
Standards-Version: 4.4.0
Vcs-Browser: https://salsa.debian.org/debian-gis-team/pyninjotiff
Vcs-Git: https://salsa.debian.org/debian-gis-team/pyninjotiff.git
......
......@@ -4,7 +4,7 @@ Upstream-Contact: Martin Raspaud <martin.raspaud@smhi.se>
Source: https://github.com/pytroll/pyninjotiff
Files: *
Copyright: 2017 Martin Raspaud <martin.raspaud@smhi.se>
Copyright: 2017-2019 Martin Raspaud <martin.raspaud@smhi.se>
2013 Space Science and Engineering Center (SSEC),
University of Wisconsin-Madison. Lars Ørum Rasmussen, DMI.
License: GPL-3+
......@@ -14,7 +14,7 @@ Copyright: 2008-2014 Christoph Gohlke
License: BSD-3-clause
Files: debian/*
Copyright: 2018 Antonio Valentino <antonio.valentino@tiscali.it>
Copyright: 2018-2019 Antonio Valentino <antonio.valentino@tiscali.it>
License: GPL-3+
License: GPL-3+
......
From: Antonio Valentino <antonio.valentino@tiscali.it>
Date: Mon, 31 Dec 2018 17:15:28 +0000
Subject: Python 3 compatibility
---
pyninjotiff/ninjotiff.py | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)
diff --git a/pyninjotiff/ninjotiff.py b/pyninjotiff/ninjotiff.py
index 16b8374..813f672 100644
--- a/pyninjotiff/ninjotiff.py
+++ b/pyninjotiff/ninjotiff.py
@@ -35,6 +35,8 @@ Edited by Christian Kliche (Ernst Basler + Partner) to replace pylibtiff with
a modified version of tifffile.py (created by Christoph Gohlke)
"""
+from __future__ import print_function
+
import calendar
import logging
import os
@@ -176,7 +178,10 @@ class ProductConfigs(object):
return sorted(self._products.keys())
def read_config(self):
- from ConfigParser import ConfigParser
+ try:
+ from ConfigParser import ConfigParser
+ except ImportError:
+ from configparser import ConfigParser
def _eval(val):
try:
@@ -1060,9 +1065,9 @@ if __name__ == '__main__':
try:
filename = args[0]
except IndexError:
- print >> sys.stderr, """usage: python ninjotiff.py [<-p page-number>] [-c] <ninjotiff-filename>
+ print("""usage: python ninjotiff.py [<-p page-number>] [-c] <ninjotiff-filename>
-p <page-number>: print page number (default are all pages).
- -c: print color maps (default is not to print color maps)."""
+ -c: print color maps (default is not to print color maps).""", file=sys.stderr)
sys.exit(2)
pages = read_tags(filename)
@@ -1070,12 +1075,12 @@ if __name__ == '__main__':
try:
pages = [pages[page_no]]
except IndexError:
- print >>sys.stderr, "Invalid page number '%d'" % page_no
+ print("Invalid page number '%d'" % page_no, file=sys.stderr)
sys.exit(2)
for page in pages:
names = sorted(page.keys())
- print ""
+ print("")
for name in names:
if not print_color_maps and name == "color_map":
continue
- print name, page[name]
+ print(name, page[name])
From: Antonio Valentino <antonio.valentino@tiscali.it>
Date: Mon, 31 Dec 2018 17:33:47 +0000
Subject: Disable pointless warning
---
pyninjotiff/tifffile.py | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/pyninjotiff/tifffile.py b/pyninjotiff/tifffile.py
index 3e0cf23..29ebadb 100644
--- a/pyninjotiff/tifffile.py
+++ b/pyninjotiff/tifffile.py
@@ -148,13 +148,13 @@ from xml.etree import cElementTree as etree
import numpy
-try:
- import _tifffile
-except ImportError:
- warnings.warn(
- "failed to import the optional _tifffile C extension module.\n"
- "Loading of some compressed images will be slow.\n"
- "Tifffile.c can be obtained at http://www.lfd.uci.edu/~gohlke/")
+# try:
+# import _tifffile
+# except ImportError:
+# warnings.warn(
+# "failed to import the optional _tifffile C extension module.\n"
+# "Loading of some compressed images will be slow.\n"
+# "Tifffile.c can be obtained at http://www.lfd.uci.edu/~gohlke/")
__version__ = '2014.08.24'
__docformat__ = 'restructuredtext en'
0001-Python-3-compatibility.patch
0002-Disable-pointless-warning.patch
......@@ -5,7 +5,7 @@
#export DH_VERBOSE=1
export PYBUILD_NAME=pyninjotiff
export PYBUILD_DISABLE=test
export PYBUILD_BEFORE_TEST=cp -r {dir}/pyninjotiff/tests {build_dir}
%:
dh $@ --with python3 --buildsystem=pybuild
......
---
Bug-Database: https://github.com/pytroll/pyninjotiff/issues
Bug-Submit: https://github.com/pytroll/pyninjotiff/issues/new
Name: PyNinjoTiff
Repository: https://github.com/pytroll/pyninjotiff.git
Repository-Browse: https://github.com/pytroll/pyninjotiff
This diff is collapsed.
import os
from satpy import Scene
from datetime import datetime
from satpy.utils import debug_on
import pyninjotiff
from glob import glob
from pyresample.utils import load_area
import copy
debug_on()
chn = "IR_108"
ninjoRegion = load_area("areas.def", "nrEURO3km")
filenames = glob("data/*__")
global_scene = Scene(reader="hrit_msg", filenames=filenames)
global_scene.load([chn])
local_scene = global_scene.resample(ninjoRegion)
local_scene.save_dataset(chn, filename="msg.tif", writer='ninjotiff',
# ninjo product name to look for in .cfg file
ninjo_product_name="IR_108",
# custom configuration file for ninjo tiff products
# if not specified PPP_CONFIG_DIR is used as config file directory
ninjo_product_file="/config_dir/ninjotiff_products.cfg")
......@@ -3,19 +3,23 @@ from satpy import Scene
from datetime import datetime
from satpy.utils import debug_on
import pyninjotiff
from glob import glob
from pyresample.utils import load_area
import copy
debug_on()
chn=10.8
time_slot = datetime(2017, 1, 27, 7, 45)
global_data = Scene(platform_name="Meteosat-10", sensor="seviri", reader="hrit_msg", start_time=time_slot)
chn = "IR_108"
ninjoRegion = load_area("areas.def", "nrEURO3km")
global_data.load([chn])
local_scene = global_data.resample("NinJoRegion")
filenames = glob("data/*__")
global_scene = Scene(reader="hrit_msg", filenames=filenames)
global_scene.load([chn])
local_scene = global_scene.resample(ninjoRegion)
local_scene.save_dataset(chn, filename="msg.tif", writer='ninjotiff',
sat_id=1234,
chan_id=5678,
sat_id=6300014,
chan_id=900015,
data_cat='GORN',
data_source='EUMETSAT/MeteoSwiss',
data_source='EUMCAST',
physic_unit='K',
nbits=8)
import os
from satpy import Scene
from datetime import datetime
from satpy.utils import debug_on
import pyninjotiff
from glob import glob
from pyresample.utils import load_area
debug_on()
chn = "airmass"
ninjoRegion = load_area("areas.def", "nrEURO3km")
filenames = glob("data/*__")
global_scene = Scene(reader="hrit_msg", filenames=filenames)
global_scene.load([chn])
local_scene = global_scene.resample(ninjoRegion)
local_scene.save_dataset(chn, filename="airmass.tif", writer='ninjotiff',
sat_id=6300014,
chan_id=6500015,
data_cat='GPRN',
data_source='EUMCAST',
nbits=8)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2019 Martin Raspaud
# Author(s):
# Martin Raspaud <martin.raspaud@smhi.se>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Test the ninjotiff writing."""
import numpy as np
import datetime
import tempfile
import xarray as xr
import dask.array as da
import colorsys
import pytest
TIME = datetime.datetime.utcnow()
DELETE_FILES = True
class FakeImage(object):
"""Fake Image object for testing purposes."""
def __init__(self, data):
"""Initialize the image."""
self.mode = ''.join(data.bands.values)
self.data = data
def finalize(self, fill_value=None, dtype=None):
if dtype is None:
dtype = np.uint8
if np.issubdtype(self.data.dtype, np.floating) and np.issubdtype(dtype, np.integer):
res = self.data.clip(0, 1) * np.iinfo(dtype).max
res = res.astype(dtype)
else:
res = self.data
return [res.astype(dtype)]
class FakeArea(object):
def __init__(self, proj_dict, extent, y_size, x_size):
self.proj_dict = proj_dict
self.area_extent = extent
self.x_size, self.y_size = x_size, y_size
self.pixel_size_x = (extent[2] - extent[0]) / x_size
self.pixel_size_y = (extent[3] - extent[1]) / y_size
def test_write_bw():
"""Test saving a BW image."""
from pyninjotiff.ninjotiff import save
from pyninjotiff.tifffile import TiffFile
area = FakeArea({'ellps': 'WGS84', 'lat_0': 90.0, 'lat_ts': 60.0, 'lon_0': 0.0, 'proj': 'stere'},
(-1000000.0, -4500000.0, 2072000.0, -1428000.0),
1024, 1024)
scale = 1.0 / 120
offset = 0.0
attrs = dict([('resolution', 1050),
('polarization', None),
('platform_name', 'NOAA-18'),
('sensor', 'avhrr-3'),
('units', '%'),
('name', '1'),
('level', None),
('modifiers', ()),
('wavelength', (10.3, 10.8, 11.3)),
('calibration', 'brightness_temperature'),
('start_time', TIME - datetime.timedelta(minutes=5)),
('end_time', TIME),
('area', area),
('ancillary_variables', []),
('enhancement_history', [{'offset': offset, 'scale': scale}])])
kwargs = {'ch_min_measurement_unit': np.array([0]),
'ch_max_measurement_unit': np.array([120]),
'compute': True, 'fill_value': None, 'sat_id': 6300014,
'chan_id': 100015, 'data_cat': 'PORN', 'data_source': 'SMHI',
'physic_unit': '%', 'nbits': 8}
data = da.tile(da.repeat(da.arange(4, chunks=1024) /
3.0, 256), 1024).reshape((1, 1024, 1024))
data = xr.DataArray(data, coords={'bands': ['L']}, dims=[
'bands', 'y', 'x'], attrs=attrs)
img = FakeImage(data)
with tempfile.NamedTemporaryFile(delete=DELETE_FILES) as tmpfile:
filename = tmpfile.name
if not DELETE_FILES:
print(filename)
save(img, filename, data_is_scaled_01=True, **kwargs)
tif = TiffFile(filename)
res = tif[0].asarray()
assert(np.allclose(res[0, 0, ::256],
np.array([256, 22016, 43520, 65280])))
def test_write_bw_inverted_ir():
"""Test saving a BW image."""
from pyninjotiff.ninjotiff import save
from pyninjotiff.tifffile import TiffFile
area = FakeArea({'ellps': 'WGS84', 'lat_0': 90.0, 'lat_ts': 60.0, 'lon_0': 0.0, 'proj': 'stere'},
(-1000000.0, -4500000.0, 2072000.0, -1428000.0),
1024, 1024)
scale = 1.0 / 120
offset = 70.0 / 120
attrs = dict([('resolution', 1050),
('polarization', None),
('platform_name', 'NOAA-18'),
('sensor', 'avhrr-3'),
('units', 'K'),
('name', '4'),
('level', None),
('modifiers', ()),
('wavelength', (10.3, 10.8, 11.3)),
('calibration', 'brightness_temperature'),
('start_time', TIME - datetime.timedelta(minutes=15)),
('end_time', TIME - datetime.timedelta(minutes=10)),
('area', area),
('ancillary_variables', []),
('enhancement_history', [{'offset': offset, 'scale': scale}])])
kwargs = {'ch_min_measurement_unit': np.array([-70]),
'ch_max_measurement_unit': np.array([50]),
'compute': True, 'fill_value': None, 'sat_id': 6300014,
'chan_id': 900015, 'data_cat': 'PORN', 'data_source': 'SMHI',
'physic_unit': 'C', 'nbits': 8}
data = da.tile(da.repeat(da.arange(4, chunks=1024) /
3.0, 256), 1024).reshape((1, 1024, 1024))
data = xr.DataArray(data, coords={'bands': ['L']}, dims=[
'bands', 'y', 'x'], attrs=attrs)
img = FakeImage(data)
with tempfile.NamedTemporaryFile(delete=DELETE_FILES) as tmpfile:
filename = tmpfile.name
if not DELETE_FILES:
print(filename)
save(img, filename, data_is_scaled_01=True, **kwargs)
tif = TiffFile(filename)
res = tif[0].asarray()
assert(np.allclose(res[0, 0, ::256],
np.array([65024, 43264, 21760, 0])))
def test_write_bw_fill():
"""Test saving a BW image with transparency."""
from pyninjotiff.ninjotiff import save
from pyninjotiff.tifffile import TiffFile
area = FakeArea({'ellps': 'WGS84', 'lat_0': 90.0, 'lat_ts': 60.0, 'lon_0': 0.0, 'proj': 'stere'},
(-1000000.0, -4500000.0, 2072000.0, -1428000.0),
1024, 1024)
scale = 1.0 / 120
offset = 0.0
attrs = dict([('resolution', 1050),
('polarization', None),
('platform_name', 'NOAA-18'),
('sensor', 'avhrr-3'),
('units', '%'),
('name', '1'),
('level', None),
('modifiers', ()),
('wavelength', (10.3, 10.8, 11.3)),
('calibration', 'brightness_temperature'),
('start_time', TIME - datetime.timedelta(minutes=25)),
('end_time', TIME - datetime.timedelta(minutes=20)),
('area', area),
('ancillary_variables', []),
('enhancement_history', [{'offset': offset, 'scale': scale}])])
kwargs = {'ch_min_measurement_unit': np.array([0]),
'ch_max_measurement_unit': np.array([120]),
'compute': True, 'fill_value': None, 'sat_id': 6300014,
'chan_id': 100015, 'data_cat': 'PORN', 'data_source': 'SMHI',
'physic_unit': '%', 'nbits': 8}
data1 = da.tile(da.repeat(da.arange(4, chunks=1024) /
3.0, 256), 256).reshape((1, 256, 1024))
datanan = da.ones((1, 256, 1024), chunks=1024) * np.nan
data2 = da.tile(da.repeat(da.arange(4, chunks=1024) /
3.0, 256), 512).reshape((1, 512, 1024))
data = da.concatenate((data1, datanan, data2), axis=1)
data = xr.DataArray(data, coords={'bands': ['L']}, dims=[
'bands', 'y', 'x'], attrs=attrs)
img = FakeImage(data)
with tempfile.NamedTemporaryFile(delete=DELETE_FILES) as tmpfile:
filename = tmpfile.name
if not DELETE_FILES:
print(filename)
save(img, filename, data_is_scaled_01=True, **kwargs)
tif = TiffFile(filename)
res = tif[0].asarray()
assert(np.allclose(res[0, 0, ::256],
np.array([256, 22016, 43520, 65280])))
def test_write_bw_inverted_ir_fill():
"""Test saving a BW image with transparency."""
from pyninjotiff.ninjotiff import save
from pyninjotiff.tifffile import TiffFile
area = FakeArea({'ellps': 'WGS84', 'lat_0': 90.0, 'lat_ts': 60.0, 'lon_0': 0.0, 'proj': 'stere'},
(-1000000.0, -4500000.0, 2072000.0, -1428000.0),
1024, 1024)
scale = 1.0 / 120
offset = 70.0 / 120
attrs = dict([('resolution', 1050),
('polarization', None),
('platform_name', 'NOAA-18'),
('sensor', 'avhrr-3'),
('units', 'K'),
('name', '4'),
('level', None),
('modifiers', ()),
('wavelength', (10.3, 10.8, 11.3)),
('calibration', 'brightness_temperature'),
('start_time', TIME - datetime.timedelta(minutes=35)),
('end_time', TIME - datetime.timedelta(minutes=30)),
('area', area),
('ancillary_variables', []),
('enhancement_history', [{'offset': offset, 'scale': scale}])])
kwargs = {'ch_min_measurement_unit': np.array([-70]),
'ch_max_measurement_unit': np.array([50]),
'compute': True, 'fill_value': None, 'sat_id': 6300014,
'chan_id': 900015, 'data_cat': 'PORN', 'data_source': 'SMHI',
'physic_unit': 'C', 'nbits': 8}
data1 = da.tile(da.repeat(da.arange(4, chunks=1024) /
3.0, 256), 256).reshape((1, 256, 1024))
datanan = da.ones((1, 256, 1024), chunks=1024) * np.nan
data2 = da.tile(da.repeat(da.arange(4, chunks=1024) /
3.0, 256), 512).reshape((1, 512, 1024))
data = da.concatenate((data1, datanan, data2), axis=1)
data = xr.DataArray(data, coords={'bands': ['L']}, dims=[
'bands', 'y', 'x'], attrs=attrs)
img = FakeImage(data)
with tempfile.NamedTemporaryFile(delete=DELETE_FILES) as tmpfile:
filename = tmpfile.name
if not DELETE_FILES:
print(filename)
save(img, filename, data_is_scaled_01=True, **kwargs)
tif = TiffFile(filename)
res = tif[0].asarray()
assert(np.allclose(res[0, 0, ::256],
np.array([65024, 43264, 21760, 0])))
def test_write_rgb():
"""Test saving a non-trasparent RGB."""
from pyninjotiff.ninjotiff import save
from pyninjotiff.tifffile import TiffFile
area = FakeArea({'ellps': 'WGS84', 'lat_0': 90.0, 'lat_ts': 60.0, 'lon_0': 0.0, 'proj': 'stere'},
(-1000000.0, -4500000.0, 2072000.0, -1428000.0),
1024, 1024)
x_size, y_size = 1024, 1024
arr = np.zeros((3, y_size, x_size))
radius = min(x_size, y_size) / 2.0
centre = x_size / 2, y_size / 2
for x in range(x_size):
for y in range(y_size):
rx = x - centre[0]
ry = y - centre[1]
s = ((x - centre[0])**2.0 + (y - centre[1])**2.0)**0.5 / radius
if s <= 1.0:
h = ((np.arctan2(ry, rx) / np.pi) + 1.0) / 2.0
rgb = colorsys.hsv_to_rgb(h, s, 1.0)
arr[:, y, x] = np.array(rgb)
attrs = dict([('platform_name', 'NOAA-18'),
('resolution', 1050),
('polarization', None),
('level', None),
('sensor', 'avhrr-3'),
('ancillary_variables', []),
('area', area),
('start_time', TIME - datetime.timedelta(minutes=45)),
('end_time', TIME - datetime.timedelta(minutes=40)),
('wavelength', None),
('optional_datasets', []),
('standard_name', 'overview'),
('name', 'overview'),
('prerequisites', [0.6, 0.8, 10.8]),
('optional_prerequisites', []),
('calibration', None),
('modifiers', None),
('mode', 'RGB'),
('enhancement_history', [{'scale': np.array([1, 1, -1]), 'offset': np.array([0, 0, 1])},
{'scale': np.array([0.0266347, 0.03559078, 0.01329783]),
'offset': np.array([-0.02524969, -0.01996642, 3.8918446])},
{'gamma': 1.6}])])
kwargs = {'compute': True, 'fill_value': None, 'sat_id': 6300014,
'chan_id': 6500015, 'data_cat': 'PPRN', 'data_source': 'SMHI', 'nbits': 8}
data = da.from_array(arr.clip(0, 1), chunks=1024)
data = xr.DataArray(data, coords={'bands': ['R', 'G', 'B']}, dims=[
'bands', 'y', 'x'], attrs=attrs)
from trollimage.xrimage import XRImage
img = XRImage(data)
with tempfile.NamedTemporaryFile(delete=DELETE_FILES) as tmpfile:
filename = tmpfile.name
if not DELETE_FILES:
print(filename)
save(img, filename, data_is_scaled_01=False, **kwargs)
tif = TiffFile(filename)
res = tif[0].asarray()
for idx in range(3):
np.testing.assert_allclose(res[:, :, idx], np.round(
arr[idx, :, :] * 255).astype(np.uint8))
def test_write_rgb_with_a():
"""Test saving a transparent RGB."""
from pyninjotiff.ninjotiff import save
from pyninjotiff.tifffile import TiffFile
area = FakeArea({'ellps': 'WGS84', 'lat_0': 90.0, 'lat_ts': 60.0, 'lon_0': 0.0, 'proj': 'stere'},
(-1000000.0, -4500000.0, 2072000.0, -1428000.0),
1024, 1024)
x_size, y_size = 1024, 1024
arr = np.zeros((3, y_size, x_size))
radius = min(x_size, y_size) / 2.0
centre = x_size / 2, y_size / 2
for x in range(x_size):
for y in range(y_size):
rx = x - centre[0]
ry = y - centre[1]
s = ((x - centre[0])**2.0 + (y - centre[1])**2.0)**0.5 / radius
if s <= 1.0:
h = ((np.arctan2(ry, rx) / np.pi) + 1.0) / 2.0
rgb = colorsys.hsv_to_rgb(h, s, 1.0)
arr[:, y, x] = np.array(rgb)
else:
arr[:, y, x] = np.nan
attrs = dict([('platform_name', 'NOAA-18'),
('resolution', 1050),
('polarization', None),
('start_time', TIME - datetime.timedelta(minutes=55)),
('end_time', TIME - datetime.timedelta(minutes=50)),
('level', None),
('sensor', 'avhrr-3'),
('ancillary_variables', []),
('area', area),
('wavelength', None),
('optional_datasets', []),
('standard_name', 'overview'),
('name', 'overview'),
('prerequisites', [0.6, 0.8, 10.8]),
('optional_prerequisites', []),
('calibration', None),
('modifiers', None),
('mode', 'RGB'),
('enhancement_history', [{'scale': np.array([1, 1, -1]), 'offset': np.array([0, 0, 1])},
{'scale': np.array([0.0266347, 0.03559078, 0.01329783]),
'offset': np.array([-0.02524969, -0.01996642, 3.8918446])},
{'gamma': 1.6}])])
kwargs = {'compute': True, 'fill_value': None, 'sat_id': 6300014,
'chan_id': 6500015, 'data_cat': 'PPRN', 'data_source': 'SMHI', 'nbits': 8}
data = da.from_array(arr.clip(0, 1), chunks=1024)
data = xr.DataArray(data, coords={'bands': ['R', 'G', 'B']}, dims=[
'bands', 'y', 'x'], attrs=attrs)
from trollimage.xrimage import XRImage
img = XRImage(data)
with tempfile.NamedTemporaryFile(delete=DELETE_FILES) as tmpfile:
filename = tmpfile.name
if not DELETE_FILES:
print(filename)
save(img, filename, data_is_scaled_01=True, **kwargs)
tif = TiffFile(filename)
res = tif[0].asarray()
for idx in range(3):
np.testing.assert_allclose(res[:, :, idx], np.round(
np.nan_to_num(arr[idx, :, :]) * 255).astype(np.uint8))
np.testing.assert_allclose(res[:, :, 3] == 0, np.isnan(arr[0, :, :]))
@pytest.mark.skip(reason="this is no implemented yet.")
def test_write_rgb_classified():
"""Test saving a transparent RGB."""
from pyninjotiff.ninjotiff import save
from pyninjotiff.tifffile import TiffFile
area = FakeArea({'ellps': 'WGS84', 'lat_0': 90.0, 'lat_ts': 60.0, 'lon_0': 0.0, 'proj': 'stere'},
(-1000000.0, -4500000.0, 2072000.0, -1428000.0),
1024, 1024)
x_size, y_size = 1024, 1024
arr = np.zeros((3, y_size, x_size))
attrs = dict([('platform_name', 'NOAA-18'),
('resolution', 1050),
('polarization', None),
('start_time', TIME - datetime.timedelta(minutes=55)),
('end_time', TIME - datetime.timedelta(minutes=50)),
('level', None),
('sensor', 'avhrr-3'),
('ancillary_variables', []),
('area', area),
('wavelength', None),
('optional_datasets', []),
('standard_name', 'overview'),
('name', 'overview'),
('prerequisites', [0.6, 0.8, 10.8]),
('optional_prerequisites', []),
('calibration', None),
('modifiers', None),
('mode', 'P')])
kwargs = {'compute': True, 'fill_value': None, 'sat_id': 6300014,
'chan_id': 1700015, 'data_cat': 'PPRN', 'data_source': 'SMHI', 'nbits': 8}
data1 = da.tile(da.repeat(da.arange(4, chunks=1024), 256), 256).reshape((1, 256, 1024))
datanan = da.ones((1, 256, 1024), chunks=1024) * 4
data2 = da.tile(da.repeat(da.arange(4, chunks=1024), 256), 512).reshape((1, 512, 1024))
data = da.concatenate((data1, datanan, data2), axis=1)
data = xr.DataArray(data, coords={'bands': ['P']}, dims=['bands', 'y', 'x'], attrs=attrs)
from trollimage.xrimage import XRImage
img = XRImage(data)
with tempfile.NamedTemporaryFile(delete=DELETE_FILES) as tmpfile:
filename = tmpfile.name
if not DELETE_FILES:
print(filename)
save(img, filename, data_is_scaled_01=True, **kwargs)
tif = TiffFile(filename)
res = tif[0].asarray()
for idx in range(3):
np.testing.assert_allclose(res[:, :, idx], np.round(
np.nan_to_num(arr[idx, :, :]) * 255).astype(np.uint8))
np.testing.assert_allclose(res[:, :, 3] == 0, np.isnan(arr[0, :, :]))
......@@ -711,8 +711,8 @@ class TiffWriter(object):
# reset and use compress sizes
strip_byte_counts = []
for plane in data[pageindex]:
for ty in xrange(0, tiles_y):
for tx in xrange(0, tiles_x):
for ty in range(0, tiles_y):
for tx in range(0, tiles_x):
# allocate fixed size tile filled with zeros
tile = numpy.zeros((tile_width * tile_length,
shape[-1]), data.dtype)
......@@ -724,7 +724,7 @@ class TiffWriter(object):
itw = min(tile_width,
shape[3] - tx*tile_width)
ioffs = tx*tile_width
for tl in xrange(0, itl):
for tl in range(0, itl):
# copy data to tile line
ir = ty*tile_length+tl
tile[tl*tile_width:tl*tile_width+itw] \
......@@ -4989,4 +4989,3 @@ if sys.version_info[0] > 2:
if __name__ == "__main__":
sys.exit(main())
......@@ -22,4 +22,4 @@
"""Version file."""
__version__ = "v0.1.0"
__version__ = "v0.2.0"