internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: python-pillow/Pillow

Issue:
ImageDraw.floodfill not listed in docs
Is this intentional? 

I ended up implementing my own version of it before I realized it was already in the library.


Discussion:
No, Definitely an oversight.

Resolving patch:
diff --git a/PIL/ImageDraw.py b/PIL/ImageDraw.py
--- a/PIL/ImageDraw.py
+++ b/PIL/ImageDraw.py
@@ -87,7 +87,10 @@ def __init__(self, im, mode=None):
         self.font = None
 
     def getfont(self):
-        """Get the current default font."""
+        """
+        Get the current default font.
+
+        :returns: An image font."""
         if not self.font:
             # FIXME: should add a font repository
             from . import ImageFont
@@ -330,8 +333,8 @@ def floodfill(image, xy, value, border=None, thresh=0):
         pixels with a color different from the border color.  If not given,
         the region consists of pixels having the same color as the seed
         pixel.
-    :param thresh: Optional threshold value which specifies a maximum 
-        tolerable difference of a pixel value from the 'background' in 
+    :param thresh: Optional threshold value which specifies a maximum
+        tolerable difference of a pixel value from the 'background' in
         order for it to be replaced. Useful for filling regions of non-
         homogeneous, but similar, colors.
     """
@@ -375,7 +378,7 @@ def floodfill(image, xy, value, border=None, thresh=0):
                             newedge.append((s, t))
             edge = newedge
 
-  
+
 def _color_diff(rgb1, rgb2):
     """
     Uses 1-norm distance to calculate difference between two rgb values.


Test patch:
Repository: python-pillow/Pillow

Issue:
A typo in document
Hi, I think one number in the document might be typo.

>lut – A lookup table, containing 256 (or 65336 if self.mode==”I” and mode == “L”) values per band in the image. 

The above is from the description of Image.point 

Link: http://pillow.readthedocs.io/en/3.1.x/reference/Image.html

65336 is a strange number, should it be 65536 instead?



Discussion:

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -1457,7 +1457,7 @@ def point(self, lut, mode=None):
         """
         Maps this image through a lookup table or function.
 
-        :param lut: A lookup table, containing 256 (or 65336 if
+        :param lut: A lookup table, containing 256 (or 65536 if
            self.mode=="I" and mode == "L") values per band in the
            image.  A function can be used instead, it should take a
            single argument. The function is called once for each
@@ -2102,7 +2102,7 @@ def transform(self, size, method, data=None, resample=NEAREST,
            in the output image.
         :returns: An :py:class:`~PIL.Image.Image` object.
         """
-        
+
         if self.mode == 'LA':
             return self.convert('La').transform(
                 size, method, data, resample, fill).convert('LA')


Test patch:
Repository: python-pillow/Pillow

Issue:
Gif duration setting is ignored
### What versions of Pillow and Python are you using?
Python 3.6.4
Pillow 5.0

Any animated gif I have tried the following lines of code on show no affect on the gif frame duration:

```python
> from PIL import Image
> f = Image.open('in.gif')
> f.save('out.gif', save_all=True, duration=400)
```


Discussion:
Hi. To help with your immediate problem, try this -

```python
from PIL import Image
f = Image.open('in.gif')
f.info['duration'] = 400
f.save('out.gif', save_all=True)
```

What I'm guessing is happening is that the images you are opening already have a `duration` key, and this key is overwriting the `duration` argument you are passing in on save.

Resolving patch:
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py
--- a/src/PIL/GifImagePlugin.py
+++ b/src/PIL/GifImagePlugin.py
@@ -457,7 +457,8 @@ def _save_all(im, fp, filename):
 
 
 def _save(im, fp, filename, save_all=False):
-    im.encoderinfo.update(im.info)
+    for k, v in im.info.items():
+        im.encoderinfo.setdefault(k, v)
     # header
     try:
         palette = im.encoderinfo["palette"]


Test patch:
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py
--- a/Tests/test_file_gif.py
+++ b/Tests/test_file_gif.py
@@ -305,9 +305,12 @@ def test_duration(self):
 
         out = self.tempfile('temp.gif')
         im = Image.new('L', (100, 100), '#000')
+
+        # Check that the argument has priority over the info settings
+        im.info['duration'] = 100
         im.save(out, duration=duration)
-        reread = Image.open(out)
 
+        reread = Image.open(out)
         self.assertEqual(reread.info['duration'], duration)
 
     def test_multiple_duration(self):
