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

Issue:
Documentation error: Wrong threshold in conversion from L to 1
<!--
Thank you for reporting an issue.

Follow these guidelines to ensure your issue is handled properly.

If you have a ...

2.  Bug report: include a self-contained, copy-pastable example that
    generates the issue if possible. Be concise with code posted.
    Guidelines on how to provide a good bug report:

    * https://stackoverflow.com/help/mcve

    Bug reports which follow these guidelines are easier to diagnose,
    and are often handled much more quickly.


We know asking good questions takes effort, and we appreciate your time.
Thank you.
-->

### What did you do?
Convert an image from grayscale (L) to bilevel (1) using dither=NONE

### What did you expect to happen?
Following [this section of the manual](https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=128#PIL.Image.Image.convert), I expected all values larger than 128 to be set to 255, all others to 0

> The default method of converting a greyscale (“L”) or “RGB” image into a bilevel (mode “1”) image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is NONE, all values larger than 128 are set to 255 (white), all other values to 0 (black).

### What actually happened?
All values larger than 127 were set to 255, all others to 0

### What are your OS, Python and Pillow versions?

* OS: Windows 10 Oct 2020
* Python: 3.8.3
* Pillow: 8.1.0

<!--
Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive.

The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow.
-->

```python
import numpy as np
from PIL import Image

array = np.arange(120, 130)
# array([120, 121, 122, 123, 124, 125, 126, 127, 128, 129])
image = Image.fromarray(array).convert('1', dither=Image.NONE)
np.array(image)
# array([[False], [False], [False], [False], [False], [False], [False], [False], [True], [True]])
```

Considering this a mistake in the  documentation since 'larger than 127' (`0b01111111`) makes a lot more sense


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
@@ -878,7 +878,7 @@ def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256):
         The default method of converting a greyscale ("L") or "RGB"
         image into a bilevel (mode "1") image uses Floyd-Steinberg
         dither to approximate the original image luminosity levels. If
-        dither is :data:`NONE`, all values larger than 128 are set to 255 (white),
+        dither is :data:`NONE`, all values larger than 127 are set to 255 (white),
         all other values to 0 (black). To use other thresholds, use the
         :py:meth:`~PIL.Image.Image.point` method.
 


Test patch:
Repository: python-pillow/Pillow

Issue:
Kodi v19 crashes when PIL imports numpy
This happens on Arch Linux with all addons and skins that use PIL image libraries.
Information on TheMovieDb Helper Kodi addon where its dev did a workaround here:
https://github.com/jurialmunkey/plugin.video.themoviedb.helper/issues/445

A Kodi dev mentioned that this is a PIL / Numpy issue not a Kodi issue so I should ask here:
https://github.com/xbmc/xbmc/issues/19324

Thank you for any possible solutions.


Discussion:
I played with an issue a bit and found out that the underlying issue is the lack of sub-interpreter support in C++ numpy modules
(namely multiarray).

I am opening a NumPy bug now.
Thanks for investigating further.
@radarhere isn't it better to provide an option for Pillow users to disable internal numpy invocation somehow?

For example, by a method or constructor option that is on by default.

See attached issue: NumPy developers claim sub-interpreter support is still in near-beginning state.
If I'm understanding correctly, Pillow's only contribution to this bug is the fact that it uses numpy?

How do you feel about this idea - https://github.com/radarhere/Pillow/commit/420f4e992dc52d6e65e8a0425db902a508ff1c13 - moving the numpy import from the start of ImageFilter into the Color3DLUT class, so that it is only imported when necessary?
I like the idea. Basically @jurialmunkey did very similar fix lazy-loading Pillow.
I've created #5323.

Resolving patch:
diff --git a/src/PIL/ImageFilter.py b/src/PIL/ImageFilter.py
--- a/src/PIL/ImageFilter.py
+++ b/src/PIL/ImageFilter.py
@@ -16,11 +16,6 @@
 #
 import functools
 
-try:
-    import numpy
-except ImportError:  # pragma: no cover
-    numpy = None
-
 
 class Filter:
     pass
@@ -369,6 +364,13 @@ def __init__(self, size, table, channels=3, target_mode=None, **kwargs):
         items = size[0] * size[1] * size[2]
         wrong_size = False
 
+        numpy = None
+        if hasattr(table, "shape"):
+            try:
+                import numpy
+            except ImportError:  # pragma: no cover
+                pass
+
         if numpy and isinstance(table, numpy.ndarray):
             if copy_table:
                 table = table.copy()


Test patch:
Repository: python-pillow/Pillow

Issue:
Wrong frame snapshot in GIF animated file
### What did you do?

```python
im.open(gif.stream)
im.convert("RGB/RGBA/P", dither=None)
im.seek(frame_number)
im.save(outfile, fmt)
```

### What did you expect to happen?
orgi_GIF: http://gif.imgix.net/imgix-logo-ani.gif
Right_Frame_44_in_Imgix.com: http://gif.imgix.net/imgix-logo-ani.gif?frame=44
### What actually happened?
Wrong_Frame_44_in_my_system: https://files.soft.org/?url=/imgix.gif&frame=44
### What are your OS, Python and Pillow versions?

* OS: Centos 7 & 8
* Python: 3.6.8
* Pillow: 7.0.0


Discussion:

Resolving patch:
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py
--- a/src/PIL/GifImagePlugin.py
+++ b/src/PIL/GifImagePlugin.py
@@ -148,7 +148,7 @@ def _seek(self, frame):
             self.disposal_method = 0
         else:
             # ensure that the previous frame was loaded
-            if not self.im:
+            if self.tile:
                 self.load()
 
         if frame != self.__frame + 1:


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
@@ -341,6 +341,17 @@ def test_dispose_previous():
             pass
 
 
