8000 MNT move an orphaned vendored file around by DimitriPapadopoulos · Pull Request #21166 · scikit-learn/scikit-learn · GitHub
[go: up one dir, main page]

Skip to content

MNT move an orphaned vendored file around #21166

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

Closed
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion sklearn/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from sklearn.utils import _IS_32BIT
from sklearn.utils._openmp_helpers import _openmp_effective_n_threads
from sklearn.externals import _pilutil
from sklearn.utils import _pilutil
from sklearn._min_dependencies import PYTEST_MIN_VERSION
from sklearn.utils.fixes import np_version, parse_version
from sklearn.datasets import fetch_20newsgroups
Expand Down
2 changes: 1 addition & 1 deletion sklearn/datasets/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1365,7 +1365,7 @@ def load_sample_images():
dtype('uint8')
"""
# import PIL only when needed
from ..externals._pilutil import imread
from ..utils._pilutil import imread

descr = load_descr("README.txt", descr_module=IMAGES_MODULE)

Expand Down
2 changes: 1 addition & 1 deletion sklearn/datasets/_lfw.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def _check_fetch_lfw(data_home=None, funneled=True, download_if_missing=True):
def _load_imgs(file_paths, slice_, color, resize):
"""Internally used to load images"""
# import PIL only when needed
from ..externals._pilutil import imread, imresize
from ..utils._pilutil import imread, imresize

# compute the portion of the images to load to respect the slice_ parameter
# given by the caller
Expand Down
2 changes: 1 addition & 1 deletion sklearn/datasets/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from sklearn.utils._testing import SkipTest
from sklearn.datasets.tests.test_common import check_as_frame

from sklearn.externals._pilutil import pillow_installed
from sklearn.utils._pilutil import pillow_installed

from sklearn.utils import IS_PYPY

Expand Down
2 changes: 1 addition & 1 deletion sklearn/datasets/tests/test_lfw.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import numpy as np
import pytest
from functools import partial
from sklearn.externals._pilutil import pillow_installed, imsave
from sklearn.utils._pilutil import pillow_installed, imsave
from sklearn.datasets import fetch_lfw_pairs
from sklearn.datasets import fetch_lfw_people

Expand Down
97 changes: 55 additions & 42 deletions sklearn/externals/_pilutil.py → sklearn/utils/_pilutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,20 @@

import numpy

from numpy import (amin, amax, ravel, asarray, arange, ones, newaxis,
transpose, iscomplexobj, uint8, issubdtype, array)
from numpy import (
amin,
amax,
ravel,
asarray,
arange,
ones,
newaxis,
transpose,
iscomplexobj,
uint8,
issubdtype,
array,
)

# Modification of original scipy pilutil.py to make this module importable if
# pillow is not installed. If pillow is not installed, functions will raise
Expand All @@ -55,12 +67,12 @@
except ImportError:
import Image
pillow_installed = True
if not hasattr(Image, 'frombytes'):
if not hasattr(Image, "frombytes"):
Image.frombytes = Image.fromstring
except ImportError:
pillow_installed = False

__all__ = ['bytescale', 'imread', 'imsave', 'fromimage', 'toimage', 'imresize']
__all__ = ["bytescale", "imread", "imsave", "fromimage", "toimage", "imresize"]


PILLOW_ERROR_MESSAGE = (
Expand Down Expand Up @@ -102,7 +114,7 @@ def bytescale(data, cmin=None, cmax=None, high=255, low=0):
Examples
--------
>>> import numpy as np
>>> from scipy.misc import bytescale
>>> from sklearn.utils._pilutil import bytescale
>>> img = np.array([[ 91.06794177, 3.39058326, 84.4221549 ],
... [ 73.88003259, 80.91433048, 4.88878881],
... [ 51.53875334, 34.45808177, 27.5873488 ]])
Expand Down Expand Up @@ -237,7 +249,7 @@ def imsave(name, arr, format=None):
Construct an array of gradient intensity values and save to file:

>>> import numpy as np
>>> from scipy.misc import imsave
>>> from sklearn.utils._pilutil import imsave
>>> x = np.zeros((255, 255))
>>> x = np.zeros((255, 255), dtype=np.uint8)
>>> x[:] = np.arange(255)
Expand Down Expand Up @@ -293,35 +305,37 @@ def fromimage(im, flatten=False, mode=None):
if mode is not None:
if mode != im.mode:
im = im.convert(mode)
elif im.mode == 'P':
elif im.mode == "P":
# Mode 'P' means there is an indexed "palette". If we leave the mode
# as 'P', then when we do `a = array(im)` below, `a` will be a 2-D
# containing the indices into the palette, and not a 3-D array
# containing the RGB or RGBA values.
if 'transparency' in im.info:
im = im.convert('RGBA')
if "transparency" in im.info:
im = im.convert("RGBA")
else:
im = im.convert('RGB')
im = im.convert("RGB")

if flatten:
im = im.convert('F')
elif im.mode == '1':
im = im.convert("F")
elif im.mode == "1":
# Workaround for crash in PIL. When im is 1-bit, the call array(im)
# can cause a seg. fault, or generate garbage. See
# https://github.com/scipy/scipy/issues/2138 and
# https://github.com/python-pillow/Pillow/issues/350.
#
# This converts im from a 1-bit image to an 8-bit image.
im = im.convert('L')
im = im.convert("L")

a = array(im)
return a


_errstr = "Mode is unknown or incompatible with input array shape."


def toimage(arr, high=255, low=0, cmin=None, cmax=None, pal=None,
mode=None, channel_axis=None):
def toimage(
arr, high=255, low=0, cmin=None, cmax=None, pal=None, mode=None, channel_axis=None
):
"""Takes a numpy array and returns a PIL image.

This function is only available if Python Imaging Library (PIL) is installed.
Expand Down Expand Up @@ -358,39 +372,38 @@ def toimage(arr, high=255, low=0, cmin=None, cmax=None, pal=None,
if iscomplexobj(data):
raise ValueError("Cannot convert a complex-valued array.")
shape = list(data.shape)
valid = len(shape) == 2 or ((len(shape) == 3) and
((3 in shape) or (4 in shape)))
valid = len(shape) == 2 or ((len(shape) == 3) and ((3 in shape) or (4 in shape)))
if not valid:
raise ValueError("'arr' does not have a suitable array shape for "
"any mode.")
raise ValueError("'arr' does not have a suitable array shape for any mode.")
if len(shape) == 2:
shape = (shape[1], shape[0]) # columns show up first
if mode == 'F':
if mode == "F":
data32 = data.astype(numpy.float32)
image = Image.frombytes(mode, shape, data32.tobytes())
return image
if mode in [None, 'L', 'P']:
bytedata = bytescale(data, high=high, low=low,
cmin=cmin, cmax=cmax)
image = Image.frombytes('L', shape, bytedata.tobytes())
if mode in [None, "L", "P"]:
bytedata = bytescale(data, high=high, low=low, cmin=cmin, cmax=cmax)
image = Image.frombytes("L", shape, bytedata.tobytes())
if pal is not None:
image.putpalette(asarray(pal, dtype=uint8).tobytes())
# Becomes a mode='P' automagically.
elif mode == 'P': # default gray-scale
pal = (arange(0, 256, 1, dtype=uint8)[:, newaxis] *
ones((3,), dtype=uint8)[newaxis, :])
elif mode == "P": # default gray-scale
pal = (
arange(0, 256, 1, dtype=uint8)[:, newaxis]
* ones((3,), dtype=uint8)[newaxis, :]
)
image.putpalette(asarray(pal, dtype=uint8).tobytes())
return image
if mode == '1': # high input gives threshold for 1
bytedata = (data > high)
image = Image.frombytes('1', shape, bytedata.tobytes())
if mode == "1": # high input gives threshold for 1
bytedata = data > high
image = Image.frombytes("1", shape, bytedata.tobytes())
return image
if cmin is None:
cmin = amin(ravel(data))
if cmax is None:
cmax = amax(ravel(data))
data = (data*1.0 - cmin)*(high - low)/(cmax - cmin) + low
if mode == 'I':
data = (data * 1.0 - cmin) * (high - low) / (cmax - cmin) + low
if mode == "I":
data32 = data.astype(numpy.uint32)
image = Image.frombytes(mode, shape, data32.tobytes())
else:
Expand All @@ -400,7 +413,7 @@ def toimage(arr, high=255, low=0, cmin=None, cmax=None, pal=None,
# if here then 3-d array with a 3 or a 4 in the shape length.
# Check for 3 in datacube shape --- 'RGB' or 'YCbCr'
if channel_axis is None:
if (3 in shape):
if 3 in shape:
ca = numpy.flatnonzero(asarray(shape) == 3)[0]
else:
ca = numpy.flatnonzero(asarray(shape) == 4)
Expand All @@ -427,17 +440,17 @@ def toimage(arr, high=255, low=0, cmin=None, cmax=None, pal=None,
shape = (shape[2], shape[1])
if mode is None:
if numch == 3:
mode = 'RGB'
mode = "RGB"
else:
mode = 'RGBA'
mode = "RGBA"

if mode not in ['RGB', 'RGBA', 'YCbCr', 'CMYK']:
if mode not in ["RGB", "RGBA", "YCbCr", "CMYK"]:
raise ValueError(_errstr)

if mode in ['RGB', 'YCbCr']:
if mode in ["RGB", "YCbCr"]:
if numch != 3:
raise ValueError("Invalid array shape for mode.")
if mode in ['RGBA', 'CMYK']:
if mode in ["RGBA", "CMYK"]:
if numch != 4:
raise ValueError("Invalid array shape for mode.")

Expand All @@ -446,7 +459,7 @@ def toimage(arr, high=255, low=0, cmin=None, cmax=None, pal=None,
return image


def imresize(arr, size, interp='bilinear', mode=None):
def imresize(arr, size, interp="bilinear", mode=None):
"""
Resize an image.

Expand Down Expand Up @@ -492,11 +505,11 @@ def imresize(arr, size, interp='bilinear', mode=None):
ts = type(size)
if issubdtype(ts, numpy.signedinteger):
percent = size / 100.0
size = tuple((array(im.size)*percent).astype(int))
size = tuple((array(im.size) * percent).astype(int))
elif issubdtype(type(size), numpy.floating):
size = tuple((array(im.size)*size).astype(int))
size = tuple((array(im.size) * size).astype(int))
else:
size = (size[1], size[0])
func = {'nearest': 0, 'lanczos': 1, 'bilinear': 2, 'bicubic': 3, 'cubic': 3}
func = {"nearest": 0, "lanczos": 1, "bilinear": 2, "bicubic": 3, "cubic": 3}
imnew = im.resize(size, resample=func[interp])
return fromimage(imnew)
0