Repository: python-pillow/Pillow

Issue:
DeprecationWarning: Using or import the ABCs from 'collections' is deprecated

![default](https://user-images.githubusercontent.com/26893563/39669450-a4f8636e-511e-11e8-97e7-50aa6a3df01b.PNG)
![default](https://user-images.githubusercontent.com/26893563/39669456-b11ed056-511e-11e8-9fc9-4ec42ea37ac3.PNG)
Warning above,look screenshots above,how to solve this warning?


Discussion:
Thanks, some abstract base classes were moved from `collections` to `collections.abc` in Python 3.3, raise a `DeprecationWarning` in 3.7, and will be removed in 3.8.

https://docs.python.org/3.7/whatsnew/3.7.html#deprecated

See PR #3123 for a fix.

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -121,8 +121,14 @@ def __getattr__(self, id):
 import atexit
 
 # type stuff
-import collections
 import numbers
+try:
+    # Python 3
+    from collections.abc import Callable
+except ImportError:
+    # Python 2.7
+    from collections import Callable
+
 
 # works everywhere, win for pypy, not cpython
 USE_CFFI_ACCESS = hasattr(sys, 'pypy_version_info')
@@ -1142,7 +1148,7 @@ def filter(self, filter):
 
         self.load()
 
-        if isinstance(filter, collections.Callable):
+        if isinstance(filter, Callable):
             filter = filter()
         if not hasattr(filter, "filter"):
             raise TypeError("filter argument should be ImageFilter.Filter " +
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py
--- a/src/PIL/TiffImagePlugin.py
+++ b/src/PIL/TiffImagePlugin.py
@@ -58,6 +58,13 @@
 
 from .TiffTags import TYPES
 
+try:
+    # Python 3
+    from collections.abc import MutableMapping
+except ImportError:
+    # Python 2.7
+    from collections import MutableMapping
+
 
 __version__ = "1.3.5"
 DEBUG = False  # Needs to be merged with the new logging approach.
@@ -398,7 +405,7 @@ def delegate(self, *args):
     __round__ = _delegate('__round__')
 
 
-class ImageFileDirectory_v2(collections.MutableMapping):
+class ImageFileDirectory_v2(MutableMapping):
     """This class represents a TIFF tag directory.  To speed things up, we
     don't decode tags unless they're asked for.
 


Test patch:
Repository: python-pillow/Pillow

Issue:
PIL.ImageColor.getrgb("hsl(hue,sat%,lig%.)") allow values to be decimal/float numbers
The values in doing `PIL.ImageColor.getrgb("hsl(hue, sat%, lig%)")` must currently be integer, but this limits the resulting RGB color resolution, since a difference of 1 as minimum step for arguments does sometimes result in a difference for RGB value of up to about 5, thus not allowing the function to control the value fine grained.



Discussion:

Resolving patch:
diff --git a/src/PIL/ImageColor.py b/src/PIL/ImageColor.py
--- a/src/PIL/ImageColor.py
+++ b/src/PIL/ImageColor.py
@@ -87,7 +87,7 @@ def getrgb(color):
             int((int(m.group(3)) * 255) / 100.0 + 0.5)
             )
 
-    m = re.match(r"hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
+    m = re.match(r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color)
     if m:
         from colorsys import hls_to_rgb
         rgb = hls_to_rgb(


Test patch:
diff --git a/Tests/test_imagecolor.py b/Tests/test_imagecolor.py
--- a/Tests/test_imagecolor.py
+++ b/Tests/test_imagecolor.py
@@ -78,6 +78,10 @@ def test_functions(self):
         self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(360,100%,50%)"))
         self.assertEqual((0, 255, 255), ImageColor.getrgb("hsl(180,100%,50%)"))
 
+        # floats
+        self.assertEqual((254, 3, 3), ImageColor.getrgb("hsl(0.1,99.2%,50.3%)"))
+        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(360.,100.0%,50%)"))
+
         # case insensitivity
         self.assertEqual(ImageColor.getrgb("RGB(255,0,0)"),
                          ImageColor.getrgb("rgb(255,0,0)"))
Repository: python-pillow/Pillow

Issue:
Document Image.transform's fill parameter
### What did you do?

Visited http://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.transform

### What did you expect to happen?

Docs for fill and fillcolor. 

### What actually happened?

Docs for fillcolor but not fill. 




Discussion:
Iirc, Fill is currently unused for any of our transforms, but it is in the api and other code can use it.

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -2101,6 +2101,20 @@ def transform(self, size, method, data=None, resample=NEAREST,
           :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
           :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals
           in one operation).
+
+          It may also be an :py:class:`~PIL.Image.ImageTransformHandler`
+          object::
+            class Example(Image.ImageTransformHandler):
+                def transform(size, method, data, resample, fill=1):
+                    # Return result
+
+          It may also be an object with a :py:meth:`~method.getdata` method
+          that returns a tuple supplying new **method** and **data** values::
+            class Example(object):
+                def getdata(self):
+                    method = Image.EXTENT
+                    data = (0, 0, 100, 100)
+                    return method, data
         :param data: Extra data to the transformation method.
         :param resample: Optional resampling filter.  It can be one of
            :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
@@ -2108,6 +2122,9 @@ def transform(self, size, method, data=None, resample=NEAREST,
            environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline
            interpolation in a 4x4 environment). If omitted, or if the image
            has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.
+        :param fill: If **method** is an
+          :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
+          the arguments passed to it. Otherwise, it is unused.
         :param fillcolor: Optional fill color for the area outside the transform
            in the output image.
         :returns: An :py:class:`~PIL.Image.Image` object.


Test patch:
Repository: python-pillow/Pillow

Issue:
"ResourceWarning: unclosed file" with raw data (mmap)
Images containing raw data sometimes give `ResourceWarning: unclosed file` on my Linux machine, because the file opened for `mmap` is not closed.

https://github.com/python-pillow/Pillow/blob/968c2cf3c9c1e82f074a65c8c80d0da222d42eff/src/PIL/ImageFile.py#L177-L179



Discussion:
@danpla Open a PR?

Resolving patch:
diff --git a/src/PIL/ImageFile.py b/src/PIL/ImageFile.py
--- a/src/PIL/ImageFile.py
+++ b/src/PIL/ImageFile.py
@@ -174,9 +174,8 @@ def load(self):
                     else:
                         # use mmap, if possible
                         import mmap
-                        fp = open(self.filename, "r")
-                        size = os.path.getsize(self.filename)
-                        self.map = mmap.mmap(fp.fileno(), size, access=mmap.ACCESS_READ)
+                        with open(self.filename, "r") as fp:
+                            self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
                         self.im = Image.core.map_buffer(
                             self.map, self.size, decoder_name, extents, offset, args
                             )


Test patch:
Repository: python-pillow/Pillow

Issue:
Mention numpy in the docs?
I'm new to Pillow, and was trying to convert data from and to Numpy arrays.

Currently searching for `numpy` in the Pillow docs doesn't give a single result:
http://pillow.readthedocs.io/en/4.1.x/search.html?q=numpy&check_keywords=yes&area=default

With Google I found https://stackoverflow.com/a/384926/498873 which points to http://effbot.org/zone/pil-changes-116.htm which gives what I think is the way to do it now:
```
i = Image.open('lena.jpg')
a = numpy.asarray(i) # a is readonly
i = Image.fromarray(a)
```

Is it worth adding that info in a small section "converting to / from Numpy arrays" somewhere in the Pillow docs?


Discussion:

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -2440,9 +2440,20 @@ def fromarray(obj, mode=None):
     Creates an image memory from an object exporting the array interface
     (using the buffer protocol).
 
-    If obj is not contiguous, then the tobytes method is called
+    If **obj** is not contiguous, then the tobytes method is called
     and :py:func:`~PIL.Image.frombuffer` is used.
 
+    If you have an image in NumPy::
+
+      from PIL import Image
+      import numpy as np
+      im = Image.open('hopper.jpg')
+      a = numpy.asarray(im)
+
+    Then this can be used to convert it to a Pillow image::
+
+      im = Image.fromarray(a)
+
     :param obj: Object with array interface
     :param mode: Mode to use (will be determined from type if None)
       See: :ref:`concept-modes`.


Test patch:
Repository: python-pillow/Pillow

Issue:
Libtiff encoder, argument 3 must be str, not None
### What did you do?
```python
im = Image.fromarray(dataset[:])
format = 'tiff'
im.save(f, format=format, compression=None)
```

### What did you expect to happen?

File to be saved.

### What actually happened?

```
  File "../hdf5/base_hdf5.py", line 439, in upload_dataset
    im.save(f, format=format, compression=None)
  File "/usr/local/lib/python3.7/site-packages/PIL/Image.py", line 1950, in save
    save_handler(self, fp, filename)
  File "/usr/local/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 1533, in _save
    e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)
  File "/usr/local/lib/python3.7/site-packages/PIL/Image.py", line 469, in _getencoder
    return encoder(mode, *args + extra)
TypeError: argument 3 must be str, not None
```

### What versions of Pillow and Python are you using?

Python 3.7, just installed Pillow today.



Discussion:
It seems like setting the compression to a string of `'None'` fixes the issue.

This might be a documentation issue as the documentation does not have quotes around `None` making one believe it's the Python `None` type, not a string.

See: https://pillow.readthedocs.io/en/5.1.x/handbook/image-file-formats.html#tiff
Thanks for reporting. I think that `None` should be correct, so I've created a PR to fix this.

Resolving patch:
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py
--- a/src/PIL/TiffImagePlugin.py
+++ b/src/PIL/TiffImagePlugin.py
@@ -1396,8 +1396,9 @@ def _save(im, fp, filename):
 
     ifd = ImageFileDirectory_v2(prefix=prefix)
 
-    compression = im.encoderinfo.get('compression',
-                                     im.info.get('compression', 'raw'))
+    compression = im.encoderinfo.get('compression', im.info.get('compression'))
+    if compression is None:
+        compression = 'raw'
 
     libtiff = WRITE_LIBTIFF or compression != 'raw'
 


Test patch:
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py
--- a/Tests/test_file_libtiff.py
+++ b/Tests/test_file_libtiff.py
@@ -486,7 +486,7 @@ def save_bytesio(compression=None):
             pilim_load = Image.open(buffer_io)
             self.assert_image_similar(pilim, pilim_load, 0)
 
-        # save_bytesio()
+        save_bytesio()
         save_bytesio('raw')
         save_bytesio("packbits")
         save_bytesio("tiff_lzw")
Repository: python-pillow/Pillow

Issue:
Save compressed TIFF only accepts float values for dpi
There is a trap in setting the resolution for compressed TIFF images.  

```python
# pillow v3.1.1

import PIL.Image
im = PIL.Image.new('CMYK', (100, 100))

dpi = 100.0  # works
dpi = 100  # fails

im.save('test.tif', format='TIFF',
        dpi=(dpi, dpi),
        compression='tiff_lzw',
        #compression='tiff_deflate',
        #compression='tiff_adobe_deflate'
        )
```

Integers fail silently resulting in the resolution value missing from the saved file. Floats work as expected.



Discussion:

Resolving patch:
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py
--- a/src/PIL/TiffImagePlugin.py
+++ b/src/PIL/TiffImagePlugin.py
@@ -567,6 +567,9 @@ def _setitem(self, tag, value, legacy_api):
         if self.tagtype[tag] == 7 and py3:
             values = [value.encode("ascii", 'replace') if isinstance(
                       value, str) else value]
+        elif self.tagtype[tag] == 5:
+            values = [float(v) if isinstance(v, int) else v
+                      for v in values]
 
         values = tuple(info.cvt_enum(value) for value in values)
 


Test patch:
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py
--- a/Tests/test_file_libtiff.py
+++ b/Tests/test_file_libtiff.py
@@ -231,6 +231,16 @@ def test_additional_metadata(self):
 
         TiffImagePlugin.WRITE_LIBTIFF = False
 
+    def test_int_dpi(self):
+        # issue #1765
+        im = hopper('RGB')
+        out = self.tempfile('temp.tif')
+        TiffImagePlugin.WRITE_LIBTIFF = True
+        im.save(out, dpi=(72, 72))
+        TiffImagePlugin.WRITE_LIBTIFF = False
+        reloaded = Image.open(out)
+        self.assertEqual(reloaded.info['dpi'], (72.0, 72.0))
+
     def test_g3_compression(self):
         i = Image.open('Tests/images/hopper_g4_500.tif')
         out = self.tempfile("temp.tif")
Repository: python-pillow/Pillow

Issue:
WebPImagePlugin.py - ResourceWarning: unclosed file
### What did you do?

```console
> python -Wd
Python 3.7.0 (default, Jul 15 2018, 10:44:58)
[GCC 8.1.1 20180531] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
>>> with Image.open('tshirt.webp') as img:
...     img.save('tshirt.png', 'PNG')
...
/home/pajadam/.venv/hype/lib/python3.7/site-packages/PIL/WebPImagePlugin.py:156: ResourceWarning: unclosed file <_io.BufferedReader name='tshirt.webp'>
  self.fp = BytesIO(data)
>>>
```

### What did you expect to happen?

No warnings, especially while using context manager. 

### What actually happened?

Following warning occurs:

```
/home/pajadam/.venv/hype/lib/python3.7/site-packages/PIL/WebPImagePlugin.py:156: ResourceWarning: unclosed file <_io.BufferedReader name='tshirt.webp'>
  self.fp = BytesIO(data)
```

### What versions of Pillow and Python are you using?

- `Pillow==5.2`
- `Python 3.7`

Minimal example:
```python
from PIL import Image

with Image.open('tshirt.webp') as img:
     img.save('tshirt.png', 'PNG')
```



Discussion:
Thanks for reporting this. This can be replicated using transparent.webp from the Pillow test images.

I have created PR #3341

Resolving patch:
diff --git a/src/PIL/WebPImagePlugin.py b/src/PIL/WebPImagePlugin.py
--- a/src/PIL/WebPImagePlugin.py
+++ b/src/PIL/WebPImagePlugin.py
@@ -153,6 +153,8 @@ def load(self):
                 self.__loaded = self.__logical_frame
 
                 # Set tile
+                if self.fp:
+                    self.fp.close()
                 self.fp = BytesIO(data)
                 self.tile = [("raw", (0, 0) + self.size, 0, self.mode)]
 


Test patch:
diff --git a/Tests/test_file_webp.py b/Tests/test_file_webp.py
--- a/Tests/test_file_webp.py
+++ b/Tests/test_file_webp.py
@@ -135,6 +135,13 @@ def test_WebPDecode_with_invalid_args(self):
             self.assertRaises(TypeError, _webp.WebPAnimDecoder)
         self.assertRaises(TypeError, _webp.WebPDecode)
 
+    def test_no_resource_warning(self):
+        file_path = "Tests/images/hopper.webp"
+        image = Image.open(file_path)
+
+        temp_file = self.tempfile("temp.webp")
+        self.assert_warning(None, image.save, temp_file)
+
 
 if __name__ == '__main__':
     unittest.main()
Repository: python-pillow/Pillow

Issue:
Improve Image.convert() documentation
Trying to find a bug I noticed in the case of RGBA->P convert() it uses quantize() and ignores almost all parameters.
![s_7_rgb_p_quantize](https://cloud.githubusercontent.com/assets/3226483/7106501/25a7c486-e143-11e4-8d6d-7fbbf2eaf2ce.png) rgb.quantize(256)
![s_7_rgb_p_defaultweb_floyd](https://cloud.githubusercontent.com/assets/3226483/7106500/25a73b2e-e143-11e4-959e-da335332daf0.png) rgb.convert("P")
![s_7_rgb_p_adapt_nodither](https://cloud.githubusercontent.com/assets/3226483/7106502/25a9504e-e143-11e4-86a3-f11089c1964a.png)  rgb.convert("P", dither = Image.NONE, palette = Image.ADAPTIVE)
![s_7_rgb_p_adapt_floyd](https://cloud.githubusercontent.com/assets/3226483/7106503/25ac62c0-e143-11e4-8a3c-072c4f8cd500.png) rgb.convert("P", palette = Image.ADAPTIVE)
![s_7_rgba_p](https://cloud.githubusercontent.com/assets/3226483/7106498/2599fd56-e143-11e4-8b02-fb8f219da742.png) rgb.convert("RGBA").convert("P")
![s_7_rgb](https://cloud.githubusercontent.com/assets/3226483/7106499/259a2448-e143-11e4-8e04-6a4f19347a46.png) rgb



Discussion:

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -873,12 +873,17 @@ def convert(self, mode=None, matrix=None, dither=None,
         use other thresholds, use the :py:meth:`~PIL.Image.Image.point`
         method.
 
+        When converting from "RGBA" to "P" without a **matrix** argument,
+        this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,
+        and **dither** and **palette** are ignored.
+
         :param mode: The requested mode. See: :ref:`concept-modes`.
         :param matrix: An optional conversion matrix.  If given, this
            should be 4- or 12-tuple containing floating point values.
         :param dither: Dithering method, used when converting from
            mode "RGB" to "P" or from "RGB" or "L" to "1".
            Available methods are NONE or FLOYDSTEINBERG (default).
+           Note that this is not used when **matrix** is supplied.
         :param palette: Palette to use when converting from mode "RGB"
            to "P".  Available palettes are WEB or ADAPTIVE.
         :param colors: Number of colors to use for the ADAPTIVE palette.


Test patch: