{
    "file_diffs": [
        {
            "old_file_content": "from .helper import PillowTestCase, hopper\n\nfrom PIL import Image\nfrom PIL import ImageFile\nfrom PIL import ImageOps\n\ntry:\n    from PIL import _webp\n    HAVE_WEBP = True\nexcept ImportError:\n    HAVE_WEBP = False\n\n\nclass TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.pad(hopper(\"L\"), (128, 128))\n        ImageOps.pad(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n        ImageOps.exif_transpose(hopper(\"L\"))\n        ImageOps.exif_transpose(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pad(self):\n        # Same ratio\n        im = hopper()\n        new_size = (im.width * 2, im.height * 2)\n        new_im = ImageOps.pad(im, new_size)\n        self.assertEqual(new_im.size, new_size)\n\n        for label, color, new_size in [\n            (\"h\", None, (im.width * 4, im.height * 2)),\n            (\"v\", \"#f00\", (im.width * 2, im.height * 4))\n        ]:\n            for i, centering in enumerate([(0, 0), (0.5, 0.5), (1, 1)]):\n                new_im = ImageOps.pad(im, new_size,\n                                      color=color, centering=centering)\n                self.assertEqual(new_im.size, new_size)\n\n                target = Image.open(\n                    \"Tests/images/imageops_pad_\"+label+\"_\"+str(i)+\".jpg\")\n                self.assert_image_similar(new_im, target, 6)\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n\n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))\n\n    def test_colorize_2color(self):\n        # Test the colorizing function with 2-color functionality\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality\n        im_test = ImageOps.colorize(im, 'red', 'green')\n\n        # Test output image (2-color)\n        left = (0, 1)\n        middle = (127, 1)\n        right = (255, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_2color_offset(self):\n        # Test the colorizing function with 2-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    blackpoint=50,\n                                    whitepoint=100)\n\n        # Test output image (2-color) with offsets\n        left = (25, 1)\n        middle = (75, 1)\n        right = (125, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_3color_offset(self):\n        # Test the colorizing function with 3-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with new three color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    mid='blue',\n                                    blackpoint=50,\n                                    whitepoint=200,\n                                    midpoint=100)\n\n        # Test output image (3-color) with offsets\n        left = (25, 1)\n        left_middle = (75, 1)\n        middle = (100, 1)\n        right_middle = (150, 1)\n        right = (225, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(left_middle),\n                                       (127, 0, 127),\n                                       threshold=1,\n                                       msg='low-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (0, 0, 255),\n                                       threshold=1,\n                                       msg='mid incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right_middle),\n                                       (0, 63, 127),\n                                       threshold=1,\n                                       msg='high-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_exif_transpose(self):\n        exts = [\".jpg\"]\n        if HAVE_WEBP and _webp.HAVE_WEBPANIM:\n            exts.append(\".webp\")\n        for ext in exts:\n            base_im = Image.open(\"Tests/images/hopper\"+ext)\n\n            orientations = [base_im]\n            for i in range(2, 9):\n                im = Image.open(\"Tests/images/hopper_orientation_\"+str(i)+ext)\n                orientations.append(im)\n            for im in orientations:\n                if im is base_im:\n                    self.assertNotIn(\"exif\", im.info)\n                else:\n                    original_exif = im.info[\"exif\"]\n                transposed_im = ImageOps.exif_transpose(im)\n                self.assert_image_similar(base_im, transposed_im, 17)\n                if im is base_im:\n                    self.assertNotIn(\"exif\", im.info)\n                else:\n                    self.assertNotEqual(transposed_im.info[\"exif\"], original_exif)\n\n                    exif = ImageFile.Exif()\n                    exif.load(transposed_im.info[\"exif\"])\n                    self.assertNotIn(0x0112, exif)\n\n                # Repeat the operation, to test that it does not keep transposing\n                transposed_im2 = ImageOps.exif_transpose(transposed_im)\n                self.assert_image_equal(transposed_im2, transposed_im)\n",
            "new_file_content": "from .helper import PillowTestCase, hopper\n\nfrom PIL import Image\nfrom PIL import ImageFile\nfrom PIL import ImageOps\n\ntry:\n    from PIL import _webp\n    HAVE_WEBP = True\nexcept ImportError:\n    HAVE_WEBP = False\n\n\nclass TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.pad(hopper(\"L\"), (128, 128))\n        ImageOps.pad(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n        ImageOps.exif_transpose(hopper(\"L\"))\n        ImageOps.exif_transpose(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pad(self):\n        # Same ratio\n        im = hopper()\n        new_size = (im.width * 2, im.height * 2)\n        new_im = ImageOps.pad(im, new_size)\n        self.assertEqual(new_im.size, new_size)\n\n        for label, color, new_size in [\n            (\"h\", None, (im.width * 4, im.height * 2)),\n            (\"v\", \"#f00\", (im.width * 2, im.height * 4))\n        ]:\n            for i, centering in enumerate([(0, 0), (0.5, 0.5), (1, 1)]):\n                new_im = ImageOps.pad(im, new_size,\n                                      color=color, centering=centering)\n                self.assertEqual(new_im.size, new_size)\n\n                target = Image.open(\n                    \"Tests/images/imageops_pad_\"+label+\"_\"+str(i)+\".jpg\")\n                self.assert_image_similar(new_im, target, 6)\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n\n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))\n\n    def test_colorize_2color(self):\n        # Test the colorizing function with 2-color functionality\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality\n        im_test = ImageOps.colorize(im, 'red', 'green')\n\n        # Test output image (2-color)\n        left = (0, 1)\n        middle = (127, 1)\n        right = (255, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_2color_offset(self):\n        # Test the colorizing function with 2-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    blackpoint=50,\n                                    whitepoint=100)\n\n        # Test output image (2-color) with offsets\n        left = (25, 1)\n        middle = (75, 1)\n        right = (125, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_3color_offset(self):\n        # Test the colorizing function with 3-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with new three color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    mid='blue',\n                                    blackpoint=50,\n                                    whitepoint=200,\n                                    midpoint=100)\n\n        # Test output image (3-color) with offsets\n        left = (25, 1)\n        left_middle = (75, 1)\n        middle = (100, 1)\n        right_middle = (150, 1)\n        right = (225, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(left_middle),\n                                       (127, 0, 127),\n                                       threshold=1,\n                                       msg='low-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (0, 0, 255),\n                                       threshold=1,\n                                       msg='mid incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right_middle),\n                                       (0, 63, 127),\n                                       threshold=1,\n                                       msg='high-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_exif_transpose(self):\n        exts = [\".jpg\"]\n        if HAVE_WEBP and _webp.HAVE_WEBPANIM:\n            exts.append(\".webp\")\n        for ext in exts:\n            base_im = Image.open(\"Tests/images/hopper\"+ext)\n\n            orientations = [base_im]\n            for i in range(2, 9):\n                im = Image.open(\"Tests/images/hopper_orientation_\"+str(i)+ext)\n                orientations.append(im)\n            for i, orientation_im in enumerate(orientations):\n                for im in [\n                    orientation_im,        # ImageFile\n                    orientation_im.copy()  # Image\n                ]:\n                    if i == 0:\n                        self.assertNotIn(\"exif\", im.info)\n                    else:\n                        original_exif = im.info[\"exif\"]\n                    transposed_im = ImageOps.exif_transpose(im)\n                    self.assert_image_similar(base_im, transposed_im, 17)\n                    if i == 0:\n                        self.assertNotIn(\"exif\", im.info)\n                    else:\n                        self.assertNotEqual(transposed_im.info[\"exif\"], original_exif)\n\n                        exif = ImageFile.Exif()\n                        exif.load(transposed_im.info[\"exif\"])\n                        self.assertNotIn(0x0112, exif)\n\n                    # Repeat the operation, to test that it does not keep transposing\n                    transposed_im2 = ImageOps.exif_transpose(transposed_im)\n                    self.assert_image_equal(transposed_im2, transposed_im)\n",
            "header": {
                "file": {
                    "path": "Tests/test_imageops.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "f6fddde60",
                "new_commit_hash": "3b3a63122",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Tests/test_imageops.py"
            },
            "plus_file": {
                "path": "b/Tests/test_imageops.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 240,
                            "length": 22
                        },
                        "new_range": {
                            "start": 240,
                            "length": 26
                        },
                        "section": "class TestImageOps(PillowTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            for i in range(2, 9):",
                                "type": "context"
                            },
                            {
                                "content": "                im = Image.open(\"Tests/images/hopper_orientation_\"+str(i)+ext)",
                                "type": "context"
                            },
                            {
                                "content": "                orientations.append(im)",
                                "type": "context"
                            },
                            {
                                "content": "            for im in orientations:",
                                "type": "deleted"
                            },
                            {
                                "content": "                if im is base_im:",
                                "type": "deleted"
                            },
                            {
                                "content": "                    self.assertNotIn(\"exif\", im.info)",
                                "type": "deleted"
                            },
                            {
                                "content": "                else:",
                                "type": "deleted"
                            },
                            {
                                "content": "                    original_exif = im.info[\"exif\"]",
                                "type": "deleted"
                            },
                            {
                                "content": "                transposed_im = ImageOps.exif_transpose(im)",
                                "type": "deleted"
                            },
                            {
                                "content": "                self.assert_image_similar(base_im, transposed_im, 17)",
                                "type": "deleted"
                            },
                            {
                                "content": "                if im is base_im:",
                                "type": "deleted"
                            },
                            {
                                "content": "                    self.assertNotIn(\"exif\", im.info)",
                                "type": "deleted"
                            },
                            {
                                "content": "                else:",
                                "type": "deleted"
                            },
                            {
                                "content": "                    self.assertNotEqual(transposed_im.info[\"exif\"], original_exif)",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "                    exif = ImageFile.Exif()",
                                "type": "deleted"
                            },
                            {
                                "content": "                    exif.load(transposed_im.info[\"exif\"])",
                                "type": "deleted"
                            },
                            {
                                "content": "                    self.assertNotIn(0x0112, exif)",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "                # Repeat the operation, to test that it does not keep transposing",
                                "type": "deleted"
                            },
                            {
                                "content": "                transposed_im2 = ImageOps.exif_transpose(transposed_im)",
                                "type": "deleted"
                            },
                            {
                                "content": "                self.assert_image_equal(transposed_im2, transposed_im)",
                                "type": "deleted"
                            },
                            {
                                "content": "            for i, orientation_im in enumerate(orientations):",
                                "type": "added"
                            },
                            {
                                "content": "                for im in [",
                                "type": "added"
                            },
                            {
                                "content": "                    orientation_im,        # ImageFile",
                                "type": "added"
                            },
                            {
                                "content": "                    orientation_im.copy()  # Image",
                                "type": "added"
                            },
                            {
                                "content": "                ]:",
                                "type": "added"
                            },
                            {
                                "content": "                    if i == 0:",
                                "type": "added"
                            },
                            {
                                "content": "                        self.assertNotIn(\"exif\", im.info)",
                                "type": "added"
                            },
                            {
                                "content": "                    else:",
                                "type": "added"
                            },
                            {
                                "content": "                        original_exif = im.info[\"exif\"]",
                                "type": "added"
                            },
                            {
                                "content": "                    transposed_im = ImageOps.exif_transpose(im)",
                                "type": "added"
                            },
                            {
                                "content": "                    self.assert_image_similar(base_im, transposed_im, 17)",
                                "type": "added"
                            },
                            {
                                "content": "                    if i == 0:",
                                "type": "added"
                            },
                            {
                                "content": "                        self.assertNotIn(\"exif\", im.info)",
                                "type": "added"
                            },
                            {
                                "content": "                    else:",
                                "type": "added"
                            },
                            {
                                "content": "                        self.assertNotEqual(transposed_im.info[\"exif\"], original_exif)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "                        exif = ImageFile.Exif()",
                                "type": "added"
                            },
                            {
                                "content": "                        exif.load(transposed_im.info[\"exif\"])",
                                "type": "added"
                            },
                            {
                                "content": "                        self.assertNotIn(0x0112, exif)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "                    # Repeat the operation, to test that it does not keep transposing",
                                "type": "added"
                            },
                            {
                                "content": "                    transposed_im2 = ImageOps.exif_transpose(transposed_im)",
                                "type": "added"
                            },
                            {
                                "content": "                    self.assert_image_equal(transposed_im2, transposed_im)",
                                "type": "added"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_imageops.py",
                            "type": "method",
                            "name": "TestImageOps.test_exif_transpose",
                            "content": "class TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.pad(hopper(\"L\"), (128, 128))\n        ImageOps.pad(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n        ImageOps.exif_transpose(hopper(\"L\"))\n        ImageOps.exif_transpose(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pad(self):\n        # Same ratio\n        im = hopper()\n        new_size = (im.width * 2, im.height * 2)\n        new_im = ImageOps.pad(im, new_size)\n        self.assertEqual(new_im.size, new_size)\n\n        for label, color, new_size in [\n            (\"h\", None, (im.width * 4, im.height * 2)),\n            (\"v\", \"#f00\", (im.width * 2, im.height * 4))\n        ]:\n            for i, centering in enumerate([(0, 0), (0.5, 0.5), (1, 1)]):\n                new_im = ImageOps.pad(im, new_size,\n                                      color=color, centering=centering)\n                self.assertEqual(new_im.size, new_size)\n\n                target = Image.open(\n                    \"Tests/images/imageops_pad_\"+label+\"_\"+str(i)+\".jpg\")\n                self.assert_image_similar(new_im, target, 6)\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n\n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))\n\n    def test_colorize_2color(self):\n        # Test the colorizing function with 2-color functionality\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality\n        im_test = ImageOps.colorize(im, 'red', 'green')\n\n        # Test output image (2-color)\n        left = (0, 1)\n        middle = (127, 1)\n        right = (255, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_2color_offset(self):\n        # Test the colorizing function with 2-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    blackpoint=50,\n                                    whitepoint=100)\n\n        # Test output image (2-color) with offsets\n        left = (25, 1)\n        middle = (75, 1)\n        right = (125, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_3color_offset(self):\n        # Test the colorizing function with 3-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with new three color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    mid='blue',\n                                    blackpoint=50,\n                                    whitepoint=200,\n                                    midpoint=100)\n\n        # Test output image (3-color) with offsets\n        left = (25, 1)\n        left_middle = (75, 1)\n        middle = (100, 1)\n        right_middle = (150, 1)\n        right = (225, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(left_middle),\n                                       (127, 0, 127),\n                                       threshold=1,\n                                       msg='low-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (0, 0, 255),\n                                       threshold=1,\n                                       msg='mid incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right_middle),\n                                       (0, 63, 127),\n                                       threshold=1,\n                                       msg='high-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_exif_transpose(self):\n        exts = [\".jpg\"]\n        if HAVE_WEBP and _webp.HAVE_WEBPANIM:\n            exts.append(\".webp\")\n        for ext in exts:\n            base_im = Image.open(\"Tests/images/hopper\"+ext)\n\n            orientations = [base_im]\n            for i in range(2, 9):\n                im = Image.open(\"Tests/images/hopper_orientation_\"+str(i)+ext)\n                orientations.append(im)\n            for im in orientations:\n                if im is base_im:\n                    self.assertNotIn(\"exif\", im.info)\n                else:\n                    original_exif = im.info[\"exif\"]\n                transposed_im = ImageOps.exif_transpose(im)\n                self.assert_image_similar(base_im, transposed_im, 17)\n                if im is base_im:\n                    self.assertNotIn(\"exif\", im.info)\n                else:\n                    self.assertNotEqual(transposed_im.info[\"exif\"], original_exif)\n\n                    exif = ImageFile.Exif()\n                    exif.load(transposed_im.info[\"exif\"])\n                    self.assertNotIn(0x0112, exif)\n\n                # Repeat the operation, to test that it does not keep transposing\n                transposed_im2 = ImageOps.exif_transpose(transposed_im)\n                self.assert_image_equal(transposed_im2, transposed_im)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 232,
                            "end_lineno": 261,
                            "parent": {
                                "file_name": "Tests/test_imageops.py",
                                "type": "class",
                                "name": "TestImageOps",
                                "content": "class TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.pad(hopper(\"L\"), (128, 128))\n        ImageOps.pad(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n        ImageOps.exif_transpose(hopper(\"L\"))\n        ImageOps.exif_transpose(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pad(self):\n        # Same ratio\n        im = hopper()\n        new_size = (im.width * 2, im.height * 2)\n        new_im = ImageOps.pad(im, new_size)\n        self.assertEqual(new_im.size, new_size)\n\n        for label, color, new_size in [\n            (\"h\", None, (im.width * 4, im.height * 2)),\n            (\"v\", \"#f00\", (im.width * 2, im.height * 4))\n        ]:\n            for i, centering in enumerate([(0, 0), (0.5, 0.5), (1, 1)]):\n                new_im = ImageOps.pad(im, new_size,\n                                      color=color, centering=centering)\n                self.assertEqual(new_im.size, new_size)\n\n                target = Image.open(\n                    \"Tests/images/imageops_pad_\"+label+\"_\"+str(i)+\".jpg\")\n                self.assert_image_similar(new_im, target, 6)\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n\n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))\n\n    def test_colorize_2color(self):\n        # Test the colorizing function with 2-color functionality\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality\n        im_test = ImageOps.colorize(im, 'red', 'green')\n\n        # Test output image (2-color)\n        left = (0, 1)\n        middle = (127, 1)\n        right = (255, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_2color_offset(self):\n        # Test the colorizing function with 2-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    blackpoint=50,\n                                    whitepoint=100)\n\n        # Test output image (2-color) with offsets\n        left = (25, 1)\n        middle = (75, 1)\n        right = (125, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_3color_offset(self):\n        # Test the colorizing function with 3-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with new three color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    mid='blue',\n                                    blackpoint=50,\n                                    whitepoint=200,\n                                    midpoint=100)\n\n        # Test output image (3-color) with offsets\n        left = (25, 1)\n        left_middle = (75, 1)\n        middle = (100, 1)\n        right_middle = (150, 1)\n        right = (225, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(left_middle),\n                                       (127, 0, 127),\n                                       threshold=1,\n                                       msg='low-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (0, 0, 255),\n                                       threshold=1,\n                                       msg='mid incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right_middle),\n                                       (0, 63, 127),\n                                       threshold=1,\n                                       msg='high-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_exif_transpose(self):\n        exts = [\".jpg\"]\n        if HAVE_WEBP and _webp.HAVE_WEBPANIM:\n            exts.append(\".webp\")\n        for ext in exts:\n            base_im = Image.open(\"Tests/images/hopper\"+ext)\n\n            orientations = [base_im]\n            for i in range(2, 9):\n                im = Image.open(\"Tests/images/hopper_orientation_\"+str(i)+ext)\n                orientations.append(im)\n            for im in orientations:\n                if im is base_im:\n                    self.assertNotIn(\"exif\", im.info)\n                else:\n                    original_exif = im.info[\"exif\"]\n                transposed_im = ImageOps.exif_transpose(im)\n                self.assert_image_similar(base_im, transposed_im, 17)\n                if im is base_im:\n                    self.assertNotIn(\"exif\", im.info)\n                else:\n                    self.assertNotEqual(transposed_im.info[\"exif\"], original_exif)\n\n                    exif = ImageFile.Exif()\n                    exif.load(transposed_im.info[\"exif\"])\n                    self.assertNotIn(0x0112, exif)\n\n                # Repeat the operation, to test that it does not keep transposing\n                transposed_im2 = ImageOps.exif_transpose(transposed_im)\n                self.assert_image_equal(transposed_im2, transposed_im)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 14,
                                "end_lineno": 261,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Tests/test_imageops.py",
                            "type": "class",
                            "name": "TestImageOps",
                            "content": "class TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.pad(hopper(\"L\"), (128, 128))\n        ImageOps.pad(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n        ImageOps.exif_transpose(hopper(\"L\"))\n        ImageOps.exif_transpose(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pad(self):\n        # Same ratio\n        im = hopper()\n        new_size = (im.width * 2, im.height * 2)\n        new_im = ImageOps.pad(im, new_size)\n        self.assertEqual(new_im.size, new_size)\n\n        for label, color, new_size in [\n            (\"h\", None, (im.width * 4, im.height * 2)),\n            (\"v\", \"#f00\", (im.width * 2, im.height * 4))\n        ]:\n            for i, centering in enumerate([(0, 0), (0.5, 0.5), (1, 1)]):\n                new_im = ImageOps.pad(im, new_size,\n                                      color=color, centering=centering)\n                self.assertEqual(new_im.size, new_size)\n\n                target = Image.open(\n                    \"Tests/images/imageops_pad_\"+label+\"_\"+str(i)+\".jpg\")\n                self.assert_image_similar(new_im, target, 6)\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n\n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))\n\n    def test_colorize_2color(self):\n        # Test the colorizing function with 2-color functionality\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality\n        im_test = ImageOps.colorize(im, 'red', 'green')\n\n        # Test output image (2-color)\n        left = (0, 1)\n        middle = (127, 1)\n        right = (255, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_2color_offset(self):\n        # Test the colorizing function with 2-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    blackpoint=50,\n                                    whitepoint=100)\n\n        # Test output image (2-color) with offsets\n        left = (25, 1)\n        middle = (75, 1)\n        right = (125, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_3color_offset(self):\n        # Test the colorizing function with 3-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with new three color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    mid='blue',\n                                    blackpoint=50,\n                                    whitepoint=200,\n                                    midpoint=100)\n\n        # Test output image (3-color) with offsets\n        left = (25, 1)\n        left_middle = (75, 1)\n        middle = (100, 1)\n        right_middle = (150, 1)\n        right = (225, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(left_middle),\n                                       (127, 0, 127),\n                                       threshold=1,\n                                       msg='low-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (0, 0, 255),\n                                       threshold=1,\n                                       msg='mid incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right_middle),\n                                       (0, 63, 127),\n                                       threshold=1,\n                                       msg='high-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_exif_transpose(self):\n        exts = [\".jpg\"]\n        if HAVE_WEBP and _webp.HAVE_WEBPANIM:\n            exts.append(\".webp\")\n        for ext in exts:\n            base_im = Image.open(\"Tests/images/hopper\"+ext)\n\n            orientations = [base_im]\n            for i in range(2, 9):\n                im = Image.open(\"Tests/images/hopper_orientation_\"+str(i)+ext)\n                orientations.append(im)\n            for im in orientations:\n                if im is base_im:\n                    self.assertNotIn(\"exif\", im.info)\n                else:\n                    original_exif = im.info[\"exif\"]\n                transposed_im = ImageOps.exif_transpose(im)\n                self.assert_image_similar(base_im, transposed_im, 17)\n                if im is base_im:\n                    self.assertNotIn(\"exif\", im.info)\n                else:\n                    self.assertNotEqual(transposed_im.info[\"exif\"], original_exif)\n\n                    exif = ImageFile.Exif()\n                    exif.load(transposed_im.info[\"exif\"])\n                    self.assertNotIn(0x0112, exif)\n\n                # Repeat the operation, to test that it does not keep transposing\n                transposed_im2 = ImageOps.exif_transpose(transposed_im)\n                self.assert_image_equal(transposed_im2, transposed_im)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 14,
                            "end_lineno": 261,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# standard image operations\n#\n# History:\n# 2001-10-20 fl   Created\n# 2001-10-23 fl   Added autocontrast operator\n# 2001-12-18 fl   Added Kevin's fit operator\n# 2004-03-14 fl   Fixed potential division by zero in equalize\n# 2005-05-05 fl   Fixed equalize for low number of values\n#\n# Copyright (c) 2001-2004 by Secret Labs AB\n# Copyright (c) 2001-2004 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom . import Image, ImageFile\nfrom ._util import isStringType\nimport operator\nimport functools\n\n\n#\n# helpers\n\ndef _border(border):\n    if isinstance(border, tuple):\n        if len(border) == 2:\n            left, top = right, bottom = border\n        elif len(border) == 4:\n            left, top, right, bottom = border\n    else:\n        left = top = right = bottom = border\n    return left, top, right, bottom\n\n\ndef _color(color, mode):\n    if isStringType(color):\n        from . import ImageColor\n        color = ImageColor.getcolor(color, mode)\n    return color\n\n\ndef _lut(image, lut):\n    if image.mode == \"P\":\n        # FIXME: apply to lookup table, not image data\n        raise NotImplementedError(\"mode P support coming soon\")\n    elif image.mode in (\"L\", \"RGB\"):\n        if image.mode == \"RGB\" and len(lut) == 256:\n            lut = lut + lut + lut\n        return image.point(lut)\n    else:\n        raise IOError(\"not supported for this image mode\")\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None):\n    \"\"\"\n    Maximize (normalize) image contrast. This function calculates a\n    histogram of the input image, removes **cutoff** percent of the\n    lightest and darkest pixels from the histogram, and remaps the image\n    so that the darkest pixel becomes black (0), and the lightest\n    becomes white (255).\n\n    :param image: The image to process.\n    :param cutoff: How many percent to cut off from the histogram.\n    :param ignore: The background pixel value (use None for no background).\n    :return: An image.\n    \"\"\"\n    histogram = image.histogram()\n    lut = []\n    for layer in range(0, len(histogram), 256):\n        h = histogram[layer:layer+256]\n        if ignore is not None:\n            # get rid of outliers\n            try:\n                h[ignore] = 0\n            except TypeError:\n                # assume sequence\n                for ix in ignore:\n                    h[ix] = 0\n        if cutoff:\n            # cut off pixels from both ends of the histogram\n            # get number of pixels\n            n = 0\n            for ix in range(256):\n                n = n + h[ix]\n            # remove cutoff% pixels from the low end\n            cut = n * cutoff // 100\n            for lo in range(256):\n                if cut > h[lo]:\n                    cut = cut - h[lo]\n                    h[lo] = 0\n                else:\n                    h[lo] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n            # remove cutoff% samples from the hi end\n            cut = n * cutoff // 100\n            for hi in range(255, -1, -1):\n                if cut > h[hi]:\n                    cut = cut - h[hi]\n                    h[hi] = 0\n                else:\n                    h[hi] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n        # find lowest/highest samples after preprocessing\n        for lo in range(256):\n            if h[lo]:\n                break\n        for hi in range(255, -1, -1):\n            if h[hi]:\n                break\n        if hi <= lo:\n            # don't bother\n            lut.extend(list(range(256)))\n        else:\n            scale = 255.0 / (hi - lo)\n            offset = -lo * scale\n            for ix in range(256):\n                ix = int(ix * scale + offset)\n                if ix < 0:\n                    ix = 0\n                elif ix > 255:\n                    ix = 255\n                lut.append(ix)\n    return _lut(image, lut)\n\n\ndef colorize(image, black, white, mid=None, blackpoint=0,\n             whitepoint=255, midpoint=127):\n    \"\"\"\n    Colorize grayscale image.\n    This function calculates a color wedge which maps all black pixels in\n    the source image to the first color and all white pixels to the\n    second color. If **mid** is specified, it uses three-color mapping.\n    The **black** and **white** arguments should be RGB tuples or color names;\n    optionally you can use three-color mapping by also specifying **mid**.\n    Mapping positions for any of the colors can be specified\n    (e.g. **blackpoint**), where these parameters are the integer\n    value corresponding to where the corresponding color should be mapped.\n    These parameters must have logical order, such that\n    **blackpoint** <= **midpoint** <= **whitepoint** (if **mid** is specified).\n\n    :param image: The image to colorize.\n    :param black: The color to use for black input pixels.\n    :param white: The color to use for white input pixels.\n    :param mid: The color to use for midtone input pixels.\n    :param blackpoint: an int value [0, 255] for the black mapping.\n    :param whitepoint: an int value [0, 255] for the white mapping.\n    :param midpoint: an int value [0, 255] for the midtone mapping.\n    :return: An image.\n    \"\"\"\n\n    # Initial asserts\n    assert image.mode == \"L\"\n    if mid is None:\n        assert 0 <= blackpoint <= whitepoint <= 255\n    else:\n        assert 0 <= blackpoint <= midpoint <= whitepoint <= 255\n\n    # Define colors from arguments\n    black = _color(black, \"RGB\")\n    white = _color(white, \"RGB\")\n    if mid is not None:\n        mid = _color(mid, \"RGB\")\n\n    # Empty lists for the mapping\n    red = []\n    green = []\n    blue = []\n\n    # Create the low-end values\n    for i in range(0, blackpoint):\n        red.append(black[0])\n        green.append(black[1])\n        blue.append(black[2])\n\n    # Create the mapping (2-color)\n    if mid is None:\n\n        range_map = range(0, whitepoint - blackpoint)\n\n        for i in range_map:\n            red.append(black[0] + i * (white[0] - black[0]) // len(range_map))\n            green.append(black[1] + i * (white[1] - black[1]) // len(range_map))\n            blue.append(black[2] + i * (white[2] - black[2]) // len(range_map))\n\n    # Create the mapping (3-color)\n    else:\n\n        range_map1 = range(0, midpoint - blackpoint)\n        range_map2 = range(0, whitepoint - midpoint)\n\n        for i in range_map1:\n            red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1))\n            green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1))\n            blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1))\n        for i in range_map2:\n            red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2))\n            green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2))\n            blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2))\n\n    # Create the high-end values\n    for i in range(0, 256 - whitepoint):\n        red.append(white[0])\n        green.append(white[1])\n        blue.append(white[2])\n\n    # Return converted image\n    image = image.convert(\"RGB\")\n    return _lut(image, red + green + blue)\n\n\ndef pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a sized and padded version of the image, expanded to fill the\n    requested aspect ratio and size.\n\n    :param image: The image to size and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: What resampling method to use. Default is\n                   :py:attr:`PIL.Image.NEAREST`.\n    :param color: The background color of the padded image.\n    :param centering: Control the position of the original image within the\n                      padded version.\n                          (0.5, 0.5) will keep the image centered\n                          (0, 0) will keep the image aligned to the top left\n                          (1, 1) will keep the image aligned to the bottom\n                          right\n    :return: An image.\n    \"\"\"\n\n    im_ratio = image.width / image.height\n    dest_ratio = float(size[0]) / size[1]\n\n    if im_ratio == dest_ratio:\n        out = image.resize(size, resample=method)\n    else:\n        out = Image.new(image.mode, size, color)\n        if im_ratio > dest_ratio:\n            new_height = int(image.height / image.width * size[0])\n            if new_height != size[1]:\n                image = image.resize((size[0], new_height), resample=method)\n\n            y = int((size[1] - new_height) * max(0, min(centering[1], 1)))\n            out.paste(image, (0, y))\n        else:\n            new_width = int(image.width / image.height * size[1])\n            if new_width != size[0]:\n                image = image.resize((new_width, size[1]), resample=method)\n\n            x = int((size[0] - new_width) * max(0, min(centering[0], 1)))\n            out.paste(image, (x, 0))\n    return out\n\n\ndef crop(image, border=0):\n    \"\"\"\n    Remove border from image.  The same amount of pixels are removed\n    from all four sides.  This function works on all image modes.\n\n    .. seealso:: :py:meth:`~PIL.Image.Image.crop`\n\n    :param image: The image to crop.\n    :param border: The number of pixels to remove.\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    return image.crop(\n        (left, top, image.size[0]-right, image.size[1]-bottom)\n        )\n\n\ndef scale(image, factor, resample=Image.NEAREST):\n    \"\"\"\n    Returns a rescaled image by a specific factor given in parameter.\n    A factor greater than 1 expands the image, between 0 and 1 contracts the\n    image.\n\n    :param image: The image to rescale.\n    :param factor: The expansion factor, as a float.\n    :param resample: An optional resampling filter. Same values possible as\n       in the PIL.Image.resize function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n    if factor == 1:\n        return image.copy()\n    elif factor <= 0:\n        raise ValueError(\"the factor must be greater than 0\")\n    else:\n        size = (int(round(factor * image.width)),\n                int(round(factor * image.height)))\n        return image.resize(size, resample)\n\n\ndef deform(image, deformer, resample=Image.BILINEAR):\n    \"\"\"\n    Deform the image.\n\n    :param image: The image to deform.\n    :param deformer: A deformer object.  Any object that implements a\n                    **getmesh** method can be used.\n    :param resample: An optional resampling filter. Same values possible as\n       in the PIL.Image.transform function.\n    :return: An image.\n    \"\"\"\n    return image.transform(\n        image.size, Image.MESH, deformer.getmesh(image), resample\n        )\n\n\ndef equalize(image, mask=None):\n    \"\"\"\n    Equalize the image histogram. This function applies a non-linear\n    mapping to the input image, in order to create a uniform\n    distribution of grayscale values in the output image.\n\n    :param image: The image to equalize.\n    :param mask: An optional mask.  If given, only the pixels selected by\n                 the mask are included in the analysis.\n    :return: An image.\n    \"\"\"\n    if image.mode == \"P\":\n        image = image.convert(\"RGB\")\n    h = image.histogram(mask)\n    lut = []\n    for b in range(0, len(h), 256):\n        histo = [_f for _f in h[b:b+256] if _f]\n        if len(histo) <= 1:\n            lut.extend(list(range(256)))\n        else:\n            step = (functools.reduce(operator.add, histo) - histo[-1]) // 255\n            if not step:\n                lut.extend(list(range(256)))\n            else:\n                n = step // 2\n                for i in range(256):\n                    lut.append(n // step)\n                    n = n + h[i+b]\n    return _lut(image, lut)\n\n\ndef expand(image, border=0, fill=0):\n    \"\"\"\n    Add border to the image\n\n    :param image: The image to expand.\n    :param border: Border width, in pixels.\n    :param fill: Pixel fill value (a color value).  Default is 0 (black).\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    width = left + image.size[0] + right\n    height = top + image.size[1] + bottom\n    out = Image.new(image.mode, (width, height), _color(fill, image.mode))\n    out.paste(image, (left, top))\n    return out\n\n\ndef fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a sized and cropped version of the image, cropped to the\n    requested aspect ratio and size.\n\n    This function was contributed by Kevin Cazabon.\n\n    :param image: The image to size and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: What resampling method to use. Default is\n                   :py:attr:`PIL.Image.NEAREST`.\n    :param bleed: Remove a border around the outside of the image from all\n                  four edges. The value is a decimal percentage (use 0.01 for\n                  one percent). The default value is 0 (no border).\n                  Cannot be greater than or equal to 0.5.\n    :param centering: Control the cropping position.  Use (0.5, 0.5) for\n                      center cropping (e.g. if cropping the width, take 50% off\n                      of the left side, and therefore 50% off the right side).\n                      (0.0, 0.0) will crop from the top left corner (i.e. if\n                      cropping the width, take all of the crop off of the right\n                      side, and if cropping the height, take all of it off the\n                      bottom).  (1.0, 0.0) will crop from the bottom left\n                      corner, etc. (i.e. if cropping the width, take all of the\n                      crop off the left side, and if cropping the height take\n                      none from the top, and therefore all off the bottom).\n    :return: An image.\n    \"\"\"\n\n    # by Kevin Cazabon, Feb 17/2000\n    # kevin@cazabon.com\n    # http://www.cazabon.com\n\n    # ensure centering is mutable\n    centering = list(centering)\n\n    if not 0.0 <= centering[0] <= 1.0:\n        centering[0] = 0.5\n    if not 0.0 <= centering[1] <= 1.0:\n        centering[1] = 0.5\n\n    if not 0.0 <= bleed < 0.5:\n        bleed = 0.0\n\n    # calculate the area to use for resizing and cropping, subtracting\n    # the 'bleed' around the edges\n\n    # number of pixels to trim off on Top and Bottom, Left and Right\n    bleed_pixels = (bleed * image.size[0], bleed * image.size[1])\n\n    live_size = (image.size[0] - bleed_pixels[0] * 2,\n                 image.size[1] - bleed_pixels[1] * 2)\n\n    # calculate the aspect ratio of the live_size\n    live_size_ratio = float(live_size[0]) / live_size[1]\n\n    # calculate the aspect ratio of the output image\n    output_ratio = float(size[0]) / size[1]\n\n    # figure out if the sides or top/bottom will be cropped off\n    if live_size_ratio >= output_ratio:\n        # live_size is wider than what's needed, crop the sides\n        crop_width = output_ratio * live_size[1]\n        crop_height = live_size[1]\n    else:\n        # live_size is taller than what's needed, crop the top and bottom\n        crop_width = live_size[0]\n        crop_height = live_size[0] / output_ratio\n\n    # make the crop\n    crop_left = bleed_pixels[0] + (live_size[0]-crop_width) * centering[0]\n    crop_top = bleed_pixels[1] + (live_size[1]-crop_height) * centering[1]\n\n    crop = (\n        crop_left, crop_top,\n        crop_left + crop_width, crop_top + crop_height\n    )\n\n    # resize the image and return it\n    return image.resize(size, method, box=crop)\n\n\ndef flip(image):\n    \"\"\"\n    Flip the image vertically (top to bottom).\n\n    :param image: The image to flip.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_TOP_BOTTOM)\n\n\ndef grayscale(image):\n    \"\"\"\n    Convert the image to grayscale.\n\n    :param image: The image to convert.\n    :return: An image.\n    \"\"\"\n    return image.convert(\"L\")\n\n\ndef invert(image):\n    \"\"\"\n    Invert (negate) the image.\n\n    :param image: The image to invert.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        lut.append(255-i)\n    return _lut(image, lut)\n\n\ndef mirror(image):\n    \"\"\"\n    Flip image horizontally (left to right).\n\n    :param image: The image to mirror.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_LEFT_RIGHT)\n\n\ndef posterize(image, bits):\n    \"\"\"\n    Reduce the number of bits for each color channel.\n\n    :param image: The image to posterize.\n    :param bits: The number of bits to keep for each channel (1-8).\n    :return: An image.\n    \"\"\"\n    lut = []\n    mask = ~(2**(8-bits)-1)\n    for i in range(256):\n        lut.append(i & mask)\n    return _lut(image, lut)\n\n\ndef solarize(image, threshold=128):\n    \"\"\"\n    Invert all pixel values above a threshold.\n\n    :param image: The image to solarize.\n    :param threshold: All pixels above this greyscale level are inverted.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        if i < threshold:\n            lut.append(i)\n        else:\n            lut.append(255-i)\n    return _lut(image, lut)\n\n\ndef exif_transpose(image):\n    \"\"\"\n    If an image has an EXIF Orientation tag, return a new image that is\n    transposed accordingly. Otherwise, return a copy of the image.\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    if isinstance(image, ImageFile.ImageFile):\n        exif = image.getexif()\n        if exif:\n            orientation = exif.get(0x0112)\n            method = {\n                2: Image.FLIP_LEFT_RIGHT,\n                3: Image.ROTATE_180,\n                4: Image.FLIP_TOP_BOTTOM,\n                5: Image.TRANSPOSE,\n                6: Image.ROTATE_270,\n                7: Image.TRANSVERSE,\n                8: Image.ROTATE_90\n            }.get(orientation)\n            if method is not None:\n                transposed_image = image.transpose(method)\n                del exif[0x0112]\n                transposed_image.info[\"exif\"] = exif.tobytes()\n                return transposed_image\n    return image.copy()\n",
            "new_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# standard image operations\n#\n# History:\n# 2001-10-20 fl   Created\n# 2001-10-23 fl   Added autocontrast operator\n# 2001-12-18 fl   Added Kevin's fit operator\n# 2004-03-14 fl   Fixed potential division by zero in equalize\n# 2005-05-05 fl   Fixed equalize for low number of values\n#\n# Copyright (c) 2001-2004 by Secret Labs AB\n# Copyright (c) 2001-2004 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom . import Image, ImageFile\nfrom ._util import isStringType\nimport operator\nimport functools\n\n\n#\n# helpers\n\ndef _border(border):\n    if isinstance(border, tuple):\n        if len(border) == 2:\n            left, top = right, bottom = border\n        elif len(border) == 4:\n            left, top, right, bottom = border\n    else:\n        left = top = right = bottom = border\n    return left, top, right, bottom\n\n\ndef _color(color, mode):\n    if isStringType(color):\n        from . import ImageColor\n        color = ImageColor.getcolor(color, mode)\n    return color\n\n\ndef _lut(image, lut):\n    if image.mode == \"P\":\n        # FIXME: apply to lookup table, not image data\n        raise NotImplementedError(\"mode P support coming soon\")\n    elif image.mode in (\"L\", \"RGB\"):\n        if image.mode == \"RGB\" and len(lut) == 256:\n            lut = lut + lut + lut\n        return image.point(lut)\n    else:\n        raise IOError(\"not supported for this image mode\")\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None):\n    \"\"\"\n    Maximize (normalize) image contrast. This function calculates a\n    histogram of the input image, removes **cutoff** percent of the\n    lightest and darkest pixels from the histogram, and remaps the image\n    so that the darkest pixel becomes black (0), and the lightest\n    becomes white (255).\n\n    :param image: The image to process.\n    :param cutoff: How many percent to cut off from the histogram.\n    :param ignore: The background pixel value (use None for no background).\n    :return: An image.\n    \"\"\"\n    histogram = image.histogram()\n    lut = []\n    for layer in range(0, len(histogram), 256):\n        h = histogram[layer:layer+256]\n        if ignore is not None:\n            # get rid of outliers\n            try:\n                h[ignore] = 0\n            except TypeError:\n                # assume sequence\n                for ix in ignore:\n                    h[ix] = 0\n        if cutoff:\n            # cut off pixels from both ends of the histogram\n            # get number of pixels\n            n = 0\n            for ix in range(256):\n                n = n + h[ix]\n            # remove cutoff% pixels from the low end\n            cut = n * cutoff // 100\n            for lo in range(256):\n                if cut > h[lo]:\n                    cut = cut - h[lo]\n                    h[lo] = 0\n                else:\n                    h[lo] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n            # remove cutoff% samples from the hi end\n            cut = n * cutoff // 100\n            for hi in range(255, -1, -1):\n                if cut > h[hi]:\n                    cut = cut - h[hi]\n                    h[hi] = 0\n                else:\n                    h[hi] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n        # find lowest/highest samples after preprocessing\n        for lo in range(256):\n            if h[lo]:\n                break\n        for hi in range(255, -1, -1):\n            if h[hi]:\n                break\n        if hi <= lo:\n            # don't bother\n            lut.extend(list(range(256)))\n        else:\n            scale = 255.0 / (hi - lo)\n            offset = -lo * scale\n            for ix in range(256):\n                ix = int(ix * scale + offset)\n                if ix < 0:\n                    ix = 0\n                elif ix > 255:\n                    ix = 255\n                lut.append(ix)\n    return _lut(image, lut)\n\n\ndef colorize(image, black, white, mid=None, blackpoint=0,\n             whitepoint=255, midpoint=127):\n    \"\"\"\n    Colorize grayscale image.\n    This function calculates a color wedge which maps all black pixels in\n    the source image to the first color and all white pixels to the\n    second color. If **mid** is specified, it uses three-color mapping.\n    The **black** and **white** arguments should be RGB tuples or color names;\n    optionally you can use three-color mapping by also specifying **mid**.\n    Mapping positions for any of the colors can be specified\n    (e.g. **blackpoint**), where these parameters are the integer\n    value corresponding to where the corresponding color should be mapped.\n    These parameters must have logical order, such that\n    **blackpoint** <= **midpoint** <= **whitepoint** (if **mid** is specified).\n\n    :param image: The image to colorize.\n    :param black: The color to use for black input pixels.\n    :param white: The color to use for white input pixels.\n    :param mid: The color to use for midtone input pixels.\n    :param blackpoint: an int value [0, 255] for the black mapping.\n    :param whitepoint: an int value [0, 255] for the white mapping.\n    :param midpoint: an int value [0, 255] for the midtone mapping.\n    :return: An image.\n    \"\"\"\n\n    # Initial asserts\n    assert image.mode == \"L\"\n    if mid is None:\n        assert 0 <= blackpoint <= whitepoint <= 255\n    else:\n        assert 0 <= blackpoint <= midpoint <= whitepoint <= 255\n\n    # Define colors from arguments\n    black = _color(black, \"RGB\")\n    white = _color(white, \"RGB\")\n    if mid is not None:\n        mid = _color(mid, \"RGB\")\n\n    # Empty lists for the mapping\n    red = []\n    green = []\n    blue = []\n\n    # Create the low-end values\n    for i in range(0, blackpoint):\n        red.append(black[0])\n        green.append(black[1])\n        blue.append(black[2])\n\n    # Create the mapping (2-color)\n    if mid is None:\n\n        range_map = range(0, whitepoint - blackpoint)\n\n        for i in range_map:\n            red.append(black[0] + i * (white[0] - black[0]) // len(range_map))\n            green.append(black[1] + i * (white[1] - black[1]) // len(range_map))\n            blue.append(black[2] + i * (white[2] - black[2]) // len(range_map))\n\n    # Create the mapping (3-color)\n    else:\n\n        range_map1 = range(0, midpoint - blackpoint)\n        range_map2 = range(0, whitepoint - midpoint)\n\n        for i in range_map1:\n            red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1))\n            green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1))\n            blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1))\n        for i in range_map2:\n            red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2))\n            green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2))\n            blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2))\n\n    # Create the high-end values\n    for i in range(0, 256 - whitepoint):\n        red.append(white[0])\n        green.append(white[1])\n        blue.append(white[2])\n\n    # Return converted image\n    image = image.convert(\"RGB\")\n    return _lut(image, red + green + blue)\n\n\ndef pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a sized and padded version of the image, expanded to fill the\n    requested aspect ratio and size.\n\n    :param image: The image to size and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: What resampling method to use. Default is\n                   :py:attr:`PIL.Image.NEAREST`.\n    :param color: The background color of the padded image.\n    :param centering: Control the position of the original image within the\n                      padded version.\n                          (0.5, 0.5) will keep the image centered\n                          (0, 0) will keep the image aligned to the top left\n                          (1, 1) will keep the image aligned to the bottom\n                          right\n    :return: An image.\n    \"\"\"\n\n    im_ratio = image.width / image.height\n    dest_ratio = float(size[0]) / size[1]\n\n    if im_ratio == dest_ratio:\n        out = image.resize(size, resample=method)\n    else:\n        out = Image.new(image.mode, size, color)\n        if im_ratio > dest_ratio:\n            new_height = int(image.height / image.width * size[0])\n            if new_height != size[1]:\n                image = image.resize((size[0], new_height), resample=method)\n\n            y = int((size[1] - new_height) * max(0, min(centering[1], 1)))\n            out.paste(image, (0, y))\n        else:\n            new_width = int(image.width / image.height * size[1])\n            if new_width != size[0]:\n                image = image.resize((new_width, size[1]), resample=method)\n\n            x = int((size[0] - new_width) * max(0, min(centering[0], 1)))\n            out.paste(image, (x, 0))\n    return out\n\n\ndef crop(image, border=0):\n    \"\"\"\n    Remove border from image.  The same amount of pixels are removed\n    from all four sides.  This function works on all image modes.\n\n    .. seealso:: :py:meth:`~PIL.Image.Image.crop`\n\n    :param image: The image to crop.\n    :param border: The number of pixels to remove.\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    return image.crop(\n        (left, top, image.size[0]-right, image.size[1]-bottom)\n        )\n\n\ndef scale(image, factor, resample=Image.NEAREST):\n    \"\"\"\n    Returns a rescaled image by a specific factor given in parameter.\n    A factor greater than 1 expands the image, between 0 and 1 contracts the\n    image.\n\n    :param image: The image to rescale.\n    :param factor: The expansion factor, as a float.\n    :param resample: An optional resampling filter. Same values possible as\n       in the PIL.Image.resize function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n    if factor == 1:\n        return image.copy()\n    elif factor <= 0:\n        raise ValueError(\"the factor must be greater than 0\")\n    else:\n        size = (int(round(factor * image.width)),\n                int(round(factor * image.height)))\n        return image.resize(size, resample)\n\n\ndef deform(image, deformer, resample=Image.BILINEAR):\n    \"\"\"\n    Deform the image.\n\n    :param image: The image to deform.\n    :param deformer: A deformer object.  Any object that implements a\n                    **getmesh** method can be used.\n    :param resample: An optional resampling filter. Same values possible as\n       in the PIL.Image.transform function.\n    :return: An image.\n    \"\"\"\n    return image.transform(\n        image.size, Image.MESH, deformer.getmesh(image), resample\n        )\n\n\ndef equalize(image, mask=None):\n    \"\"\"\n    Equalize the image histogram. This function applies a non-linear\n    mapping to the input image, in order to create a uniform\n    distribution of grayscale values in the output image.\n\n    :param image: The image to equalize.\n    :param mask: An optional mask.  If given, only the pixels selected by\n                 the mask are included in the analysis.\n    :return: An image.\n    \"\"\"\n    if image.mode == \"P\":\n        image = image.convert(\"RGB\")\n    h = image.histogram(mask)\n    lut = []\n    for b in range(0, len(h), 256):\n        histo = [_f for _f in h[b:b+256] if _f]\n        if len(histo) <= 1:\n            lut.extend(list(range(256)))\n        else:\n            step = (functools.reduce(operator.add, histo) - histo[-1]) // 255\n            if not step:\n                lut.extend(list(range(256)))\n            else:\n                n = step // 2\n                for i in range(256):\n                    lut.append(n // step)\n                    n = n + h[i+b]\n    return _lut(image, lut)\n\n\ndef expand(image, border=0, fill=0):\n    \"\"\"\n    Add border to the image\n\n    :param image: The image to expand.\n    :param border: Border width, in pixels.\n    :param fill: Pixel fill value (a color value).  Default is 0 (black).\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    width = left + image.size[0] + right\n    height = top + image.size[1] + bottom\n    out = Image.new(image.mode, (width, height), _color(fill, image.mode))\n    out.paste(image, (left, top))\n    return out\n\n\ndef fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a sized and cropped version of the image, cropped to the\n    requested aspect ratio and size.\n\n    This function was contributed by Kevin Cazabon.\n\n    :param image: The image to size and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: What resampling method to use. Default is\n                   :py:attr:`PIL.Image.NEAREST`.\n    :param bleed: Remove a border around the outside of the image from all\n                  four edges. The value is a decimal percentage (use 0.01 for\n                  one percent). The default value is 0 (no border).\n                  Cannot be greater than or equal to 0.5.\n    :param centering: Control the cropping position.  Use (0.5, 0.5) for\n                      center cropping (e.g. if cropping the width, take 50% off\n                      of the left side, and therefore 50% off the right side).\n                      (0.0, 0.0) will crop from the top left corner (i.e. if\n                      cropping the width, take all of the crop off of the right\n                      side, and if cropping the height, take all of it off the\n                      bottom).  (1.0, 0.0) will crop from the bottom left\n                      corner, etc. (i.e. if cropping the width, take all of the\n                      crop off the left side, and if cropping the height take\n                      none from the top, and therefore all off the bottom).\n    :return: An image.\n    \"\"\"\n\n    # by Kevin Cazabon, Feb 17/2000\n    # kevin@cazabon.com\n    # http://www.cazabon.com\n\n    # ensure centering is mutable\n    centering = list(centering)\n\n    if not 0.0 <= centering[0] <= 1.0:\n        centering[0] = 0.5\n    if not 0.0 <= centering[1] <= 1.0:\n        centering[1] = 0.5\n\n    if not 0.0 <= bleed < 0.5:\n        bleed = 0.0\n\n    # calculate the area to use for resizing and cropping, subtracting\n    # the 'bleed' around the edges\n\n    # number of pixels to trim off on Top and Bottom, Left and Right\n    bleed_pixels = (bleed * image.size[0], bleed * image.size[1])\n\n    live_size = (image.size[0] - bleed_pixels[0] * 2,\n                 image.size[1] - bleed_pixels[1] * 2)\n\n    # calculate the aspect ratio of the live_size\n    live_size_ratio = float(live_size[0]) / live_size[1]\n\n    # calculate the aspect ratio of the output image\n    output_ratio = float(size[0]) / size[1]\n\n    # figure out if the sides or top/bottom will be cropped off\n    if live_size_ratio >= output_ratio:\n        # live_size is wider than what's needed, crop the sides\n        crop_width = output_ratio * live_size[1]\n        crop_height = live_size[1]\n    else:\n        # live_size is taller than what's needed, crop the top and bottom\n        crop_width = live_size[0]\n        crop_height = live_size[0] / output_ratio\n\n    # make the crop\n    crop_left = bleed_pixels[0] + (live_size[0]-crop_width) * centering[0]\n    crop_top = bleed_pixels[1] + (live_size[1]-crop_height) * centering[1]\n\n    crop = (\n        crop_left, crop_top,\n        crop_left + crop_width, crop_top + crop_height\n    )\n\n    # resize the image and return it\n    return image.resize(size, method, box=crop)\n\n\ndef flip(image):\n    \"\"\"\n    Flip the image vertically (top to bottom).\n\n    :param image: The image to flip.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_TOP_BOTTOM)\n\n\ndef grayscale(image):\n    \"\"\"\n    Convert the image to grayscale.\n\n    :param image: The image to convert.\n    :return: An image.\n    \"\"\"\n    return image.convert(\"L\")\n\n\ndef invert(image):\n    \"\"\"\n    Invert (negate) the image.\n\n    :param image: The image to invert.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        lut.append(255-i)\n    return _lut(image, lut)\n\n\ndef mirror(image):\n    \"\"\"\n    Flip image horizontally (left to right).\n\n    :param image: The image to mirror.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_LEFT_RIGHT)\n\n\ndef posterize(image, bits):\n    \"\"\"\n    Reduce the number of bits for each color channel.\n\n    :param image: The image to posterize.\n    :param bits: The number of bits to keep for each channel (1-8).\n    :return: An image.\n    \"\"\"\n    lut = []\n    mask = ~(2**(8-bits)-1)\n    for i in range(256):\n        lut.append(i & mask)\n    return _lut(image, lut)\n\n\ndef solarize(image, threshold=128):\n    \"\"\"\n    Invert all pixel values above a threshold.\n\n    :param image: The image to solarize.\n    :param threshold: All pixels above this greyscale level are inverted.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        if i < threshold:\n            lut.append(i)\n        else:\n            lut.append(255-i)\n    return _lut(image, lut)\n\n\ndef exif_transpose(image):\n    \"\"\"\n    If an image has an EXIF Orientation tag, return a new image that is\n    transposed accordingly. Otherwise, return a copy of the image.\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    if \"exif\" in image.info:\n        exif = ImageFile.Exif()\n        exif.load(image.info[\"exif\"])\n        orientation = exif.get(0x0112)\n        method = {\n            2: Image.FLIP_LEFT_RIGHT,\n            3: Image.ROTATE_180,\n            4: Image.FLIP_TOP_BOTTOM,\n            5: Image.TRANSPOSE,\n            6: Image.ROTATE_270,\n            7: Image.TRANSVERSE,\n            8: Image.ROTATE_90\n        }.get(orientation)\n        if method is not None:\n            transposed_image = image.transpose(method)\n            del exif[0x0112]\n            transposed_image.info[\"exif\"] = exif.tobytes()\n            return transposed_image\n    return image.copy()\n",
            "header": {
                "file": {
                    "path": "src/PIL/ImageOps.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "147f2821d",
                "new_commit_hash": "2cab10884",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/src/PIL/ImageOps.py"
            },
            "plus_file": {
                "path": "b/src/PIL/ImageOps.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 532,
                            "length": 22
                        },
                        "new_range": {
                            "start": 532,
                            "length": 22
                        },
                        "section": "def exif_transpose(image):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    :param image: The image to transpose.",
                                "type": "context"
                            },
                            {
                                "content": "    :return: An image.",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    if isinstance(image, ImageFile.ImageFile):",
                                "type": "deleted"
                            },
                            {
                                "content": "        exif = image.getexif()",
                                "type": "deleted"
                            },
                            {
                                "content": "        if exif:",
                                "type": "deleted"
                            },
                            {
                                "content": "            orientation = exif.get(0x0112)",
                                "type": "deleted"
                            },
                            {
                                "content": "            method = {",
                                "type": "deleted"
                            },
                            {
                                "content": "                2: Image.FLIP_LEFT_RIGHT,",
                                "type": "deleted"
                            },
                            {
                                "content": "                3: Image.ROTATE_180,",
                                "type": "deleted"
                            },
                            {
                                "content": "                4: Image.FLIP_TOP_BOTTOM,",
                                "type": "deleted"
                            },
                            {
                                "content": "                5: Image.TRANSPOSE,",
                                "type": "deleted"
                            },
                            {
                                "content": "                6: Image.ROTATE_270,",
                                "type": "deleted"
                            },
                            {
                                "content": "                7: Image.TRANSVERSE,",
                                "type": "deleted"
                            },
                            {
                                "content": "                8: Image.ROTATE_90",
                                "type": "deleted"
                            },
                            {
                                "content": "            }.get(orientation)",
                                "type": "deleted"
                            },
                            {
                                "content": "            if method is not None:",
                                "type": "deleted"
                            },
                            {
                                "content": "                transposed_image = image.transpose(method)",
                                "type": "deleted"
                            },
                            {
                                "content": "                del exif[0x0112]",
                                "type": "deleted"
                            },
                            {
                                "content": "                transposed_image.info[\"exif\"] = exif.tobytes()",
                                "type": "deleted"
                            },
                            {
                                "content": "                return transposed_image",
                                "type": "deleted"
                            },
                            {
                                "content": "    if \"exif\" in image.info:",
                                "type": "added"
                            },
                            {
                                "content": "        exif = ImageFile.Exif()",
                                "type": "added"
                            },
                            {
                                "content": "        exif.load(image.info[\"exif\"])",
                                "type": "added"
                            },
                            {
                                "content": "        orientation = exif.get(0x0112)",
                                "type": "added"
                            },
                            {
                                "content": "        method = {",
                                "type": "added"
                            },
                            {
                                "content": "            2: Image.FLIP_LEFT_RIGHT,",
                                "type": "added"
                            },
                            {
                                "content": "            3: Image.ROTATE_180,",
                                "type": "added"
                            },
                            {
                                "content": "            4: Image.FLIP_TOP_BOTTOM,",
                                "type": "added"
                            },
                            {
                                "content": "            5: Image.TRANSPOSE,",
                                "type": "added"
                            },
                            {
                                "content": "            6: Image.ROTATE_270,",
                                "type": "added"
                            },
                            {
                                "content": "            7: Image.TRANSVERSE,",
                                "type": "added"
                            },
                            {
                                "content": "            8: Image.ROTATE_90",
                                "type": "added"
                            },
                            {
                                "content": "        }.get(orientation)",
                                "type": "added"
                            },
                            {
                                "content": "        if method is not None:",
                                "type": "added"
                            },
                            {
                                "content": "            transposed_image = image.transpose(method)",
                                "type": "added"
                            },
                            {
                                "content": "            del exif[0x0112]",
                                "type": "added"
                            },
                            {
                                "content": "            transposed_image.info[\"exif\"] = exif.tobytes()",
                                "type": "added"
                            },
                            {
                                "content": "            return transposed_image",
                                "type": "added"
                            },
                            {
                                "content": "    return image.copy()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/ImageOps.py",
                            "type": "function",
                            "name": "exif_transpose",
                            "content": "def exif_transpose(image):\n    \"\"\"\n    If an image has an EXIF Orientation tag, return a new image that is\n    transposed accordingly. Otherwise, return a copy of the image.\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    if isinstance(image, ImageFile.ImageFile):\n        exif = image.getexif()\n        if exif:\n            orientation = exif.get(0x0112)\n            method = {\n                2: Image.FLIP_LEFT_RIGHT,\n                3: Image.ROTATE_180,\n                4: Image.FLIP_TOP_BOTTOM,\n                5: Image.TRANSPOSE,\n                6: Image.ROTATE_270,\n                7: Image.TRANSVERSE,\n                8: Image.ROTATE_90\n            }.get(orientation)\n            if method is not None:\n                transposed_image = image.transpose(method)\n                del exif[0x0112]\n                transposed_image.info[\"exif\"] = exif.tobytes()\n                return transposed_image\n    return image.copy()",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 527,
                            "end_lineno": 553,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "8f0db65cd7ca102c8e3c8072afcceba6bb76965e^",
    "new_commit_hash": "8f0db65cd7ca102c8e3c8072afcceba6bb76965e",
    "commit_message": "Allow exif_transpose to work on Image instances as well as ImageFile",
    "commit_date": "2019-04-01T19:37:25+11:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "8f0db65cd7ca102c8e3c8072afcceba6bb76965e",
    "test_file_codes": [
        "from .helper import PillowTestCase, hopper\n\nfrom PIL import Image\nfrom PIL import ImageFile\nfrom PIL import ImageOps\n\ntry:\n    from PIL import _webp\n    HAVE_WEBP = True\nexcept ImportError:\n    HAVE_WEBP = False\n\n\nclass TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.pad(hopper(\"L\"), (128, 128))\n        ImageOps.pad(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n        ImageOps.exif_transpose(hopper(\"L\"))\n        ImageOps.exif_transpose(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pad(self):\n        # Same ratio\n        im = hopper()\n        new_size = (im.width * 2, im.height * 2)\n        new_im = ImageOps.pad(im, new_size)\n        self.assertEqual(new_im.size, new_size)\n\n        for label, color, new_size in [\n            (\"h\", None, (im.width * 4, im.height * 2)),\n            (\"v\", \"#f00\", (im.width * 2, im.height * 4))\n        ]:\n            for i, centering in enumerate([(0, 0), (0.5, 0.5), (1, 1)]):\n                new_im = ImageOps.pad(im, new_size,\n                                      color=color, centering=centering)\n                self.assertEqual(new_im.size, new_size)\n\n                target = Image.open(\n                    \"Tests/images/imageops_pad_\"+label+\"_\"+str(i)+\".jpg\")\n                self.assert_image_similar(new_im, target, 6)\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n\n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))\n\n    def test_colorize_2color(self):\n        # Test the colorizing function with 2-color functionality\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality\n        im_test = ImageOps.colorize(im, 'red', 'green')\n\n        # Test output image (2-color)\n        left = (0, 1)\n        middle = (127, 1)\n        right = (255, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_2color_offset(self):\n        # Test the colorizing function with 2-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with original 2-color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    blackpoint=50,\n                                    whitepoint=100)\n\n        # Test output image (2-color) with offsets\n        left = (25, 1)\n        middle = (75, 1)\n        right = (125, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (127, 63, 0),\n                                       threshold=1,\n                                       msg='mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_colorize_3color_offset(self):\n        # Test the colorizing function with 3-color functionality and offset\n\n        # Open test image (256px by 10px, black to white)\n        im = Image.open(\"Tests/images/bw_gradient.png\")\n        im = im.convert(\"L\")\n\n        # Create image with new three color functionality with offsets\n        im_test = ImageOps.colorize(im,\n                                    black='red',\n                                    white='green',\n                                    mid='blue',\n                                    blackpoint=50,\n                                    whitepoint=200,\n                                    midpoint=100)\n\n        # Test output image (3-color) with offsets\n        left = (25, 1)\n        left_middle = (75, 1)\n        middle = (100, 1)\n        right_middle = (150, 1)\n        right = (225, 1)\n        self.assert_tuple_approx_equal(im_test.getpixel(left),\n                                       (255, 0, 0),\n                                       threshold=1,\n                                       msg='black test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(left_middle),\n                                       (127, 0, 127),\n                                       threshold=1,\n                                       msg='low-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(middle),\n                                       (0, 0, 255),\n                                       threshold=1,\n                                       msg='mid incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right_middle),\n                                       (0, 63, 127),\n                                       threshold=1,\n                                       msg='high-mid test pixel incorrect')\n        self.assert_tuple_approx_equal(im_test.getpixel(right),\n                                       (0, 127, 0),\n                                       threshold=1,\n                                       msg='white test pixel incorrect')\n\n    def test_exif_transpose(self):\n        exts = [\".jpg\"]\n        if HAVE_WEBP and _webp.HAVE_WEBPANIM:\n            exts.append(\".webp\")\n        for ext in exts:\n            base_im = Image.open(\"Tests/images/hopper\"+ext)\n\n            orientations = [base_im]\n            for i in range(2, 9):\n                im = Image.open(\"Tests/images/hopper_orientation_\"+str(i)+ext)\n                orientations.append(im)\n            for i, orientation_im in enumerate(orientations):\n                for im in [\n                    orientation_im,        # ImageFile\n                    orientation_im.copy()  # Image\n                ]:\n                    if i == 0:\n                        self.assertNotIn(\"exif\", im.info)\n                    else:\n                        original_exif = im.info[\"exif\"]\n                    transposed_im = ImageOps.exif_transpose(im)\n                    self.assert_image_similar(base_im, transposed_im, 17)\n                    if i == 0:\n                        self.assertNotIn(\"exif\", im.info)\n                    else:\n                        self.assertNotEqual(transposed_im.info[\"exif\"], original_exif)\n\n                        exif = ImageFile.Exif()\n                        exif.load(transposed_im.info[\"exif\"])\n                        self.assertNotIn(0x0112, exif)\n\n                    # Repeat the operation, to test that it does not keep transposing\n                    transposed_im2 = ImageOps.exif_transpose(transposed_im)\n                    self.assert_image_equal(transposed_im2, transposed_im)\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Pillow installation attempts...\nVerifying Pillow installation...\n✅ Pillow installation successful!\nSuccessfully installed Pillow\n",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 12 packages in 14ms\nInstalled 12 packages in 133ms\n + coverage==7.6.10\n + exceptiongroup==1.2.2\n + iniconfig==2.0.0\n + packaging==24.2\n + pluggy==1.5.0\n + pyqt5==5.15.11\n + pyqt5-qt5==5.15.16\n + pyqt5-sip==12.16.1\n + pytest==8.3.4\n + pytest-cov==6.0.0\n + setuptools==75.8.0\n + tomli==2.2.1\nResolved 1 package in 859ms\nPrepared 1 package in 30.58s\nInstalled 1 package in 1ms\n + pillow==6.0.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_8f0db65cd7ca102c8e3c8072afcceba6bb76965e)\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_8f0db65cd7ca102c8e3c8072afcceba6bb76965e\nplugins: cov-6.0.0\ncollected 9 items\n\nr2e_tests/test_1.py .........                                            [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestImageOps::test_1pxfit\nPASSED r2e_tests/test_1.py::TestImageOps::test_colorize_2color\nPASSED r2e_tests/test_1.py::TestImageOps::test_colorize_2color_offset\nPASSED r2e_tests/test_1.py::TestImageOps::test_colorize_3color_offset\nPASSED r2e_tests/test_1.py::TestImageOps::test_exif_transpose\nPASSED r2e_tests/test_1.py::TestImageOps::test_pad\nPASSED r2e_tests/test_1.py::TestImageOps::test_pil163\nPASSED r2e_tests/test_1.py::TestImageOps::test_sanity\nPASSED r2e_tests/test_1.py::TestImageOps::test_scale\n============================== 9 passed in 0.34s ===============================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_8f0db65cd7ca102c8e3c8072afcceba6bb76965e\nplugins: cov-6.0.0\ncollected 9 items\n\nr2e_tests/test_1.py ....F....                                            [100%]\n\n=================================== FAILURES ===================================\n_______________________ TestImageOps.test_exif_transpose _______________________\n\nself = <r2e_tests.test_1.TestImageOps testMethod=test_exif_transpose>\n\n    def test_exif_transpose(self):\n        exts = [\".jpg\"]\n        if HAVE_WEBP and _webp.HAVE_WEBPANIM:\n            exts.append(\".webp\")\n        for ext in exts:\n            base_im = Image.open(\"Tests/images/hopper\"+ext)\n    \n            orientations = [base_im]\n            for i in range(2, 9):\n                im = Image.open(\"Tests/images/hopper_orientation_\"+str(i)+ext)\n                orientations.append(im)\n            for i, orientation_im in enumerate(orientations):\n                for im in [\n                    orientation_im,        # ImageFile\n                    orientation_im.copy()  # Image\n                ]:\n                    if i == 0:\n                        self.assertNotIn(\"exif\", im.info)\n                    else:\n                        original_exif = im.info[\"exif\"]\n                    transposed_im = ImageOps.exif_transpose(im)\n>                   self.assert_image_similar(base_im, transposed_im, 17)\n\nr2e_tests/test_1.py:253: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nr2e_tests/helper.py:150: in assert_image_similar\n    raise e\nr2e_tests/helper.py:138: in assert_image_similar\n    self.assertGreaterEqual(\nE   AssertionError: 17.0 not greater than or equal to 187.18292236328125 :  average pixel value difference 187.1829 > epsilon 17.0000\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestImageOps::test_1pxfit\nPASSED r2e_tests/test_1.py::TestImageOps::test_colorize_2color\nPASSED r2e_tests/test_1.py::TestImageOps::test_colorize_2color_offset\nPASSED r2e_tests/test_1.py::TestImageOps::test_colorize_3color_offset\nPASSED r2e_tests/test_1.py::TestImageOps::test_pad\nPASSED r2e_tests/test_1.py::TestImageOps::test_pil163\nPASSED r2e_tests/test_1.py::TestImageOps::test_sanity\nPASSED r2e_tests/test_1.py::TestImageOps::test_scale\nFAILED r2e_tests/test_1.py::TestImageOps::test_exif_transpose - AssertionErro...\n========================= 1 failed, 8 passed in 0.19s ==========================\n",
    "old_commit_res_stderr": ""
}
Tests/test_imageops.py src/PIL/ImageOps.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `exif_transpose` Fails to Correctly Orient Images Using Generic `Image` Instances

**Description:**
When using the `exif_transpose` function on a standard `Image` instance, the image does not get properly transposed based on its EXIF orientation data. This results in incorrectly oriented images, which can lead to significant pixel discrepancies.

**Example Code:**
```python
from PIL import Image, ImageOps

# Open image as a generic Image instance
image = Image.open("Tests/images/hopper_orientation_6.jpg")

# Attempt to transpose based on EXIF data
transposed_image = ImageOps.exif_transpose(image)

# The transposed_image does not have the correct orientation
transposed_image.show()
```

**Expected Behavior:**
The `transposed_image` should be correctly rotated or flipped according to the EXIF orientation tag of the original image, resulting in the image being displayed with the intended orientation.

**Actual Behavior:**
The `transposed_image` retains the original orientation without applying the necessary rotation or flipping, leading to discrepancies in the image's appearance.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### src/PIL/ImageOps.py
#
# The Python Imaging Library.
# $Id$
#
# standard image operations
#
# History:
# 2001-10-20 fl   Created
# 2001-10-23 fl   Added autocontrast operator
# 2001-12-18 fl   Added Kevin's fit operator
# 2004-03-14 fl   Fixed potential division by zero in equalize
# 2005-05-05 fl   Fixed equalize for low number of values
#
# Copyright (c) 2001-2004 by Secret Labs AB
# Copyright (c) 2001-2004 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#

from . import Image, ImageFile
from ._util import isStringType
import operator
import functools


#
# helpers

def _border(border):
    if isinstance(border, tuple):
        if len(border) == 2:
            left, top = right, bottom = border
        elif len(border) == 4:
            left, top, right, bottom = border
    else:
        left = top = right = bottom = border
    return left, top, right, bottom


def _color(color, mode):
    if isStringType(color):
        from . import ImageColor
        color = ImageColor.getcolor(color, mode)
    return color


def _lut(image, lut):
    if image.mode == "P":
        # FIXME: apply to lookup table, not image data
        raise NotImplementedError("mode P support coming soon")
    elif image.mode in ("L", "RGB"):
        if image.mode == "RGB" and len(lut) == 256:
            lut = lut + lut + lut
        return image.point(lut)
    else:
        raise IOError("not supported for this image mode")

#
# actions


def autocontrast(image, cutoff=0, ignore=None):
    """
    Maximize (normalize) image contrast. This function calculates a
    histogram of the input image, removes **cutoff** percent of the
    lightest and darkest pixels from the histogram, and remaps the image
    so that the darkest pixel becomes black (0), and the lightest
    becomes white (255).

    :param image: The image to process.
    :param cutoff: How many percent to cut off from the histogram.
    :param ignore: The background pixel value (use None for no background).
    :return: An image.
    """
    histogram = image.histogram()
    lut = []
    for layer in range(0, len(histogram), 256):
        h = histogram[layer:layer+256]
        if ignore is not None:
            # get rid of outliers
            try:
                h[ignore] = 0
            except TypeError:
                # assume sequence
                for ix in ignore:
                    h[ix] = 0
        if cutoff:
            # cut off pixels from both ends of the histogram
            # get number of pixels
            n = 0
            for ix in range(256):
                n = n + h[ix]
            # remove cutoff% pixels from the low end
            cut = n * cutoff // 100
            for lo in range(256):
                if cut > h[lo]:
                    cut = cut - h[lo]
                    h[lo] = 0
                else:
                    h[lo] -= cut
                    cut = 0
                if cut <= 0:
                    break
            # remove cutoff% samples from the hi end
            cut = n * cutoff // 100
            for hi in range(255, -1, -1):
                if cut > h[hi]:
                    cut = cut - h[hi]
                    h[hi] = 0
                else:
                    h[hi] -= cut
                    cut = 0
                if cut <= 0:
                    break
        # find lowest/highest samples after preprocessing
        for lo in range(256):
            if h[lo]:
                break
        for hi in range(255, -1, -1):
            if h[hi]:
                break
        if hi <= lo:
            # don't bother
            lut.extend(list(range(256)))
        else:
            scale = 255.0 / (hi - lo)
            offset = -lo * scale
            for ix in range(256):
                ix = int(ix * scale + offset)
                if ix < 0:
                    ix = 0
                elif ix > 255:
                    ix = 255
                lut.append(ix)
    return _lut(image, lut)


def colorize(image, black, white, mid=None, blackpoint=0,
             whitepoint=255, midpoint=127):
    """
    Colorize grayscale image.
    This function calculates a color wedge which maps all black pixels in
    the source image to the first color and all white pixels to the
    second color. If **mid** is specified, it uses three-color mapping.
    The **black** and **white** arguments should be RGB tuples or color names;
    optionally you can use three-color mapping by also specifying **mid**.
    Mapping positions for any of the colors can be specified
    (e.g. **blackpoint**), where these parameters are the integer
    value corresponding to where the corresponding color should be mapped.
    These parameters must have logical order, such that
    **blackpoint** <= **midpoint** <= **whitepoint** (if **mid** is specified).

    :param image: The image to colorize.
    :param black: The color to use for black input pixels.
    :param white: The color to use for white input pixels.
    :param mid: The color to use for midtone input pixels.
    :param blackpoint: an int value [0, 255] for the black mapping.
    :param whitepoint: an int value [0, 255] for the white mapping.
    :param midpoint: an int value [0, 255] for the midtone mapping.
    :return: An image.
    """

    # Initial asserts
    assert image.mode == "L"
    if mid is None:
        assert 0 <= blackpoint <= whitepoint <= 255
    else:
        assert 0 <= blackpoint <= midpoint <= whitepoint <= 255

    # Define colors from arguments
    black = _color(black, "RGB")
    white = _color(white, "RGB")
    if mid is not None:
        mid = _color(mid, "RGB")

    # Empty lists for the mapping
    red = []
    green = []
    blue = []

    # Create the low-end values
    for i in range(0, blackpoint):
        red.append(black[0])
        green.append(black[1])
        blue.append(black[2])

    # Create the mapping (2-color)
    if mid is None:

        range_map = range(0, whitepoint - blackpoint)

        for i in range_map:
            red.append(black[0] + i * (white[0] - black[0]) // len(range_map))
            green.append(black[1] + i * (white[1] - black[1]) // len(range_map))
            blue.append(black[2] + i * (white[2] - black[2]) // len(range_map))

    # Create the mapping (3-color)
    else:

        range_map1 = range(0, midpoint - blackpoint)
        range_map2 = range(0, whitepoint - midpoint)

        for i in range_map1:
            red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1))
            green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1))
            blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1))
        for i in range_map2:
            red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2))
            green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2))
            blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2))

    # Create the high-end values
    for i in range(0, 256 - whitepoint):
        red.append(white[0])
        green.append(white[1])
        blue.append(white[2])

    # Return converted image
    image = image.convert("RGB")
    return _lut(image, red + green + blue)


def pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)):
    """
    Returns a sized and padded version of the image, expanded to fill the
    requested aspect ratio and size.

    :param image: The image to size and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: What resampling method to use. Default is
                   :py:attr:`PIL.Image.NEAREST`.
    :param color: The background color of the padded image.
    :param centering: Control the position of the original image within the
                      padded version.
                          (0.5, 0.5) will keep the image centered
                          (0, 0) will keep the image aligned to the top left
                          (1, 1) will keep the image aligned to the bottom
                          right
    :return: An image.
    """

    im_ratio = image.width / image.height
    dest_ratio = float(size[0]) / size[1]

    if im_ratio == dest_ratio:
        out = image.resize(size, resample=method)
    else:
        out = Image.new(image.mode, size, color)
        if im_ratio > dest_ratio:
            new_height = int(image.height / image.width * size[0])
            if new_height != size[1]:
                image = image.resize((size[0], new_height), resample=method)

            y = int((size[1] - new_height) * max(0, min(centering[1], 1)))
            out.paste(image, (0, y))
        else:
            new_width = int(image.width / image.height * size[1])
            if new_width != size[0]:
                image = image.resize((new_width, size[1]), resample=method)

            x = int((size[0] - new_width) * max(0, min(centering[0], 1)))
            out.paste(image, (x, 0))
    return out