+def test_previous_frame_loaded():
+    with Image.open("Tests/images/dispose_none.gif") as img:
+        img.load()
+        img.seek(1)
+        img.load()
+        img.seek(2)
+        with Image.open("Tests/images/dispose_none.gif") as img_skipped:
+            img_skipped.seek(2)
+            assert_image_equal(img_skipped, img)
+
+
 def test_save_dispose(tmp_path):
     out = str(tmp_path / "temp.gif")
     im_list = [
Repository: python-pillow/Pillow

Issue:
Not able to parse particular greyscale .ico file
I have dumped this .ico file from ResHacker from some particular PE file. I use `IcoImagePlugin.IcoImageFile` but getting:
```
python37\lib\site-packages\PIL\Image.py:800: in frombytes
    raise ValueError("not enough image data")
```
when debugging it seems that it derives bpp as 8 instead of 1.
[Icon4.zip](https://github.com/python-pillow/Pillow/files/5192877/Icon4.zip)




Discussion:
It looks like `bpp` is coming from https://github.com/python-pillow/Pillow/blob/9e6dabf0e51b96146e4fa53642d3f8bf4a1ca460/src/PIL/IcoImagePlugin.py#L189-L195 using the table https://github.com/python-pillow/Pillow/blob/9e6dabf0e51b96146e4fa53642d3f8bf4a1ca460/src/PIL/BmpImagePlugin.py#L39-L47 but for 1bpp images, the mode is first set to `P` based on this table, but then converted to `1` here https://github.com/python-pillow/Pillow/blob/9e6dabf0e51b96146e4fa53642d3f8bf4a1ca460/src/PIL/BmpImagePlugin.py#L242-L244

Changing the first block to
```python
            bpp = header["color_depth"]
```
defined at https://github.com/python-pillow/Pillow/blob/9e6dabf0e51b96146e4fa53642d3f8bf4a1ca460/src/PIL/IcoImagePlugin.py#L125-L134 lets the image load with just a warning
![Icon4](https://user-images.githubusercontent.com/3819630/92562200-d82acb00-f275-11ea-9b46-4fefd2649d5b.png)
```
c:\git\pillow\src\PIL\IcoImagePlugin.py:299: UserWarning: Image was not the expected size
  warnings.warn("Image was not the expected size")
```
but I suspect this could introduce a security vulnerability (I did not check thoroughly). The proper fix would probably be to add a special case to `IcoImageFile` for 1bpp images.

Resolving patch:
diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py
--- a/src/PIL/IcoImagePlugin.py
+++ b/src/PIL/IcoImagePlugin.py
@@ -190,13 +190,7 @@ def frame(self, idx):
             im.tile[0] = d, (0, 0) + im.size, o, a
 
             # figure out where AND mask image starts
-            mode = a[0]
-            bpp = 8
-            for k, v in BmpImagePlugin.BIT2MODE.items():
-                if mode == v[1]:
-                    bpp = k
-                    break
-
+            bpp = header["bpp"]
             if 32 == bpp:
                 # 32-bit color depth icon image allows semitransparent areas
                 # PIL's DIB format ignores transparency bits, recover them.


Test patch:
diff --git a/Tests/images/black_and_white.ico b/Tests/images/black_and_white.ico
new file mode 100644
Binary files /dev/null and b/Tests/images/black_and_white.ico differ
diff --git a/Tests/test_file_ico.py b/Tests/test_file_ico.py
--- a/Tests/test_file_ico.py
+++ b/Tests/test_file_ico.py
@@ -18,6 +18,12 @@ def test_sanity():
     assert im.get_format_mimetype() == "image/x-icon"
 
 
+def test_black_and_white():
+    with Image.open("Tests/images/black_and_white.ico") as im:
+        assert im.mode == "RGBA"
+        assert im.size == (16, 16)
+
+
 def test_invalid_file():
     with open("Tests/images/flower.jpg", "rb") as fp:
         with pytest.raises(SyntaxError):
Repository: python-pillow/Pillow

Issue:
TypeError when checking FreeType version
After PR https://github.com/python-pillow/Pillow/pull/5098:

```
$ python
Python 3.9.4 (default, Apr 20 2021, 15:51:38) 
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL.ImageFont
>>> PIL.ImageFont.FreeTypeFont()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.9/site-packages/PIL/ImageFont.py", line 173, in __init__
    freetype_version = parse_version(features.version_module("freetype2"))
  File "/usr/lib/python3.9/site-packages/packaging/version.py", line 57, in parse
    return Version(version)
  File "/usr/lib/python3.9/site-packages/packaging/version.py", line 296, in __init__
    match = self._regex.search(version)
TypeError: expected string or bytes-like object
```

The ImageFont module tries to be accepting of missing (optional) system dependencies for the _imagingft module. But then features.version_module() returns None, which cannot be parsed as a version, so this dumps a completely incomprehensible traceback rather than what most of the rest of this module does, which is:

https://github.com/python-pillow/Pillow/blob/56730906f2e0262cb2528287635c03c3fab128cf/src/PIL/ImageFont.py#L41-L50

_Originally posted by @eli-schwartz in https://github.com/python-pillow/Pillow/issues/5098#issuecomment-827071705_


Discussion:

Resolving patch:
diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py
--- a/src/PIL/ImageFont.py
+++ b/src/PIL/ImageFont.py
@@ -170,8 +170,10 @@ def __init__(self, font=None, size=10, index=0, encoding="", layout_engine=None)
         except ImportError:
             pass
         else:
-            freetype_version = parse_version(features.version_module("freetype2"))
-            if freetype_version < parse_version("2.8"):
+            freetype_version = features.version_module("freetype2")
+            if freetype_version is not None and parse_version(
+                freetype_version
+            ) < parse_version("2.8"):
                 warnings.warn(
                     "Support for FreeType 2.7 is deprecated and will be removed"
                     " in Pillow 9 (2022-01-02). Please upgrade to FreeType 2.8 "


Test patch:
Repository: python-pillow/Pillow

Issue:
WebP file size increased by 20-60%, compared to Pillow 7.1.2
### What did you do?
Load the image linked below, convert it to WebP.
### What did you expect to happen?
Same file size as with `Pillow 7.1.2` (± 5%)
### What actually happened?
File size increased by almost 50%, compared to `Pillow 7.1.2`.

|     File                       |    Size    |
|----------------------------|-------------|
| Source (jpg)             | 214 779 |
| Pillow 7.1.2 (webp)  | 108 450 |
| Pillow 7.2.0 (webp)  | 159 964 |

### What are your OS, Python and Pillow versions?

* OS: Ubuntu 20.04
* Python: 3.8.2
* Pillow: 7.2.0

```python
from PIL import Image
source = Image.open('source.jpg')
source.save('dest.webp', quality=80)
```

![source](https://user-images.githubusercontent.com/6928240/87582822-05cb1c00-c6ec-11ea-934d-14890d84f66e.jpg)


Discussion:
Testing, I find this is the result of #4547

Resolving patch:
diff --git a/src/PIL/WebPImagePlugin.py b/src/PIL/WebPImagePlugin.py
--- a/src/PIL/WebPImagePlugin.py
+++ b/src/PIL/WebPImagePlugin.py
@@ -314,7 +314,7 @@ def _save(im, fp, filename):
     if isinstance(exif, Image.Exif):
         exif = exif.tobytes()
     xmp = im.encoderinfo.get("xmp", "")
-    method = im.encoderinfo.get("method", 0)
+    method = im.encoderinfo.get("method", 4)
 
     if im.mode not in _VALID_WEBP_LEGACY_MODES:
         alpha = (


Test patch:
Repository: python-pillow/Pillow

Issue:
`exif_transpose` overwrites the original image exif
### What did you do?

Use `ImageOps.exif_tranpose` on an image with an EXIF orientation code (not in [None, 0, 1]).

### What did you expect to happen?

`exif_transpose()` should be immutable and returns a new image with the correct orientation.

### What actually happened?

`exif_transpose()` returns a new image but also modifies the original image exif info in-place (deletes the orientation, key 0x112).
It's a pretty big problem if your work with rotated images because it breaks the original images, if you e.g. call again `exif_transpose()` on it the EXIF orientation value is not there but the image content is not correctly rotated.

### What are your OS, Python and Pillow versions?

* OS: ubuntu 18.04
* Python: 3.8.8
* Pillow: 8.2.0

### Code

```python
import PIL, PIL.ImageOps
# if you have an image with exif
pil = PIL.Image.open(file)
# otherwise
import requests
resp = requests.get('https://raw.githubusercontent.com/recurser/exif-orientation-examples/master/Portrait_3.jpg', stream=True)
resp.raw.decode_content = True
pil = PIL.Image.open(resp.raw)

print(pil.getexif().get(0x0112))  # 3
correct_image = PIL.ImageOps.exif_transpose(pil)
print(pil.getexif().get(0x0112))  # None, but should be 3
```

### Proposed fix

Replace the first line of exif_tranpose in https://pillow.readthedocs.io/en/stable/_modules/PIL/ImageOps.html#exif_transpose with
```diff
from copy import deepcopy  # copy may be enough, I didn't try it

-    exif = image.getexif()
+    exif = deepcopy(image.getexif())
```


Discussion:

Resolving patch:
diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py
--- a/src/PIL/ImageOps.py
+++ b/src/PIL/ImageOps.py
@@ -578,7 +578,8 @@ def exif_transpose(image):
     }.get(orientation)
     if method is not None:
         transposed_image = image.transpose(method)
-        del exif[0x0112]
-        transposed_image.info["exif"] = exif.tobytes()
+        transposed_exif = transposed_image.getexif()
+        del transposed_exif[0x0112]
+        transposed_image.info["exif"] = transposed_exif.tobytes()
         return transposed_image
     return image.copy()


Test patch:
diff --git a/Tests/test_imageops.py b/Tests/test_imageops.py
--- a/Tests/test_imageops.py
+++ b/Tests/test_imageops.py
@@ -302,6 +302,7 @@ def check(orientation_im):
                     else:
                         assert transposed_im.info["exif"] != original_exif
 
+                        assert 0x0112 in im.getexif()
                         assert 0x0112 not in transposed_im.getexif()
 
                     # Repeat the operation to test that it does not keep transposing
Repository: python-pillow/Pillow

Issue:
"UnboundLocalError: local variable 'values' referenced before assignment" when `image.getexif().tobytes()` on specific JPEGs
I can't post the picture itself because it's from a customer, but the offending exif data trying to be serialized is:

```
ifd: <PIL.TiffImagePlugin.ImageFileDirectory_v2 object at ...>
ifd.self._tags_v2.items : {34665: {}, 40962: 1920, 40963: 1440, 40961: 1}
```

That empty dictionary for 34665 seems to be the culprit.

The failing statement is the use of `str(values)` when `is_ifd` is true (and thus `values` never gets defined):
https://github.com/python-pillow/Pillow/blob/70ef50cf72992ab6c9330412d6f1340c593e2d8f/src/PIL/TiffImagePlugin.py#L840

This will silently do the wrong thing instead of exploding if this is the second+ tag being serialized (as it will inherit `values` from the previous iteration of the loop.
It probably won't take that path for non-empty dictionaries, as those would have non-trivial `data` length.

A simple fix would be `if len(data) >= 16 or is_ifd` but I'm not super familiar with the codebase so it may not be the best choice.



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
@@ -826,7 +826,8 @@ def tobytes(self, offset=0):
                 else:
                     ifh = b"MM\x00\x2A\x00\x00\x00\x08"
                 ifd = ImageFileDirectory_v2(ifh)
-                for ifd_tag, ifd_value in self._tags_v2[tag].items():
+                values = self._tags_v2[tag]
+                for ifd_tag, ifd_value in values.items():
                     ifd[ifd_tag] = ifd_value
                 data = ifd.tobytes(offset)
             else:


Test patch:
diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py
--- a/Tests/test_file_tiff_metadata.py
+++ b/Tests/test_file_tiff_metadata.py
@@ -376,3 +376,16 @@ def test_too_many_entries():
 
     # Should not raise ValueError.
     pytest.warns(UserWarning, lambda: ifd[277])
+
+
+def test_empty_subifd(tmp_path):
+    out = str(tmp_path / "temp.jpg")
+
+    im = hopper()
+    exif = im.getexif()
+    exif[TiffImagePlugin.EXIFIFD] = {}
+    im.save(out, exif=exif)
+
+    with Image.open(out) as reloaded:
+        exif = reloaded.getexif()
+        assert exif.get_ifd(TiffImagePlugin.EXIFIFD) == {}
Repository: python-pillow/Pillow

Issue:
Pillow 8.3 and NumPy
Throws exception with Pillow 8.3: `TypeError: __array__() takes 1 positional argument but 2 were given`

````python
with PIL.Image.open(filepath) as img:
    numpy.array( img, dtype=numpy.float32 )
````


Discussion:
What version of Python are you using? What version of numpy?
Same problem here.
Python 3.7.4
numpy 1.21.0

workaround:
```python
with PIL.Image.open(filepath) as img:
    numpy.array(img).astype(np.float32)
```
Works with just about anything. The problem is that pillow newly implemented `__array__`, but only without arguments. Numpy requires `__array__` to take an optional dtype argument. This is used e.g. by numpy.array when the user passes a dtype argument. This should be with just about any numpy/python version.
fails with python 3.8 + 3.9, numpy 1.20 + 1.21
I'll send a patch.
We are seeing errors in `3.{6,7,8,9}`
Same issue in https://github.com/hyperspy/hyperspy/runs/2961516889 for all python version >=3.6 using the `imageio` library:

```python
                # Apply palette
>               frame_paletted = np.array(im, np.uint8)
E               TypeError: __array__() takes 1 positional argument but 2 were given

/opt/hostedtoolcache/Python/3.9.5/x64/lib/python3.9/site-packages/imageio/plugins/pillow.py:745: TypeError
```

The python 3.6 build is with numpy 1.17.1

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -681,7 +681,7 @@ def _repr_png_(self):
             raise ValueError("Could not save to PNG for display") from e
         return b.getvalue()
 
-    def __array__(self):
+    def __array__(self, dtype=None):
         # numpy array interface support
         import numpy as np
 
@@ -700,7 +700,7 @@ def __array__(self):
         class ArrayData:
             __array_interface__ = new
 
-        return np.array(ArrayData())
+        return np.array(ArrayData(), dtype)
 
     def __getstate__(self):
         return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()]


Test patch:
diff --git a/Tests/test_image_array.py b/Tests/test_image_array.py
--- a/Tests/test_image_array.py
+++ b/Tests/test_image_array.py
@@ -14,6 +14,10 @@ def test(mode):
         ai = numpy.array(im.convert(mode))
         return ai.shape, ai.dtype.str, ai.nbytes
 
+    def test_with_dtype(dtype):
+        ai = numpy.array(im, dtype=dtype)
+        assert ai.dtype == dtype
+
     # assert test("1") == ((100, 128), '|b1', 1600))
     assert test("L") == ((100, 128), "|u1", 12800)
 
@@ -27,6 +31,9 @@ def test(mode):
     assert test("RGBA") == ((100, 128, 4), "|u1", 51200)
     assert test("RGBX") == ((100, 128, 4), "|u1", 51200)
 
+    test_with_dtype(numpy.float64)
+    test_with_dtype(numpy.uint8)
+
     with Image.open("Tests/images/truncated_jpeg.jpg") as im_truncated:
         with pytest.raises(OSError):
             numpy.array(im_truncated)