def crop(image, border=0):
    """
    Remove border from image.  The same amount of pixels are removed
    from all four sides.  This function works on all image modes.

    .. seealso:: :py:meth:`~PIL.Image.Image.crop`

    :param image: The image to crop.
    :param border: The number of pixels to remove.
    :return: An image.
    """
    left, top, right, bottom = _border(border)
    return image.crop(
        (left, top, image.size[0]-right, image.size[1]-bottom)
        )


def scale(image, factor, resample=Image.NEAREST):
    """
    Returns a rescaled image by a specific factor given in parameter.
    A factor greater than 1 expands the image, between 0 and 1 contracts the
    image.

    :param image: The image to rescale.
    :param factor: The expansion factor, as a float.
    :param resample: An optional resampling filter. Same values possible as
       in the PIL.Image.resize function.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """
    if factor == 1:
        return image.copy()
    elif factor <= 0:
        raise ValueError("the factor must be greater than 0")
    else:
        size = (int(round(factor * image.width)),
                int(round(factor * image.height)))
        return image.resize(size, resample)


def deform(image, deformer, resample=Image.BILINEAR):
    """
    Deform the image.

    :param image: The image to deform.
    :param deformer: A deformer object.  Any object that implements a
                    **getmesh** method can be used.
    :param resample: An optional resampling filter. Same values possible as
       in the PIL.Image.transform function.
    :return: An image.
    """
    return image.transform(
        image.size, Image.MESH, deformer.getmesh(image), resample
        )


def equalize(image, mask=None):
    """
    Equalize the image histogram. This function applies a non-linear
    mapping to the input image, in order to create a uniform
    distribution of grayscale values in the output image.

    :param image: The image to equalize.
    :param mask: An optional mask.  If given, only the pixels selected by
                 the mask are included in the analysis.
    :return: An image.
    """
    if image.mode == "P":
        image = image.convert("RGB")
    h = image.histogram(mask)
    lut = []
    for b in range(0, len(h), 256):
        histo = [_f for _f in h[b:b+256] if _f]
        if len(histo) <= 1:
            lut.extend(list(range(256)))
        else:
            step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
            if not step:
                lut.extend(list(range(256)))
            else:
                n = step // 2
                for i in range(256):
                    lut.append(n // step)
                    n = n + h[i+b]
    return _lut(image, lut)


def expand(image, border=0, fill=0):
    """
    Add border to the image

    :param image: The image to expand.
    :param border: Border width, in pixels.
    :param fill: Pixel fill value (a color value).  Default is 0 (black).
    :return: An image.
    """
    left, top, right, bottom = _border(border)
    width = left + image.size[0] + right
    height = top + image.size[1] + bottom
    out = Image.new(image.mode, (width, height), _color(fill, image.mode))
    out.paste(image, (left, top))
    return out


def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
    """
    Returns a sized and cropped version of the image, cropped to the
    requested aspect ratio and size.

    This function was contributed by Kevin Cazabon.

    :param image: The image to size and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: What resampling method to use. Default is
                   :py:attr:`PIL.Image.NEAREST`.
    :param bleed: Remove a border around the outside of the image from all
                  four edges. The value is a decimal percentage (use 0.01 for
                  one percent). The default value is 0 (no border).
                  Cannot be greater than or equal to 0.5.
    :param centering: Control the cropping position.  Use (0.5, 0.5) for
                      center cropping (e.g. if cropping the width, take 50% off
                      of the left side, and therefore 50% off the right side).
                      (0.0, 0.0) will crop from the top left corner (i.e. if
                      cropping the width, take all of the crop off of the right
                      side, and if cropping the height, take all of it off the
                      bottom).  (1.0, 0.0) will crop from the bottom left
                      corner, etc. (i.e. if cropping the width, take all of the
                      crop off the left side, and if cropping the height take
                      none from the top, and therefore all off the bottom).
    :return: An image.
    """

    # by Kevin Cazabon, Feb 17/2000
    # kevin@cazabon.com
    # http://www.cazabon.com

    # ensure centering is mutable
    centering = list(centering)

    if not 0.0 <= centering[0] <= 1.0:
        centering[0] = 0.5
    if not 0.0 <= centering[1] <= 1.0:
        centering[1] = 0.5

    if not 0.0 <= bleed < 0.5:
        bleed = 0.0

    # calculate the area to use for resizing and cropping, subtracting
    # the 'bleed' around the edges

    # number of pixels to trim off on Top and Bottom, Left and Right
    bleed_pixels = (bleed * image.size[0], bleed * image.size[1])

    live_size = (image.size[0] - bleed_pixels[0] * 2,
                 image.size[1] - bleed_pixels[1] * 2)

    # calculate the aspect ratio of the live_size
    live_size_ratio = float(live_size[0]) / live_size[1]

    # calculate the aspect ratio of the output image
    output_ratio = float(size[0]) / size[1]

    # figure out if the sides or top/bottom will be cropped off
    if live_size_ratio >= output_ratio:
        # live_size is wider than what's needed, crop the sides
        crop_width = output_ratio * live_size[1]
        crop_height = live_size[1]
    else:
        # live_size is taller than what's needed, crop the top and bottom
        crop_width = live_size[0]
        crop_height = live_size[0] / output_ratio

    # make the crop
    crop_left = bleed_pixels[0] + (live_size[0]-crop_width) * centering[0]
    crop_top = bleed_pixels[1] + (live_size[1]-crop_height) * centering[1]

    crop = (
        crop_left, crop_top,
        crop_left + crop_width, crop_top + crop_height
    )

    # resize the image and return it
    return image.resize(size, method, box=crop)


def flip(image):
    """
    Flip the image vertically (top to bottom).

    :param image: The image to flip.
    :return: An image.
    """
    return image.transpose(Image.FLIP_TOP_BOTTOM)


def grayscale(image):
    """
    Convert the image to grayscale.

    :param image: The image to convert.
    :return: An image.
    """
    return image.convert("L")


def invert(image):
    """
    Invert (negate) the image.

    :param image: The image to invert.
    :return: An image.
    """
    lut = []
    for i in range(256):
        lut.append(255-i)
    return _lut(image, lut)


def mirror(image):
    """
    Flip image horizontally (left to right).

    :param image: The image to mirror.
    :return: An image.
    """
    return image.transpose(Image.FLIP_LEFT_RIGHT)


def posterize(image, bits):
    """
    Reduce the number of bits for each color channel.

    :param image: The image to posterize.
    :param bits: The number of bits to keep for each channel (1-8).
    :return: An image.
    """
    lut = []
    mask = ~(2**(8-bits)-1)
    for i in range(256):
        lut.append(i & mask)
    return _lut(image, lut)


def solarize(image, threshold=128):
    """
    Invert all pixel values above a threshold.

    :param image: The image to solarize.
    :param threshold: All pixels above this greyscale level are inverted.
    :return: An image.
    """
    lut = []
    for i in range(256):
        if i < threshold:
            lut.append(i)
        else:
            lut.append(255-i)
    return _lut(image, lut)


def exif_transpose(image):
    """
    If an image has an EXIF Orientation tag, return a new image that is
    transposed accordingly. Otherwise, return a copy of the image.

    :param image: The image to transpose.
    :return: An image.
    """
    if isinstance(image, ImageFile.ImageFile):
        exif = image.getexif()
        if exif:
            orientation = exif.get(0x0112)
            method = {
                2: Image.FLIP_LEFT_RIGHT,
                3: Image.ROTATE_180,
                4: Image.FLIP_TOP_BOTTOM,
                5: Image.TRANSPOSE,
                6: Image.ROTATE_270,
                7: Image.TRANSVERSE,
                8: Image.ROTATE_90
            }.get(orientation)
            if method is not None:
                transposed_image = image.transpose(method)
                del exif[0x0112]
                transposed_image.info["exif"] = exif.tobytes()
                return transposed_image
    return image.copy()

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** `exif_transpose` Fails to Correctly Orient Images Using Generic `Image` Instances

**Description:**
When using the `exif_transpose` function on a standard `Image` instance, the image does not get properly transposed based on its EXIF orientation data. This results in incorrectly oriented images, which can lead to significant pixel discrepancies.

**Example Code:**
```python
from PIL import Image, ImageOps

# Open image as a generic Image instance
image = Image.open("Tests/images/hopper_orientation_6.jpg")

# Attempt to transpose based on EXIF data
transposed_image = ImageOps.exif_transpose(image)

# The transposed_image does not have the correct orientation
transposed_image.show()
```

**Expected Behavior:**
The `transposed_image` should be correctly rotated or flipped according to the EXIF orientation tag of the original image, resulting in the image being displayed with the intended orientation.

**Actual Behavior:**
The `transposed_image` retains the original orientation without applying the necessary rotation or flipping, leading to discrepancies in the image's appearance.

[/ISSUE]
{
    "TestImageOps.test_1pxfit": "PASSED",
    "TestImageOps.test_colorize_2color": "PASSED",
    "TestImageOps.test_colorize_2color_offset": "PASSED",
    "TestImageOps.test_colorize_3color_offset": "PASSED",
    "TestImageOps.test_exif_transpose": "PASSED",
    "TestImageOps.test_pad": "PASSED",
    "TestImageOps.test_pil163": "PASSED",
    "TestImageOps.test_sanity": "PASSED",
    "TestImageOps.test_scale": "PASSED"
}
diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py
index 147f2821d..2cab10884 100644
--- a/src/PIL/ImageOps.py
+++ b/src/PIL/ImageOps.py
@@ -532,22 +532,22 @@ def exif_transpose(image):
     :param image: The image to transpose.
     :return: An image.
     """
-    if isinstance(image, ImageFile.ImageFile):
-        exif = image.getexif()
-        if exif:
-            orientation = exif.get(0x0112)
-            method = {
-                2: Image.FLIP_LEFT_RIGHT,
-                3: Image.ROTATE_180,
-                4: Image.FLIP_TOP_BOTTOM,
-                5: Image.TRANSPOSE,
-                6: Image.ROTATE_270,
-                7: Image.TRANSVERSE,
-                8: Image.ROTATE_90
-            }.get(orientation)
-            if method is not None:
-                transposed_image = image.transpose(method)
-                del exif[0x0112]
-                transposed_image.info["exif"] = exif.tobytes()
-                return transposed_image
+    if "exif" in image.info:
+        exif = ImageFile.Exif()
+        exif.load(image.info["exif"])
+        orientation = exif.get(0x0112)
+        method = {
+            2: Image.FLIP_LEFT_RIGHT,
+            3: Image.ROTATE_180,
+            4: Image.FLIP_TOP_BOTTOM,
+            5: Image.TRANSPOSE,
+            6: Image.ROTATE_270,
+            7: Image.TRANSVERSE,
+            8: Image.ROTATE_90
+        }.get(orientation)
+        if method is not None:
+            transposed_image = image.transpose(method)
+            del exif[0x0112]
+            transposed_image.info["exif"] = exif.tobytes()
+            return transposed_image
     return image.copy()
 

{"src/PIL/ImageOps.py": "#\n# The Python Imaging Library.\n# $Id$\n#\n# standard image operations\n#\n# History:\n# 2001-10-20 fl   Created\n# 2001-10-23 fl   Added autocontrast operator\n# 2001-12-18 fl   Added Kevin's fit operator\n# 2004-03-14 fl   Fixed potential division by zero in equalize\n# 2005-05-05 fl   Fixed equalize for low number of values\n#\n# Copyright (c) 2001-2004 by Secret Labs AB\n# Copyright (c) 2001-2004 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom . import Image, ImageFile\nfrom ._util import isStringType\nimport operator\nimport functools\n\n\n#\n# helpers\n\ndef _border(border):\n    if isinstance(border, tuple):\n        if len(border) == 2:\n            left, top = right, bottom = border\n        elif len(border) == 4:\n            left, top, right, bottom = border\n    else:\n        left = top = right = bottom = border\n    return left, top, right, bottom\n\n\ndef _color(color, mode):\n    if isStringType(color):\n        from . import ImageColor\n        color = ImageColor.getcolor(color, mode)\n    return color\n\n\ndef _lut(image, lut):\n    if image.mode == \"P\":\n        # FIXME: apply to lookup table, not image data\n        raise NotImplementedError(\"mode P support coming soon\")\n    elif image.mode in (\"L\", \"RGB\"):\n        if image.mode == \"RGB\" and len(lut) == 256:\n            lut = lut + lut + lut\n        return image.point(lut)\n    else:\n        raise IOError(\"not supported for this image mode\")\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None):\n    \"\"\"\n    Maximize (normalize) image contrast. This function calculates a\n    histogram of the input image, removes **cutoff** percent of the\n    lightest and darkest pixels from the histogram, and remaps the image\n    so that the darkest pixel becomes black (0), and the lightest\n    becomes white (255).\n\n    :param image: The image to process.\n    :param cutoff: How many percent to cut off from the histogram.\n    :param ignore: The background pixel value (use None for no background).\n    :return: An image.\n    \"\"\"\n    histogram = image.histogram()\n    lut = []\n    for layer in range(0, len(histogram), 256):\n        h = histogram[layer:layer+256]\n        if ignore is not None:\n            # get rid of outliers\n            try:\n                h[ignore] = 0\n            except TypeError:\n                # assume sequence\n                for ix in ignore:\n                    h[ix] = 0\n        if cutoff:\n            # cut off pixels from both ends of the histogram\n            # get number of pixels\n            n = 0\n            for ix in range(256):\n                n = n + h[ix]\n            # remove cutoff% pixels from the low end\n            cut = n * cutoff // 100\n            for lo in range(256):\n                if cut > h[lo]:\n                    cut = cut - h[lo]\n                    h[lo] = 0\n                else:\n                    h[lo] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n            # remove cutoff% samples from the hi end\n            cut = n * cutoff // 100\n            for hi in range(255, -1, -1):\n                if cut > h[hi]:\n                    cut = cut - h[hi]\n                    h[hi] = 0\n                else:\n                    h[hi] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n        # find lowest/highest samples after preprocessing\n        for lo in range(256):\n            if h[lo]:\n                break\n        for hi in range(255, -1, -1):\n            if h[hi]:\n                break\n        if hi <= lo:\n            # don't bother\n            lut.extend(list(range(256)))\n        else:\n            scale = 255.0 / (hi - lo)\n            offset = -lo * scale\n            for ix in range(256):\n                ix = int(ix * scale + offset)\n                if ix < 0:\n                    ix = 0\n                elif ix > 255:\n                    ix = 255\n                lut.append(ix)\n    return _lut(image, lut)\n\n\ndef colorize(image, black, white, mid=None, blackpoint=0,\n             whitepoint=255, midpoint=127):\n    \"\"\"\n    Colorize grayscale image.\n    This function calculates a color wedge which maps all black pixels in\n    the source image to the first color and all white pixels to the\n    second color. If **mid** is specified, it uses three-color mapping.\n    The **black** and **white** arguments should be RGB tuples or color names;\n    optionally you can use three-color mapping by also specifying **mid**.\n    Mapping positions for any of the colors can be specified\n    (e.g. **blackpoint**), where these parameters are the integer\n    value corresponding to where the corresponding color should be mapped.\n    These parameters must have logical order, such that\n    **blackpoint** <= **midpoint** <= **whitepoint** (if **mid** is specified).\n\n    :param image: The image to colorize.\n    :param black: The color to use for black input pixels.\n    :param white: The color to use for white input pixels.\n    :param mid: The color to use for midtone input pixels.\n    :param blackpoint: an int value [0, 255] for the black mapping.\n    :param whitepoint: an int value [0, 255] for the white mapping.\n    :param midpoint: an int value [0, 255] for the midtone mapping.\n    :return: An image.\n    \"\"\"\n\n    # Initial asserts\n    assert image.mode == \"L\"\n    if mid is None:\n        assert 0 <= blackpoint <= whitepoint <= 255\n    else:\n        assert 0 <= blackpoint <= midpoint <= whitepoint <= 255\n\n    # Define colors from arguments\n    black = _color(black, \"RGB\")\n    white = _color(white, \"RGB\")\n    if mid is not None:\n        mid = _color(mid, \"RGB\")\n\n    # Empty lists for the mapping\n    red = []\n    green = []\n    blue = []\n\n    # Create the low-end values\n    for i in range(0, blackpoint):\n        red.append(black[0])\n        green.append(black[1])\n        blue.append(black[2])\n\n    # Create the mapping (2-color)\n    if mid is None:\n\n        range_map = range(0, whitepoint - blackpoint)\n\n        for i in range_map:\n            red.append(black[0] + i * (white[0] - black[0]) // len(range_map))\n            green.append(black[1] + i * (white[1] - black[1]) // len(range_map))\n            blue.append(black[2] + i * (white[2] - black[2]) // len(range_map))\n\n    # Create the mapping (3-color)\n    else:\n\n        range_map1 = range(0, midpoint - blackpoint)\n        range_map2 = range(0, whitepoint - midpoint)\n\n        for i in range_map1:\n            red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1))\n            green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1))\n            blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1))\n        for i in range_map2:\n            red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2))\n            green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2))\n            blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2))\n\n    # Create the high-end values\n    for i in range(0, 256 - whitepoint):\n        red.append(white[0])\n        green.append(white[1])\n        blue.append(white[2])\n\n    # Return converted image\n    image = image.convert(\"RGB\")\n    return _lut(image, red + green + blue)\n\n\ndef pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a sized and padded version of the image, expanded to fill the\n    requested aspect ratio and size.\n\n    :param image: The image to size and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: What resampling method to use. Default is\n                   :py:attr:`PIL.Image.NEAREST`.\n    :param color: The background color of the padded image.\n    :param centering: Control the position of the original image within the\n                      padded version.\n                          (0.5, 0.5) will keep the image centered\n                          (0, 0) will keep the image aligned to the top left\n                          (1, 1) will keep the image aligned to the bottom\n                          right\n    :return: An image.\n    \"\"\"\n\n    im_ratio = image.width / image.height\n    dest_ratio = float(size[0]) / size[1]\n\n    if im_ratio == dest_ratio:\n        out = image.resize(size, resample=method)\n    else:\n        out = Image.new(image.mode, size, color)\n        if im_ratio > dest_ratio:\n            new_height = int(image.height / image.width * size[0])\n            if new_height != size[1]:\n                image = image.resize((size[0], new_height), resample=method)\n\n            y = int((size[1] - new_height) * max(0, min(centering[1], 1)))\n            out.paste(image, (0, y))\n        else:\n            new_width = int(image.width / image.height * size[1])\n            if new_width != size[0]:\n                image = image.resize((new_width, size[1]), resample=method)\n\n            x = int((size[0] - new_width) * max(0, min(centering[0], 1)))\n            out.paste(image, (x, 0))\n    return out\n\n\ndef crop(image, border=0):\n    \"\"\"\n    Remove border from image.  The same amount of pixels are removed\n    from all four sides.  This function works on all image modes.\n\n    .. seealso:: :py:meth:`~PIL.Image.Image.crop`\n\n    :param image: The image to crop.\n    :param border: The number of pixels to remove.\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    return image.crop(\n        (left, top, image.size[0]-right, image.size[1]-bottom)\n        )\n\n\ndef scale(image, factor, resample=Image.NEAREST):\n    \"\"\"\n    Returns a rescaled image by a specific factor given in parameter.\n    A factor greater than 1 expands the image, between 0 and 1 contracts the\n    image.\n\n    :param image: The image to rescale.\n    :param factor: The expansion factor, as a float.\n    :param resample: An optional resampling filter. Same values possible as\n       in the PIL.Image.resize function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n    if factor == 1:\n        return image.copy()\n    elif factor <= 0:\n        raise ValueError(\"the factor must be greater than 0\")\n    else:\n        size = (int(round(factor * image.width)),\n                int(round(factor * image.height)))\n        return image.resize(size, resample)\n\n\ndef deform(image, deformer, resample=Image.BILINEAR):\n    \"\"\"\n    Deform the image.\n\n    :param image: The image to deform.\n    :param deformer: A deformer object.  Any object that implements a\n                    **getmesh** method can be used.\n    :param resample: An optional resampling filter. Same values possible as\n       in the PIL.Image.transform function.\n    :return: An image.\n    \"\"\"\n    return image.transform(\n        image.size, Image.MESH, deformer.getmesh(image), resample\n        )\n\n\ndef equalize(image, mask=None):\n    \"\"\"\n    Equalize the image histogram. This function applies a non-linear\n    mapping to the input image, in order to create a uniform\n    distribution of grayscale values in the output image.\n\n    :param image: The image to equalize.\n    :param mask: An optional mask.  If given, only the pixels selected by\n                 the mask are included in the analysis.\n    :return: An image.\n    \"\"\"\n    if image.mode == \"P\":\n        image = image.convert(\"RGB\")\n    h = image.histogram(mask)\n    lut = []\n    for b in range(0, len(h), 256):\n        histo = [_f for _f in h[b:b+256] if _f]\n        if len(histo) <= 1:\n            lut.extend(list(range(256)))\n        else:\n            step = (functools.reduce(operator.add, histo) - histo[-1]) // 255\n            if not step:\n                lut.extend(list(range(256)))\n            else:\n                n = step // 2\n                for i in range(256):\n                    lut.append(n // step)\n                    n = n + h[i+b]\n    return _lut(image, lut)\n\n\ndef expand(image, border=0, fill=0):\n    \"\"\"\n    Add border to the image\n\n    :param image: The image to expand.\n    :param border: Border width, in pixels.\n    :param fill: Pixel fill value (a color value).  Default is 0 (black).\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    width = left + image.size[0] + right\n    height = top + image.size[1] + bottom\n    out = Image.new(image.mode, (width, height), _color(fill, image.mode))\n    out.paste(image, (left, top))\n    return out\n\n\ndef fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a sized and cropped version of the image, cropped to the\n    requested aspect ratio and size.\n\n    This function was contributed by Kevin Cazabon.\n\n    :param image: The image to size and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: What resampling method to use. Default is\n                   :py:attr:`PIL.Image.NEAREST`.\n    :param bleed: Remove a border around the outside of the image from all\n                  four edges. The value is a decimal percentage (use 0.01 for\n                  one percent). The default value is 0 (no border).\n                  Cannot be greater than or equal to 0.5.\n    :param centering: Control the cropping position.  Use (0.5, 0.5) for\n                      center cropping (e.g. if cropping the width, take 50% off\n                      of the left side, and therefore 50% off the right side).\n                      (0.0, 0.0) will crop from the top left corner (i.e. if\n                      cropping the width, take all of the crop off of the right\n                      side, and if cropping the height, take all of it off the\n                      bottom).  (1.0, 0.0) will crop from the bottom left\n                      corner, etc. (i.e. if cropping the width, take all of the\n                      crop off the left side, and if cropping the height take\n                      none from the top, and therefore all off the bottom).\n    :return: An image.\n    \"\"\"\n\n    # by Kevin Cazabon, Feb 17/2000\n    # kevin@cazabon.com\n    # http://www.cazabon.com\n\n    # ensure centering is mutable\n    centering = list(centering)\n\n    if not 0.0 <= centering[0] <= 1.0:\n        centering[0] = 0.5\n    if not 0.0 <= centering[1] <= 1.0:\n        centering[1] = 0.5\n\n    if not 0.0 <= bleed < 0.5:\n        bleed = 0.0\n\n    # calculate the area to use for resizing and cropping, subtracting\n    # the 'bleed' around the edges\n\n    # number of pixels to trim off on Top and Bottom, Left and Right\n    bleed_pixels = (bleed * image.size[0], bleed * image.size[1])\n\n    live_size = (image.size[0] - bleed_pixels[0] * 2,\n                 image.size[1] - bleed_pixels[1] * 2)\n\n    # calculate the aspect ratio of the live_size\n    live_size_ratio = float(live_size[0]) / live_size[1]\n\n    # calculate the aspect ratio of the output image\n    output_ratio = float(size[0]) / size[1]\n\n    # figure out if the sides or top/bottom will be cropped off\n    if live_size_ratio >= output_ratio:\n        # live_size is wider than what's needed, crop the sides\n        crop_width = output_ratio * live_size[1]\n        crop_height = live_size[1]\n    else:\n        # live_size is taller than what's needed, crop the top and bottom\n        crop_width = live_size[0]\n        crop_height = live_size[0] / output_ratio\n\n    # make the crop\n    crop_left = bleed_pixels[0] + (live_size[0]-crop_width) * centering[0]\n    crop_top = bleed_pixels[1] + (live_size[1]-crop_height) * centering[1]\n\n    crop = (\n        crop_left, crop_top,\n        crop_left + crop_width, crop_top + crop_height\n    )\n\n    # resize the image and return it\n    return image.resize(size, method, box=crop)\n\n\ndef flip(image):\n    \"\"\"\n    Flip the image vertically (top to bottom).\n\n    :param image: The image to flip.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_TOP_BOTTOM)\n\n\ndef grayscale(image):\n    \"\"\"\n    Convert the image to grayscale.\n\n    :param image: The image to convert.\n    :return: An image.\n    \"\"\"\n    return image.convert(\"L\")\n\n\ndef invert(image):\n    \"\"\"\n    Invert (negate) the image.\n\n    :param image: The image to invert.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        lut.append(255-i)\n    return _lut(image, lut)\n\n\ndef mirror(image):\n    \"\"\"\n    Flip image horizontally (left to right).\n\n    :param image: The image to mirror.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_LEFT_RIGHT)\n\n\ndef posterize(image, bits):\n    \"\"\"\n    Reduce the number of bits for each color channel.\n\n    :param image: The image to posterize.\n    :param bits: The number of bits to keep for each channel (1-8).\n    :return: An image.\n    \"\"\"\n    lut = []\n    mask = ~(2**(8-bits)-1)\n    for i in range(256):\n        lut.append(i & mask)\n    return _lut(image, lut)\n\n\ndef solarize(image, threshold=128):\n    \"\"\"\n    Invert all pixel values above a threshold.\n\n    :param image: The image to solarize.\n    :param threshold: All pixels above this greyscale level are inverted.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        if i < threshold:\n            lut.append(i)\n        else:\n            lut.append(255-i)\n    return _lut(image, lut)\n\n\ndef exif_transpose(image):\n    \"\"\"\n    If an image has an EXIF Orientation tag, return a new image that is\n    transposed accordingly. Otherwise, return a copy of the image.\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    if isinstance(image, ImageFile.ImageFile):\n        exif = image.getexif()\n        if exif:\n            orientation = exif.get(0x0112)\n            method = {\n                2: Image.FLIP_LEFT_RIGHT,\n                3: Image.ROTATE_180,\n                4: Image.FLIP_TOP_BOTTOM,\n                5: Image.TRANSPOSE,\n                6: Image.ROTATE_270,\n                7: Image.TRANSVERSE,\n                8: Image.ROTATE_90\n            }.get(orientation)\n            if method is not None:\n                transposed_image = image.transpose(method)\n                del exif[0x0112]\n                transposed_image.info[\"exif\"] = exif.tobytes()\n                return transposed_image\n    return image.copy()\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `exif_transpose` Fails to Correctly Orient Images Using Generic `Image` Instances

**Description:**
When using the `exif_transpose` function on a standard `Image` instance, the image does not get properly transposed based on its EXIF orientation data. This results in incorrectly oriented images, which can lead to significant pixel discrepancies.

**Example Code:**
```python
from PIL import Image, ImageOps

# Open image as a generic Image instance
image = Image.open("Tests/images/hopper_orientation_6.jpg")

# Attempt to transpose based on EXIF data
transposed_image = ImageOps.exif_transpose(image)

# The transposed_image does not have the correct orientation
transposed_image.show()
```

**Expected Behavior:**
The `transposed_image` should be correctly rotated or flipped according to the EXIF orientation tag of the original image, resulting in the image being displayed with the intended orientation.

**Actual Behavior:**
The `transposed_image` retains the original orientation without applying the necessary rotation or flipping, leading to discrepancies in the image's appearance.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### src/PIL/ImageOps.py
#
# The Python Imaging Library.
# $Id$
#
# standard image operations
#
# History:
# 2001-10-20 fl   Created
# 2001-10-23 fl   Added autocontrast operator
# 2001-12-18 fl   Added Kevin's fit operator
# 2004-03-14 fl   Fixed potential division by zero in equalize
# 2005-05-05 fl   Fixed equalize for low number of values
#
# Copyright (c) 2001-2004 by Secret Labs AB
# Copyright (c) 2001-2004 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#

from . import Image, ImageFile
from ._util import isStringType
import operator
import functools


#
# helpers

def _border(border):
    if isinstance(border, tuple):
        if len(border) == 2:
            left, top = right, bottom = border
        elif len(border) == 4:
            left, top, right, bottom = border
    else:
        left = top = right = bottom = border
    return left, top, right, bottom


def _color(color, mode):
    if isStringType(color):
        from . import ImageColor
        color = ImageColor.getcolor(color, mode)
    return color


def _lut(image, lut):
    if image.mode == "P":
        # FIXME: apply to lookup table, not image data
        raise NotImplementedError("mode P support coming soon")
    elif image.mode in ("L", "RGB"):
        if image.mode == "RGB" and len(lut) == 256:
            lut = lut + lut + lut
        return image.point(lut)
    else:
        raise IOError("not supported for this image mode")

#
# actions


def autocontrast(image, cutoff=0, ignore=None):
    """
    Maximize (normalize) image contrast. This function calculates a
    histogram of the input image, removes **cutoff** percent of the
    lightest and darkest pixels from the histogram, and remaps the image
    so that the darkest pixel becomes black (0), and the lightest
    becomes white (255).

    :param image: The image to process.
    :param cutoff: How many percent to cut off from the histogram.
    :param ignore: The background pixel value (use None for no background).
    :return: An image.
    """
    histogram = image.histogram()
    lut = []
    for layer in range(0, len(histogram), 256):
        h = histogram[layer:layer+256]
        if ignore is not None:
            # get rid of outliers
            try:
                h[ignore] = 0
            except TypeError:
                # assume sequence
                for ix in ignore:
                    h[ix] = 0
        if cutoff:
            # cut off pixels from both ends of the histogram
            # get number of pixels
            n = 0
            for ix in range(256):
                n = n + h[ix]
            # remove cutoff% pixels from the low end
            cut = n * cutoff // 100
            for lo in range(256):
                if cut > h[lo]:
                    cut = cut - h[lo]
                    h[lo] = 0
                else:
                    h[lo] -= cut
                    cut = 0
                if cut <= 0:
                    break
            # remove cutoff% samples from the hi end
            cut = n * cutoff // 100
            for hi in range(255, -1, -1):
                if cut > h[hi]:
                    cut = cut - h[hi]
                    h[hi] = 0
                else:
                    h[hi] -= cut
                    cut = 0
                if cut <= 0:
                    break
        # find lowest/highest samples after preprocessing
        for lo in range(256):
            if h[lo]:
                break
        for hi in range(255, -1, -1):
            if h[hi]:
                break
        if hi <= lo:
            # don't bother
            lut.extend(list(range(256)))
        else:
            scale = 255.0 / (hi - lo)
            offset = -lo * scale
            for ix in range(256):
                ix = int(ix * scale + offset)
                if ix < 0:
                    ix = 0
                elif ix > 255:
                    ix = 255
                lut.append(ix)
    return _lut(image, lut)


def colorize(image, black, white, mid=None, blackpoint=0,
             whitepoint=255, midpoint=127):
    """
    Colorize grayscale image.
    This function calculates a color wedge which maps all black pixels in
    the source image to the first color and all white pixels to the
    second color. If **mid** is specified, it uses three-color mapping.
    The **black** and **white** arguments should be RGB tuples or color names;
    optionally you can use three-color mapping by also specifying **mid**.
    Mapping positions for any of the colors can be specified
    (e.g. **blackpoint**), where these parameters are the integer
    value corresponding to where the corresponding color should be mapped.
    These parameters must have logical order, such that
    **blackpoint** <= **midpoint** <= **whitepoint** (if **mid** is specified).

    :param image: The image to colorize.
    :param black: The color to use for black input pixels.
    :param white: The color to use for white input pixels.
    :param mid: The color to use for midtone input pixels.
    :param blackpoint: an int value [0, 255] for the black mapping.
    :param whitepoint: an int value [0, 255] for the white mapping.
    :param midpoint: an int value [0, 255] for the midtone mapping.
    :return: An image.
    """

    # Initial asserts
    assert image.mode == "L"
    if mid is None:
        assert 0 <= blackpoint <= whitepoint <= 255
    else:
        assert 0 <= blackpoint <= midpoint <= whitepoint <= 255

    # Define colors from arguments
    black = _color(black, "RGB")
    white = _color(white, "RGB")
    if mid is not None:
        mid = _color(mid, "RGB")

    # Empty lists for the mapping
    red = []
    green = []
    blue = []

    # Create the low-end values
    for i in range(0, blackpoint):
        red.append(black[0])
        green.append(black[1])
        blue.append(black[2])

    # Create the mapping (2-color)
    if mid is None:

        range_map = range(0, whitepoint - blackpoint)

        for i in range_map:
            red.append(black[0] + i * (white[0] - black[0]) // len(range_map))
            green.append(black[1] + i * (white[1] - black[1]) // len(range_map))
            blue.append(black[2] + i * (white[2] - black[2]) // len(range_map))

    # Create the mapping (3-color)
    else:

        range_map1 = range(0, midpoint - blackpoint)
        range_map2 = range(0, whitepoint - midpoint)

        for i in range_map1:
            red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1))
            green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1))
            blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1))
        for i in range_map2:
            red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2))
            green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2))
            blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2))

    # Create the high-end values
    for i in range(0, 256 - whitepoint):
        red.append(white[0])
        green.append(white[1])
        blue.append(white[2])

    # Return converted image
    image = image.convert("RGB")
    return _lut(image, red + green + blue)


def pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)):
    """
    Returns a sized and padded version of the image, expanded to fill the
    requested aspect ratio and size.

    :param image: The image to size and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: What resampling method to use. Default is
                   :py:attr:`PIL.Image.NEAREST`.
    :param color: The background color of the padded image.
    :param centering: Control the position of the original image within the
                      padded version.
                          (0.5, 0.5) will keep the image centered
                          (0, 0) will keep the image aligned to the top left
                          (1, 1) will keep the image aligned to the bottom
                          right
    :return: An image.
    """

    im_ratio = image.width / image.height
    dest_ratio = float(size[0]) / size[1]

    if im_ratio == dest_ratio:
        out = image.resize(size, resample=method)
    else:
        out = Image.new(image.mode, size, color)
        if im_ratio > dest_ratio:
            new_height = int(image.height / image.width * size[0])
            if new_height != size[1]:
                image = image.resize((size[0], new_height), resample=method)

            y = int((size[1] - new_height) * max(0, min(centering[1], 1)))
            out.paste(image, (0, y))
        else:
            new_width = int(image.width / image.height * size[1])
            if new_width != size[0]:
                image = image.resize((new_width, size[1]), resample=method)

            x = int((size[0] - new_width) * max(0, min(centering[0], 1)))
            out.paste(image, (x, 0))
    return out


def crop(image, border=0):
    """
    Remove border from image.  The same amount of pixels are removed
    from all four sides.  This function works on all image modes.

    .. seealso:: :py:meth:`~PIL.Image.Image.crop`

    :param image: The image to crop.
    :param border: The number of pixels to remove.
    :return: An image.
    """
    left, top, right, bottom = _border(border)
    return image.crop(
        (left, top, image.size[0]-right, image.size[1]-bottom)
        )


def scale(image, factor, resample=Image.NEAREST):
    """
    Returns a rescaled image by a specific factor given in parameter.
    A factor greater than 1 expands the image, between 0 and 1 contracts the
    image.

    :param image: The image to rescale.
    :param factor: The expansion factor, as a float.
    :param resample: An optional resampling filter. Same values possible as
       in the PIL.Image.resize function.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """
    if factor == 1:
        return image.copy()
    elif factor <= 0:
        raise ValueError("the factor must be greater than 0")
    else:
        size = (int(round(factor * image.width)),
                int(round(factor * image.height)))
        return image.resize(size, resample)


def deform(image, deformer, resample=Image.BILINEAR):
    """
    Deform the image.

    :param image: The image to deform.
    :param deformer: A deformer object.  Any object that implements a
                    **getmesh** method can be used.
    :param resample: An optional resampling filter. Same values possible as
       in the PIL.Image.transform function.
    :return: An image.
    """
    return image.transform(
        image.size, Image.MESH, deformer.getmesh(image), resample
        )


def equalize(image, mask=None):
    """
    Equalize the image histogram. This function applies a non-linear
    mapping to the input image, in order to create a uniform
    distribution of grayscale values in the output image.

    :param image: The image to equalize.
    :param mask: An optional mask.  If given, only the pixels selected by
                 the mask are included in the analysis.
    :return: An image.
    """
    if image.mode == "P":
        image = image.convert("RGB")
    h = image.histogram(mask)
    lut = []
    for b in range(0, len(h), 256):
        histo = [_f for _f in h[b:b+256] if _f]
        if len(histo) <= 1:
            lut.extend(list(range(256)))
        else:
            step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
            if not step:
                lut.extend(list(range(256)))
            else:
                n = step // 2
                for i in range(256):
                    lut.append(n // step)
                    n = n + h[i+b]
    return _lut(image, lut)


def expand(image, border=0, fill=0):
    """
    Add border to the image

    :param image: The image to expand.
    :param border: Border width, in pixels.
    :param fill: Pixel fill value (a color value).  Default is 0 (black).
    :return: An image.
    """
    left, top, right, bottom = _border(border)
    width = left + image.size[0] + right
    height = top + image.size[1] + bottom
    out = Image.new(image.mode, (width, height), _color(fill, image.mode))
    out.paste(image, (left, top))
    return out


def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
    """
    Returns a sized and cropped version of the image, cropped to the
    requested aspect ratio and size.

    This function was contributed by Kevin Cazabon.

    :param image: The image to size and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: What resampling method to use. Default is
                   :py:attr:`PIL.Image.NEAREST`.
    :param bleed: Remove a border around the outside of the image from all
                  four edges. The value is a decimal percentage (use 0.01 for
                  one percent). The default value is 0 (no border).
                  Cannot be greater than or equal to 0.5.
    :param centering: Control the cropping position.  Use (0.5, 0.5) for
                      center cropping (e.g. if cropping the width, take 50% off
                      of the left side, and therefore 50% off the right side).
                      (0.0, 0.0) will crop from the top left corner (i.e. if
                      cropping the width, take all of the crop off of the right
                      side, and if cropping the height, take all of it off the
                      bottom).  (1.0, 0.0) will crop from the bottom left
                      corner, etc. (i.e. if cropping the width, take all of the
                      crop off the left side, and if cropping the height take
                      none from the top, and therefore all off the bottom).
    :return: An image.
    """

    # by Kevin Cazabon, Feb 17/2000
    # kevin@cazabon.com
    # http://www.cazabon.com

    # ensure centering is mutable
    centering = list(centering)

    if not 0.0 <= centering[0] <= 1.0:
        centering[0] = 0.5
    if not 0.0 <= centering[1] <= 1.0:
        centering[1] = 0.5

    if not 0.0 <= bleed < 0.5:
        bleed = 0.0

    # calculate the area to use for resizing and cropping, subtracting
    # the 'bleed' around the edges

    # number of pixels to trim off on Top and Bottom, Left and Right
    bleed_pixels = (bleed * image.size[0], bleed * image.size[1])

    live_size = (image.size[0] - bleed_pixels[0] * 2,
                 image.size[1] - bleed_pixels[1] * 2)

    # calculate the aspect ratio of the live_size
    live_size_ratio = float(live_size[0]) / live_size[1]

    # calculate the aspect ratio of the output image
    output_ratio = float(size[0]) / size[1]

    # figure out if the sides or top/bottom will be cropped off
    if live_size_ratio >= output_ratio:
        # live_size is wider than what's needed, crop the sides
        crop_width = output_ratio * live_size[1]
        crop_height = live_size[1]
    else:
        # live_size is taller than what's needed, crop the top and bottom
        crop_width = live_size[0]
        crop_height = live_size[0] / output_ratio

    # make the crop
    crop_left = bleed_pixels[0] + (live_size[0]-crop_width) * centering[0]
    crop_top = bleed_pixels[1] + (live_size[1]-crop_height) * centering[1]

    crop = (
        crop_left, crop_top,
        crop_left + crop_width, crop_top + crop_height
    )

    # resize the image and return it
    return image.resize(size, method, box=crop)


def flip(image):
    """
    Flip the image vertically (top to bottom).

    :param image: The image to flip.
    :return: An image.
    """
    return image.transpose(Image.FLIP_TOP_BOTTOM)


def grayscale(image):
    """
    Convert the image to grayscale.

    :param image: The image to convert.
    :return: An image.
    """
    return image.convert("L")


def invert(image):
    """
    Invert (negate) the image.

    :param image: The image to invert.
    :return: An image.
    """
    lut = []
    for i in range(256):
        lut.append(255-i)
    return _lut(image, lut)


def mirror(image):
    """
    Flip image horizontally (left to right).

    :param image: The image to mirror.
    :return: An image.
    """
    return image.transpose(Image.FLIP_LEFT_RIGHT)


def posterize(image, bits):
    """
    Reduce the number of bits for each color channel.

    :param image: The image to posterize.
    :param bits: The number of bits to keep for each channel (1-8).
    :return: An image.
    """
    lut = []
    mask = ~(2**(8-bits)-1)
    for i in range(256):
        lut.append(i & mask)
    return _lut(image, lut)


def solarize(image, threshold=128):
    """
    Invert all pixel values above a threshold.

    :param image: The image to solarize.
    :param threshold: All pixels above this greyscale level are inverted.
    :return: An image.
    """
    lut = []
    for i in range(256):
        if i < threshold:
            lut.append(i)
        else:
            lut.append(255-i)
    return _lut(image, lut)


def exif_transpose(image):
    """
    If an image has an EXIF Orientation tag, return a new image that is
    transposed accordingly. Otherwise, return a copy of the image.

    :param image: The image to transpose.
    :return: An image.
    """
    if isinstance(image, ImageFile.ImageFile):
        exif = image.getexif()
        if exif:
            orientation = exif.get(0x0112)
            method = {
                2: Image.FLIP_LEFT_RIGHT,
                3: Image.ROTATE_180,
                4: Image.FLIP_TOP_BOTTOM,
                5: Image.TRANSPOSE,
                6: Image.ROTATE_270,
                7: Image.TRANSVERSE,
                8: Image.ROTATE_90
            }.get(orientation)
            if method is not None:
                transposed_image = image.transpose(method)
                del exif[0x0112]
                transposed_image.info["exif"] = exif.tobytes()
                return transposed_image
    return image.copy()

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user