{
    "file_diffs": [
        {
            "old_file_content": "import pytest\n\nfrom PIL import Image, ImageDraw, ImageOps, ImageStat, features\n\nfrom .helper import (\n    assert_image_equal,\n    assert_image_similar,\n    assert_image_similar_tofile,\n    assert_tuple_approx_equal,\n    hopper,\n)\n\n\nclass Deformer:\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\ndeformer = Deformer()\n\n\ndef test_sanity():\n\n    ImageOps.autocontrast(hopper(\"L\"))\n    ImageOps.autocontrast(hopper(\"RGB\"))\n\n    ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n    ImageOps.autocontrast(hopper(\"L\"), cutoff=(2, 10))\n    ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n    ImageOps.autocontrast(hopper(\"L\"), mask=hopper(\"L\"))\n    ImageOps.autocontrast(hopper(\"L\"), preserve_tone=True)\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.contain(hopper(\"L\"), (128, 128))\n    ImageOps.contain(hopper(\"RGB\"), (128, 128))\n\n    ImageOps.crop(hopper(\"L\"), 1)\n    ImageOps.crop(hopper(\"RGB\"), 1)\n\n    ImageOps.deform(hopper(\"L\"), deformer)\n    ImageOps.deform(hopper(\"RGB\"), 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(\"1\"))\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\ndef test_1pxfit():\n    # Division by zero in equalize if image is 1 pixel high\n    newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n    assert newimg.size == (35, 35)\n\n    newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n    assert newimg.size == (35, 35)\n\n    newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n    assert newimg.size == (35, 35)\n\n\ndef test_fit_same_ratio():\n    # The ratio for this image is 1000.0 / 755 = 1.3245033112582782\n    # If the ratios are not acknowledged to be the same,\n    # and Pillow attempts to adjust the width to\n    # 1.3245033112582782 * 755 = 1000.0000000000001\n    # then centering this greater width causes a negative x offset when cropping\n    with Image.new(\"RGB\", (1000, 755)) as im:\n        new_im = ImageOps.fit(im, (1000, 755))\n        assert new_im.size == (1000, 755)\n\n\n@pytest.mark.parametrize(\"new_size\", ((256, 256), (512, 256), (256, 512)))\ndef test_contain(new_size):\n    im = hopper()\n    new_im = ImageOps.contain(im, new_size)\n    assert new_im.size == (256, 256)\n\n\ndef test_pad():\n    # Same ratio\n    im = hopper()\n    new_size = (im.width * 2, im.height * 2)\n    new_im = ImageOps.pad(im, new_size)\n    assert 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, color=color, centering=centering)\n            assert new_im.size == new_size\n\n            assert_image_similar_tofile(\n                new_im, \"Tests/images/imageops_pad_\" + label + \"_\" + str(i) + \".jpg\", 6\n            )\n\n\ndef test_pil163():\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\ndef test_scale():\n    # Test the scaling function\n    i = hopper(\"L\").resize((50, 50))\n\n    with pytest.raises(ValueError):\n        ImageOps.scale(i, -1)\n\n    newimg = ImageOps.scale(i, 1)\n    assert newimg.size == (50, 50)\n\n    newimg = ImageOps.scale(i, 2)\n    assert newimg.size == (100, 100)\n\n    newimg = ImageOps.scale(i, 0.5)\n    assert newimg.size == (25, 25)\n\n\n@pytest.mark.parametrize(\"border\", (10, (1, 2, 3, 4)))\ndef test_expand_palette(border):\n    with Image.open(\"Tests/images/p_16.tga\") as im:\n        im_expanded = ImageOps.expand(im, border, (255, 0, 0))\n\n        if isinstance(border, int):\n            left = top = right = bottom = border\n        else:\n            left, top, right, bottom = border\n        px = im_expanded.convert(\"RGB\").load()\n        for x in range(im_expanded.width):\n            for b in range(top):\n                assert px[x, b] == (255, 0, 0)\n            for b in range(bottom):\n                assert px[x, im_expanded.height - 1 - b] == (255, 0, 0)\n        for y in range(im_expanded.height):\n            for b in range(left):\n                assert px[b, y] == (255, 0, 0)\n            for b in range(right):\n                assert px[im_expanded.width - 1 - b, y] == (255, 0, 0)\n\n        im_cropped = im_expanded.crop(\n            (left, top, im_expanded.width - right, im_expanded.height - bottom)\n        )\n        assert_image_equal(im_cropped, im)\n\n\ndef test_colorize_2color():\n    # Test the colorizing function with 2-color functionality\n\n    # Open test image (256px by 10px, black to white)\n    with Image.open(\"Tests/images/bw_gradient.png\") as im:\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    assert_tuple_approx_equal(\n        im_test.getpixel(left),\n        (255, 0, 0),\n        threshold=1,\n        msg=\"black test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(middle),\n        (127, 63, 0),\n        threshold=1,\n        msg=\"mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right),\n        (0, 127, 0),\n        threshold=1,\n        msg=\"white test pixel incorrect\",\n    )\n\n\ndef test_colorize_2color_offset():\n    # Test the colorizing function with 2-color functionality and offset\n\n    # Open test image (256px by 10px, black to white)\n    with Image.open(\"Tests/images/bw_gradient.png\") as im:\n        im = im.convert(\"L\")\n\n    # Create image with original 2-color functionality with offsets\n    im_test = ImageOps.colorize(\n        im, black=\"red\", white=\"green\", blackpoint=50, whitepoint=100\n    )\n\n    # Test output image (2-color) with offsets\n    left = (25, 1)\n    middle = (75, 1)\n    right = (125, 1)\n    assert_tuple_approx_equal(\n        im_test.getpixel(left),\n        (255, 0, 0),\n        threshold=1,\n        msg=\"black test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(middle),\n        (127, 63, 0),\n        threshold=1,\n        msg=\"mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right),\n        (0, 127, 0),\n        threshold=1,\n        msg=\"white test pixel incorrect\",\n    )\n\n\ndef test_colorize_3color_offset():\n    # Test the colorizing function with 3-color functionality and offset\n\n    # Open test image (256px by 10px, black to white)\n    with Image.open(\"Tests/images/bw_gradient.png\") as im:\n        im = im.convert(\"L\")\n\n    # Create image with new three color functionality with offsets\n    im_test = ImageOps.colorize(\n        im,\n        black=\"red\",\n        white=\"green\",\n        mid=\"blue\",\n        blackpoint=50,\n        whitepoint=200,\n        midpoint=100,\n    )\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    assert_tuple_approx_equal(\n        im_test.getpixel(left),\n        (255, 0, 0),\n        threshold=1,\n        msg=\"black test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(left_middle),\n        (127, 0, 127),\n        threshold=1,\n        msg=\"low-mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(middle), (0, 0, 255), threshold=1, msg=\"mid incorrect\"\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right_middle),\n        (0, 63, 127),\n        threshold=1,\n        msg=\"high-mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right),\n        (0, 127, 0),\n        threshold=1,\n        msg=\"white test pixel incorrect\",\n    )\n\n\ndef test_exif_transpose():\n    exts = [\".jpg\"]\n    if features.check(\"webp\") and features.check(\"webp_anim\"):\n        exts.append(\".webp\")\n    for ext in exts:\n        with Image.open(\"Tests/images/hopper\" + ext) as base_im:\n\n            def check(orientation_im):\n                for im in [\n                    orientation_im,\n                    orientation_im.copy(),\n                ]:  # ImageFile  # Image\n                    if orientation_im is base_im:\n                        assert \"exif\" not in im.info\n                    else:\n                        original_exif = im.info[\"exif\"]\n                    transposed_im = ImageOps.exif_transpose(im)\n                    assert_image_similar(base_im, transposed_im, 17)\n                    if orientation_im is base_im:\n                        assert \"exif\" not in im.info\n                    else:\n                        assert transposed_im.info[\"exif\"] != original_exif\n\n                        assert 0x0112 in im.getexif()\n                        assert 0x0112 not in transposed_im.getexif()\n\n                    # Repeat the operation to test that it does not keep transposing\n                    transposed_im2 = ImageOps.exif_transpose(transposed_im)\n                    assert_image_equal(transposed_im2, transposed_im)\n\n            check(base_im)\n            for i in range(2, 9):\n                with Image.open(\n                    \"Tests/images/hopper_orientation_\" + str(i) + ext\n                ) as orientation_im:\n                    check(orientation_im)\n\n    # Orientation from \"XML:com.adobe.xmp\" info key\n    for suffix in (\"\", \"_exiftool\"):\n        with Image.open(\"Tests/images/xmp_tags_orientation\" + suffix + \".png\") as im:\n            assert im.getexif()[0x0112] == 3\n\n            transposed_im = ImageOps.exif_transpose(im)\n            assert 0x0112 not in transposed_im.getexif()\n\n            transposed_im._reload_exif()\n            assert 0x0112 not in transposed_im.getexif()\n\n    # Orientation from \"Raw profile type exif\" info key\n    # This test image has been manually hexedited from exif_imagemagick.png\n    # to have a different orientation\n    with Image.open(\"Tests/images/exif_imagemagick_orientation.png\") as im:\n        assert im.getexif()[0x0112] == 3\n\n        transposed_im = ImageOps.exif_transpose(im)\n        assert 0x0112 not in transposed_im.getexif()\n\n    # Orientation set directly on Image.Exif\n    im = hopper()\n    im.getexif()[0x0112] = 3\n    transposed_im = ImageOps.exif_transpose(im)\n    assert 0x0112 not in transposed_im.getexif()\n\n\ndef test_autocontrast_cutoff():\n    # Test the cutoff argument of autocontrast\n    with Image.open(\"Tests/images/bw_gradient.png\") as img:\n\n        def autocontrast(cutoff):\n            return ImageOps.autocontrast(img, cutoff).histogram()\n\n        assert autocontrast(10) == autocontrast((10, 10))\n        assert autocontrast(10) != autocontrast((1, 10))\n\n\ndef test_autocontrast_mask_toy_input():\n    # Test the mask argument of autocontrast\n    with Image.open(\"Tests/images/bw_gradient.png\") as img:\n\n        rect_mask = Image.new(\"L\", img.size, 0)\n        draw = ImageDraw.Draw(rect_mask)\n        x0 = img.size[0] // 4\n        y0 = img.size[1] // 4\n        x1 = 3 * img.size[0] // 4\n        y1 = 3 * img.size[1] // 4\n        draw.rectangle((x0, y0, x1, y1), fill=255)\n\n        result = ImageOps.autocontrast(img, mask=rect_mask)\n        result_nomask = ImageOps.autocontrast(img)\n\n        assert result != result_nomask\n        assert ImageStat.Stat(result, mask=rect_mask).median == [127]\n        assert ImageStat.Stat(result_nomask).median == [128]\n\n\ndef test_autocontrast_mask_real_input():\n    # Test the autocontrast with a rectangular mask\n    with Image.open(\"Tests/images/iptc.jpg\") as img:\n\n        rect_mask = Image.new(\"L\", img.size, 0)\n        draw = ImageDraw.Draw(rect_mask)\n        x0, y0 = img.size[0] // 2, img.size[1] // 2\n        x1, y1 = img.size[0] - 40, img.size[1]\n        draw.rectangle((x0, y0, x1, y1), fill=255)\n\n        result = ImageOps.autocontrast(img, mask=rect_mask)\n        result_nomask = ImageOps.autocontrast(img)\n\n        assert result_nomask != result\n        assert_tuple_approx_equal(\n            ImageStat.Stat(result, mask=rect_mask).median,\n            [195, 202, 184],\n            threshold=2,\n            msg=\"autocontrast with mask pixel incorrect\",\n        )\n        assert_tuple_approx_equal(\n            ImageStat.Stat(result_nomask).median,\n            [119, 106, 79],\n            threshold=2,\n            msg=\"autocontrast without mask pixel incorrect\",\n        )\n\n\ndef test_autocontrast_preserve_tone():\n    def autocontrast(mode, preserve_tone):\n        im = hopper(mode)\n        return ImageOps.autocontrast(im, preserve_tone=preserve_tone).histogram()\n\n    assert autocontrast(\"RGB\", True) != autocontrast(\"RGB\", False)\n    assert autocontrast(\"L\", True) == autocontrast(\"L\", False)\n\n\ndef test_autocontrast_preserve_gradient():\n    gradient = Image.linear_gradient(\"L\")\n\n    # test with a grayscale gradient that extends to 0,255.\n    # Should be a noop.\n    out = ImageOps.autocontrast(gradient, cutoff=0, preserve_tone=True)\n\n    assert_image_equal(gradient, out)\n\n    # cutoff the top and bottom\n    # autocontrast should make the first and last histogram entries equal\n    # and, with rounding, should be 10% of the image pixels\n    out = ImageOps.autocontrast(gradient, cutoff=10, preserve_tone=True)\n    hist = out.histogram()\n    assert hist[0] == hist[-1]\n    assert hist[-1] == 256 * round(256 * 0.10)\n\n    # in rgb\n    img = gradient.convert(\"RGB\")\n    out = ImageOps.autocontrast(img, cutoff=0, preserve_tone=True)\n    assert_image_equal(img, out)\n\n\n@pytest.mark.parametrize(\n    \"color\", ((255, 255, 255), (127, 255, 0), (127, 127, 127), (0, 0, 0))\n)\ndef test_autocontrast_preserve_one_color(color):\n    img = Image.new(\"RGB\", (10, 10), color)\n\n    # single color images shouldn't change\n    out = ImageOps.autocontrast(img, cutoff=0, preserve_tone=True)\n    assert_image_equal(img, out)  # single color, no cutoff\n\n    # even if there is a cutoff\n    out = ImageOps.autocontrast(\n        img, cutoff=10, preserve_tone=True\n    )  # single color 10 cutoff\n    assert_image_equal(img, out)\n",
            "new_file_content": "import pytest\n\nfrom PIL import Image, ImageDraw, ImageOps, ImageStat, features\n\nfrom .helper import (\n    assert_image_equal,\n    assert_image_similar,\n    assert_image_similar_tofile,\n    assert_tuple_approx_equal,\n    hopper,\n)\n\n\nclass Deformer:\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\ndeformer = Deformer()\n\n\ndef test_sanity():\n\n    ImageOps.autocontrast(hopper(\"L\"))\n    ImageOps.autocontrast(hopper(\"RGB\"))\n\n    ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n    ImageOps.autocontrast(hopper(\"L\"), cutoff=(2, 10))\n    ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n    ImageOps.autocontrast(hopper(\"L\"), mask=hopper(\"L\"))\n    ImageOps.autocontrast(hopper(\"L\"), preserve_tone=True)\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.contain(hopper(\"L\"), (128, 128))\n    ImageOps.contain(hopper(\"RGB\"), (128, 128))\n\n    ImageOps.crop(hopper(\"L\"), 1)\n    ImageOps.crop(hopper(\"RGB\"), 1)\n\n    ImageOps.deform(hopper(\"L\"), deformer)\n    ImageOps.deform(hopper(\"RGB\"), 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(\"1\"))\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\ndef test_1pxfit():\n    # Division by zero in equalize if image is 1 pixel high\n    newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n    assert newimg.size == (35, 35)\n\n    newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n    assert newimg.size == (35, 35)\n\n    newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n    assert newimg.size == (35, 35)\n\n\ndef test_fit_same_ratio():\n    # The ratio for this image is 1000.0 / 755 = 1.3245033112582782\n    # If the ratios are not acknowledged to be the same,\n    # and Pillow attempts to adjust the width to\n    # 1.3245033112582782 * 755 = 1000.0000000000001\n    # then centering this greater width causes a negative x offset when cropping\n    with Image.new(\"RGB\", (1000, 755)) as im:\n        new_im = ImageOps.fit(im, (1000, 755))\n        assert new_im.size == (1000, 755)\n\n\n@pytest.mark.parametrize(\"new_size\", ((256, 256), (512, 256), (256, 512)))\ndef test_contain(new_size):\n    im = hopper()\n    new_im = ImageOps.contain(im, new_size)\n    assert new_im.size == (256, 256)\n\n\ndef test_contain_round():\n    im = Image.new(\"1\", (43, 63), 1)\n    new_im = ImageOps.contain(im, (5, 7))\n    assert new_im.width == 5\n\n    im = Image.new(\"1\", (63, 43), 1)\n    new_im = ImageOps.contain(im, (7, 5))\n    assert new_im.height == 5\n\n\ndef test_pad():\n    # Same ratio\n    im = hopper()\n    new_size = (im.width * 2, im.height * 2)\n    new_im = ImageOps.pad(im, new_size)\n    assert 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, color=color, centering=centering)\n            assert new_im.size == new_size\n\n            assert_image_similar_tofile(\n                new_im, \"Tests/images/imageops_pad_\" + label + \"_\" + str(i) + \".jpg\", 6\n            )\n\n\ndef test_pad_round():\n    im = Image.new(\"1\", (1, 1), 1)\n    new_im = ImageOps.pad(im, (4, 1))\n    assert new_im.load()[2, 0] == 1\n\n    new_im = ImageOps.pad(im, (1, 4))\n    assert new_im.load()[0, 2] == 1\n\n\ndef test_pil163():\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\ndef test_scale():\n    # Test the scaling function\n    i = hopper(\"L\").resize((50, 50))\n\n    with pytest.raises(ValueError):\n        ImageOps.scale(i, -1)\n\n    newimg = ImageOps.scale(i, 1)\n    assert newimg.size == (50, 50)\n\n    newimg = ImageOps.scale(i, 2)\n    assert newimg.size == (100, 100)\n\n    newimg = ImageOps.scale(i, 0.5)\n    assert newimg.size == (25, 25)\n\n\n@pytest.mark.parametrize(\"border\", (10, (1, 2, 3, 4)))\ndef test_expand_palette(border):\n    with Image.open(\"Tests/images/p_16.tga\") as im:\n        im_expanded = ImageOps.expand(im, border, (255, 0, 0))\n\n        if isinstance(border, int):\n            left = top = right = bottom = border\n        else:\n            left, top, right, bottom = border\n        px = im_expanded.convert(\"RGB\").load()\n        for x in range(im_expanded.width):\n            for b in range(top):\n                assert px[x, b] == (255, 0, 0)\n            for b in range(bottom):\n                assert px[x, im_expanded.height - 1 - b] == (255, 0, 0)\n        for y in range(im_expanded.height):\n            for b in range(left):\n                assert px[b, y] == (255, 0, 0)\n            for b in range(right):\n                assert px[im_expanded.width - 1 - b, y] == (255, 0, 0)\n\n        im_cropped = im_expanded.crop(\n            (left, top, im_expanded.width - right, im_expanded.height - bottom)\n        )\n        assert_image_equal(im_cropped, im)\n\n\ndef test_colorize_2color():\n    # Test the colorizing function with 2-color functionality\n\n    # Open test image (256px by 10px, black to white)\n    with Image.open(\"Tests/images/bw_gradient.png\") as im:\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    assert_tuple_approx_equal(\n        im_test.getpixel(left),\n        (255, 0, 0),\n        threshold=1,\n        msg=\"black test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(middle),\n        (127, 63, 0),\n        threshold=1,\n        msg=\"mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right),\n        (0, 127, 0),\n        threshold=1,\n        msg=\"white test pixel incorrect\",\n    )\n\n\ndef test_colorize_2color_offset():\n    # Test the colorizing function with 2-color functionality and offset\n\n    # Open test image (256px by 10px, black to white)\n    with Image.open(\"Tests/images/bw_gradient.png\") as im:\n        im = im.convert(\"L\")\n\n    # Create image with original 2-color functionality with offsets\n    im_test = ImageOps.colorize(\n        im, black=\"red\", white=\"green\", blackpoint=50, whitepoint=100\n    )\n\n    # Test output image (2-color) with offsets\n    left = (25, 1)\n    middle = (75, 1)\n    right = (125, 1)\n    assert_tuple_approx_equal(\n        im_test.getpixel(left),\n        (255, 0, 0),\n        threshold=1,\n        msg=\"black test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(middle),\n        (127, 63, 0),\n        threshold=1,\n        msg=\"mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right),\n        (0, 127, 0),\n        threshold=1,\n        msg=\"white test pixel incorrect\",\n    )\n\n\ndef test_colorize_3color_offset():\n    # Test the colorizing function with 3-color functionality and offset\n\n    # Open test image (256px by 10px, black to white)\n    with Image.open(\"Tests/images/bw_gradient.png\") as im:\n        im = im.convert(\"L\")\n\n    # Create image with new three color functionality with offsets\n    im_test = ImageOps.colorize(\n        im,\n        black=\"red\",\n        white=\"green\",\n        mid=\"blue\",\n        blackpoint=50,\n        whitepoint=200,\n        midpoint=100,\n    )\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    assert_tuple_approx_equal(\n        im_test.getpixel(left),\n        (255, 0, 0),\n        threshold=1,\n        msg=\"black test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(left_middle),\n        (127, 0, 127),\n        threshold=1,\n        msg=\"low-mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(middle), (0, 0, 255), threshold=1, msg=\"mid incorrect\"\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right_middle),\n        (0, 63, 127),\n        threshold=1,\n        msg=\"high-mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right),\n        (0, 127, 0),\n        threshold=1,\n        msg=\"white test pixel incorrect\",\n    )\n\n\ndef test_exif_transpose():\n    exts = [\".jpg\"]\n    if features.check(\"webp\") and features.check(\"webp_anim\"):\n        exts.append(\".webp\")\n    for ext in exts:\n        with Image.open(\"Tests/images/hopper\" + ext) as base_im:\n\n            def check(orientation_im):\n                for im in [\n                    orientation_im,\n                    orientation_im.copy(),\n                ]:  # ImageFile  # Image\n                    if orientation_im is base_im:\n                        assert \"exif\" not in im.info\n                    else:\n                        original_exif = im.info[\"exif\"]\n                    transposed_im = ImageOps.exif_transpose(im)\n                    assert_image_similar(base_im, transposed_im, 17)\n                    if orientation_im is base_im:\n                        assert \"exif\" not in im.info\n                    else:\n                        assert transposed_im.info[\"exif\"] != original_exif\n\n                        assert 0x0112 in im.getexif()\n                        assert 0x0112 not in transposed_im.getexif()\n\n                    # Repeat the operation to test that it does not keep transposing\n                    transposed_im2 = ImageOps.exif_transpose(transposed_im)\n                    assert_image_equal(transposed_im2, transposed_im)\n\n            check(base_im)\n            for i in range(2, 9):\n                with Image.open(\n                    \"Tests/images/hopper_orientation_\" + str(i) + ext\n                ) as orientation_im:\n                    check(orientation_im)\n\n    # Orientation from \"XML:com.adobe.xmp\" info key\n    for suffix in (\"\", \"_exiftool\"):\n        with Image.open(\"Tests/images/xmp_tags_orientation\" + suffix + \".png\") as im:\n            assert im.getexif()[0x0112] == 3\n\n            transposed_im = ImageOps.exif_transpose(im)\n            assert 0x0112 not in transposed_im.getexif()\n\n            transposed_im._reload_exif()\n            assert 0x0112 not in transposed_im.getexif()\n\n    # Orientation from \"Raw profile type exif\" info key\n    # This test image has been manually hexedited from exif_imagemagick.png\n    # to have a different orientation\n    with Image.open(\"Tests/images/exif_imagemagick_orientation.png\") as im:\n        assert im.getexif()[0x0112] == 3\n\n        transposed_im = ImageOps.exif_transpose(im)\n        assert 0x0112 not in transposed_im.getexif()\n\n    # Orientation set directly on Image.Exif\n    im = hopper()\n    im.getexif()[0x0112] = 3\n    transposed_im = ImageOps.exif_transpose(im)\n    assert 0x0112 not in transposed_im.getexif()\n\n\ndef test_autocontrast_cutoff():\n    # Test the cutoff argument of autocontrast\n    with Image.open(\"Tests/images/bw_gradient.png\") as img:\n\n        def autocontrast(cutoff):\n            return ImageOps.autocontrast(img, cutoff).histogram()\n\n        assert autocontrast(10) == autocontrast((10, 10))\n        assert autocontrast(10) != autocontrast((1, 10))\n\n\ndef test_autocontrast_mask_toy_input():\n    # Test the mask argument of autocontrast\n    with Image.open(\"Tests/images/bw_gradient.png\") as img:\n\n        rect_mask = Image.new(\"L\", img.size, 0)\n        draw = ImageDraw.Draw(rect_mask)\n        x0 = img.size[0] // 4\n        y0 = img.size[1] // 4\n        x1 = 3 * img.size[0] // 4\n        y1 = 3 * img.size[1] // 4\n        draw.rectangle((x0, y0, x1, y1), fill=255)\n\n        result = ImageOps.autocontrast(img, mask=rect_mask)\n        result_nomask = ImageOps.autocontrast(img)\n\n        assert result != result_nomask\n        assert ImageStat.Stat(result, mask=rect_mask).median == [127]\n        assert ImageStat.Stat(result_nomask).median == [128]\n\n\ndef test_autocontrast_mask_real_input():\n    # Test the autocontrast with a rectangular mask\n    with Image.open(\"Tests/images/iptc.jpg\") as img:\n\n        rect_mask = Image.new(\"L\", img.size, 0)\n        draw = ImageDraw.Draw(rect_mask)\n        x0, y0 = img.size[0] // 2, img.size[1] // 2\n        x1, y1 = img.size[0] - 40, img.size[1]\n        draw.rectangle((x0, y0, x1, y1), fill=255)\n\n        result = ImageOps.autocontrast(img, mask=rect_mask)\n        result_nomask = ImageOps.autocontrast(img)\n\n        assert result_nomask != result\n        assert_tuple_approx_equal(\n            ImageStat.Stat(result, mask=rect_mask).median,\n            [195, 202, 184],\n            threshold=2,\n            msg=\"autocontrast with mask pixel incorrect\",\n        )\n        assert_tuple_approx_equal(\n            ImageStat.Stat(result_nomask).median,\n            [119, 106, 79],\n            threshold=2,\n            msg=\"autocontrast without mask pixel incorrect\",\n        )\n\n\ndef test_autocontrast_preserve_tone():\n    def autocontrast(mode, preserve_tone):\n        im = hopper(mode)\n        return ImageOps.autocontrast(im, preserve_tone=preserve_tone).histogram()\n\n    assert autocontrast(\"RGB\", True) != autocontrast(\"RGB\", False)\n    assert autocontrast(\"L\", True) == autocontrast(\"L\", False)\n\n\ndef test_autocontrast_preserve_gradient():\n    gradient = Image.linear_gradient(\"L\")\n\n    # test with a grayscale gradient that extends to 0,255.\n    # Should be a noop.\n    out = ImageOps.autocontrast(gradient, cutoff=0, preserve_tone=True)\n\n    assert_image_equal(gradient, out)\n\n    # cutoff the top and bottom\n    # autocontrast should make the first and last histogram entries equal\n    # and, with rounding, should be 10% of the image pixels\n    out = ImageOps.autocontrast(gradient, cutoff=10, preserve_tone=True)\n    hist = out.histogram()\n    assert hist[0] == hist[-1]\n    assert hist[-1] == 256 * round(256 * 0.10)\n\n    # in rgb\n    img = gradient.convert(\"RGB\")\n    out = ImageOps.autocontrast(img, cutoff=0, preserve_tone=True)\n    assert_image_equal(img, out)\n\n\n@pytest.mark.parametrize(\n    \"color\", ((255, 255, 255), (127, 255, 0), (127, 127, 127), (0, 0, 0))\n)\ndef test_autocontrast_preserve_one_color(color):\n    img = Image.new(\"RGB\", (10, 10), color)\n\n    # single color images shouldn't change\n    out = ImageOps.autocontrast(img, cutoff=0, preserve_tone=True)\n    assert_image_equal(img, out)  # single color, no cutoff\n\n    # even if there is a cutoff\n    out = ImageOps.autocontrast(\n        img, cutoff=10, preserve_tone=True\n    )  # single color 10 cutoff\n    assert_image_equal(img, out)\n",
            "header": {
                "file": {
                    "path": "Tests/test_imageops.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "01e40e6d4",
                "new_commit_hash": "550578f8f",
                "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": 110,
                            "length": 6
                        },
                        "new_range": {
                            "start": 110,
                            "length": 16
                        },
                        "section": "def test_contain(new_size):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    assert new_im.size == (256, 256)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def test_contain_round():",
                                "type": "added"
                            },
                            {
                                "content": "    im = Image.new(\"1\", (43, 63), 1)",
                                "type": "added"
                            },
                            {
                                "content": "    new_im = ImageOps.contain(im, (5, 7))",
                                "type": "added"
                            },
                            {
                                "content": "    assert new_im.width == 5",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    im = Image.new(\"1\", (63, 43), 1)",
                                "type": "added"
                            },
                            {
                                "content": "    new_im = ImageOps.contain(im, (7, 5))",
                                "type": "added"
                            },
                            {
                                "content": "    assert new_im.height == 5",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "def test_pad():",
                                "type": "context"
                            },
                            {
                                "content": "    # Same ratio",
                                "type": "context"
                            },
                            {
                                "content": "    im = hopper()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Tests/test_imageops.py",
                            "type": "function",
                            "name": "test_contain_round",
                            "content": "def test_contain_round():\n    im = Image.new(\"1\", (43, 63), 1)\n    new_im = ImageOps.contain(im, (5, 7))\n    assert new_im.width == 5\n\n    im = Image.new(\"1\", (63, 43), 1)\n    new_im = ImageOps.contain(im, (7, 5))\n    assert new_im.height == 5",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 113,
                            "end_lineno": 120,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 130,
                            "length": 6
                        },
                        "new_range": {
                            "start": 140,
                            "length": 15
                        },
                        "section": "def test_pad():"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            )",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def test_pad_round():",
                                "type": "added"
                            },
                            {
                                "content": "    im = Image.new(\"1\", (1, 1), 1)",
                                "type": "added"
                            },
                            {
                                "content": "    new_im = ImageOps.pad(im, (4, 1))",
                                "type": "added"
                            },
                            {
                                "content": "    assert new_im.load()[2, 0] == 1",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    new_im = ImageOps.pad(im, (1, 4))",
                                "type": "added"
                            },
                            {
                                "content": "    assert new_im.load()[0, 2] == 1",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "def test_pil163():",
                                "type": "context"
                            },
                            {
                                "content": "    # Division by zero in equalize if < 255 pixels in image (@PIL163)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Tests/test_imageops.py",
                            "type": "function",
                            "name": "test_pad_round",
                            "content": "def test_pad_round():\n    im = Image.new(\"1\", (1, 1), 1)\n    new_im = ImageOps.pad(im, (4, 1))\n    assert new_im.load()[2, 0] == 1\n\n    new_im = ImageOps.pad(im, (1, 4))\n    assert new_im.load()[0, 2] == 1",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 143,
                            "end_lineno": 149,
                            "parent": null
                        }
                    ],
                    "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\nimport functools\nimport operator\nimport re\n\nfrom . import Image\n\n#\n# helpers\n\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 isinstance(color, str):\n        from . import ImageColor\n\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 OSError(\"not supported for this image mode\")\n\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None, mask=None, preserve_tone=False):\n    \"\"\"\n    Maximize (normalize) image contrast. This function calculates a\n    histogram of the input image (or mask region), 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: The percent to cut off from the histogram on the low and\n                   high ends. Either a tuple of (low, high), or a single\n                   number for both.\n    :param ignore: The background pixel value (use None for no background).\n    :param mask: Histogram used in contrast operation is computed using pixels\n                 within the mask. If no mask is given the entire image is used\n                 for histogram computation.\n    :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.\n\n                          .. versionadded:: 8.2.0\n\n    :return: An image.\n    \"\"\"\n    if preserve_tone:\n        histogram = image.convert(\"L\").histogram(mask)\n    else:\n        histogram = image.histogram(mask)\n\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            if not isinstance(cutoff, tuple):\n                cutoff = (cutoff, cutoff)\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[0] // 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 high end\n            cut = n * cutoff[1] // 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, 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 contain(image, size, method=Image.Resampling.BICUBIC):\n    \"\"\"\n    Returns a resized version of the image, set to the maximum width and height\n    within the requested size, while maintaining the original aspect ratio.\n\n    :param image: The image to resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\n    :return: An image.\n    \"\"\"\n\n    im_ratio = image.width / image.height\n    dest_ratio = size[0] / size[1]\n\n    if im_ratio != dest_ratio:\n        if im_ratio > dest_ratio:\n            new_height = int(image.height / image.width * size[0])\n            if new_height != size[1]:\n                size = (size[0], new_height)\n        else:\n            new_width = int(image.width / image.height * size[1])\n            if new_width != size[0]:\n                size = (new_width, size[1])\n    return image.resize(size, resample=method)\n\n\ndef pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a resized and padded version of the image, expanded to fill the\n    requested aspect ratio and size.\n\n    :param image: The image to resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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\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    resized = contain(image, size, method)\n    if resized.size == size:\n        out = resized\n    else:\n        out = Image.new(image.mode, size, color)\n        if resized.width != size[0]:\n            x = int((size[0] - resized.width) * max(0, min(centering[0], 1)))\n            out.paste(resized, (x, 0))\n        else:\n            y = int((size[1] - resized.height) * max(0, min(centering[1], 1)))\n            out.paste(resized, (0, y))\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((left, top, image.size[0] - right, image.size[1] - bottom))\n\n\ndef scale(image, factor, resample=Image.Resampling.BICUBIC):\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: Resampling method to use. Default is\n                     :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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 = (round(factor * image.width), round(factor * image.height))\n        return image.resize(size, resample)\n\n\ndef deform(image, deformer, resample=Image.Resampling.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.Transform.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    color = _color(fill, image.mode)\n    if image.mode == \"P\" and image.palette:\n        image.load()\n        palette = image.palette.copy()\n        if isinstance(color, tuple):\n            color = palette.getcolor(color)\n    else:\n        palette = None\n    out = Image.new(image.mode, (width, height), color)\n    if palette:\n        out.putpalette(palette.palette)\n    out.paste(image, (left, top))\n    return out\n\n\ndef fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a resized 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 resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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    # https://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 = (\n        image.size[0] - bleed_pixels[0] * 2,\n        image.size[1] - bleed_pixels[1] * 2,\n    )\n\n    # calculate the aspect ratio of the live_size\n    live_size_ratio = live_size[0] / live_size[1]\n\n    # calculate the aspect ratio of the output image\n    output_ratio = 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 already the needed ratio\n        crop_width = live_size[0]\n        crop_height = live_size[1]\n    elif 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 = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)\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.Transpose.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 image.point(lut) if image.mode == \"1\" else _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.Transpose.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, other than 1, return a new image\n    that is transposed accordingly. The new image will have the orientation\n    data removed.\n\n    Otherwise, return a copy of the image.\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    exif = image.getexif()\n    orientation = exif.get(0x0112)\n    method = {\n        2: Image.Transpose.FLIP_LEFT_RIGHT,\n        3: Image.Transpose.ROTATE_180,\n        4: Image.Transpose.FLIP_TOP_BOTTOM,\n        5: Image.Transpose.TRANSPOSE,\n        6: Image.Transpose.ROTATE_270,\n        7: Image.Transpose.TRANSVERSE,\n        8: Image.Transpose.ROTATE_90,\n    }.get(orientation)\n    if method is not None:\n        transposed_image = image.transpose(method)\n        transposed_exif = transposed_image.getexif()\n        if 0x0112 in transposed_exif:\n            del transposed_exif[0x0112]\n            if \"exif\" in transposed_image.info:\n                transposed_image.info[\"exif\"] = transposed_exif.tobytes()\n            elif \"Raw profile type exif\" in transposed_image.info:\n                transposed_image.info[\n                    \"Raw profile type exif\"\n                ] = transposed_exif.tobytes().hex()\n            elif \"XML:com.adobe.xmp\" in transposed_image.info:\n                for pattern in (\n                    r'tiff:Orientation=\"([0-9])\"',\n                    r\"<tiff:Orientation>([0-9])</tiff:Orientation>\",\n                ):\n                    transposed_image.info[\"XML:com.adobe.xmp\"] = re.sub(\n                        pattern, \"\", transposed_image.info[\"XML:com.adobe.xmp\"]\n                    )\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\nimport functools\nimport operator\nimport re\n\nfrom . import Image\n\n#\n# helpers\n\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 isinstance(color, str):\n        from . import ImageColor\n\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 OSError(\"not supported for this image mode\")\n\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None, mask=None, preserve_tone=False):\n    \"\"\"\n    Maximize (normalize) image contrast. This function calculates a\n    histogram of the input image (or mask region), 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: The percent to cut off from the histogram on the low and\n                   high ends. Either a tuple of (low, high), or a single\n                   number for both.\n    :param ignore: The background pixel value (use None for no background).\n    :param mask: Histogram used in contrast operation is computed using pixels\n                 within the mask. If no mask is given the entire image is used\n                 for histogram computation.\n    :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.\n\n                          .. versionadded:: 8.2.0\n\n    :return: An image.\n    \"\"\"\n    if preserve_tone:\n        histogram = image.convert(\"L\").histogram(mask)\n    else:\n        histogram = image.histogram(mask)\n\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            if not isinstance(cutoff, tuple):\n                cutoff = (cutoff, cutoff)\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[0] // 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 high end\n            cut = n * cutoff[1] // 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, 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 contain(image, size, method=Image.Resampling.BICUBIC):\n    \"\"\"\n    Returns a resized version of the image, set to the maximum width and height\n    within the requested size, while maintaining the original aspect ratio.\n\n    :param image: The image to resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\n    :return: An image.\n    \"\"\"\n\n    im_ratio = image.width / image.height\n    dest_ratio = size[0] / size[1]\n\n    if im_ratio != dest_ratio:\n        if im_ratio > dest_ratio:\n            new_height = round(image.height / image.width * size[0])\n            if new_height != size[1]:\n                size = (size[0], new_height)\n        else:\n            new_width = round(image.width / image.height * size[1])\n            if new_width != size[0]:\n                size = (new_width, size[1])\n    return image.resize(size, resample=method)\n\n\ndef pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a resized and padded version of the image, expanded to fill the\n    requested aspect ratio and size.\n\n    :param image: The image to resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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\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    resized = contain(image, size, method)\n    if resized.size == size:\n        out = resized\n    else:\n        out = Image.new(image.mode, size, color)\n        if resized.width != size[0]:\n            x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))\n            out.paste(resized, (x, 0))\n        else:\n            y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))\n            out.paste(resized, (0, y))\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((left, top, image.size[0] - right, image.size[1] - bottom))\n\n\ndef scale(image, factor, resample=Image.Resampling.BICUBIC):\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: Resampling method to use. Default is\n                     :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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 = (round(factor * image.width), round(factor * image.height))\n        return image.resize(size, resample)\n\n\ndef deform(image, deformer, resample=Image.Resampling.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.Transform.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    color = _color(fill, image.mode)\n    if image.mode == \"P\" and image.palette:\n        image.load()\n        palette = image.palette.copy()\n        if isinstance(color, tuple):\n            color = palette.getcolor(color)\n    else:\n        palette = None\n    out = Image.new(image.mode, (width, height), color)\n    if palette:\n        out.putpalette(palette.palette)\n    out.paste(image, (left, top))\n    return out\n\n\ndef fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a resized 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 resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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    # https://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 = (\n        image.size[0] - bleed_pixels[0] * 2,\n        image.size[1] - bleed_pixels[1] * 2,\n    )\n\n    # calculate the aspect ratio of the live_size\n    live_size_ratio = live_size[0] / live_size[1]\n\n    # calculate the aspect ratio of the output image\n    output_ratio = 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 already the needed ratio\n        crop_width = live_size[0]\n        crop_height = live_size[1]\n    elif 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 = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)\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.Transpose.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 image.point(lut) if image.mode == \"1\" else _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.Transpose.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, other than 1, return a new image\n    that is transposed accordingly. The new image will have the orientation\n    data removed.\n\n    Otherwise, return a copy of the image.\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    exif = image.getexif()\n    orientation = exif.get(0x0112)\n    method = {\n        2: Image.Transpose.FLIP_LEFT_RIGHT,\n        3: Image.Transpose.ROTATE_180,\n        4: Image.Transpose.FLIP_TOP_BOTTOM,\n        5: Image.Transpose.TRANSPOSE,\n        6: Image.Transpose.ROTATE_270,\n        7: Image.Transpose.TRANSVERSE,\n        8: Image.Transpose.ROTATE_90,\n    }.get(orientation)\n    if method is not None:\n        transposed_image = image.transpose(method)\n        transposed_exif = transposed_image.getexif()\n        if 0x0112 in transposed_exif:\n            del transposed_exif[0x0112]\n            if \"exif\" in transposed_image.info:\n                transposed_image.info[\"exif\"] = transposed_exif.tobytes()\n            elif \"Raw profile type exif\" in transposed_image.info:\n                transposed_image.info[\n                    \"Raw profile type exif\"\n                ] = transposed_exif.tobytes().hex()\n            elif \"XML:com.adobe.xmp\" in transposed_image.info:\n                for pattern in (\n                    r'tiff:Orientation=\"([0-9])\"',\n                    r\"<tiff:Orientation>([0-9])</tiff:Orientation>\",\n                ):\n                    transposed_image.info[\"XML:com.adobe.xmp\"] = re.sub(\n                        pattern, \"\", transposed_image.info[\"XML:com.adobe.xmp\"]\n                    )\n        return transposed_image\n    return image.copy()\n",
            "header": {
                "file": {
                    "path": "src/PIL/ImageOps.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "0c3f900ca",
                "new_commit_hash": "ae43fc3bd",
                "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": 255,
                            "length": 11
                        },
                        "new_range": {
                            "start": 255,
                            "length": 11
                        },
                        "section": "def contain(image, size, method=Image.Resampling.BICUBIC):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    if im_ratio != dest_ratio:",
                                "type": "context"
                            },
                            {
                                "content": "        if im_ratio > dest_ratio:",
                                "type": "context"
                            },
                            {
                                "content": "            new_height = int(image.height / image.width * size[0])",
                                "type": "deleted"
                            },
                            {
                                "content": "            new_height = round(image.height / image.width * size[0])",
                                "type": "added"
                            },
                            {
                                "content": "            if new_height != size[1]:",
                                "type": "context"
                            },
                            {
                                "content": "                size = (size[0], new_height)",
                                "type": "context"
                            },
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            new_width = int(image.width / image.height * size[1])",
                                "type": "deleted"
                            },
                            {
                                "content": "            new_width = round(image.width / image.height * size[1])",
                                "type": "added"
                            },
                            {
                                "content": "            if new_width != size[0]:",
                                "type": "context"
                            },
                            {
                                "content": "                size = (new_width, size[1])",
                                "type": "context"
                            },
                            {
                                "content": "    return image.resize(size, resample=method)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/ImageOps.py",
                            "type": "function",
                            "name": "contain",
                            "content": "def contain(image, size, method=Image.Resampling.BICUBIC):\n    \"\"\"\n    Returns a resized version of the image, set to the maximum width and height\n    within the requested size, while maintaining the original aspect ratio.\n\n    :param image: The image to resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\n    :return: An image.\n    \"\"\"\n\n    im_ratio = image.width / image.height\n    dest_ratio = size[0] / size[1]\n\n    if im_ratio != dest_ratio:\n        if im_ratio > dest_ratio:\n            new_height = int(image.height / image.width * size[0])\n            if new_height != size[1]:\n                size = (size[0], new_height)\n        else:\n            new_width = int(image.width / image.height * size[1])\n            if new_width != size[0]:\n                size = (new_width, size[1])\n    return image.resize(size, resample=method)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 240,
                            "end_lineno": 265,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 292,
                            "length": 10
                        },
                        "new_range": {
                            "start": 292,
                            "length": 10
                        },
                        "section": "def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    else:",
                                "type": "context"
                            },
                            {
                                "content": "        out = Image.new(image.mode, size, color)",
                                "type": "context"
                            },
                            {
                                "content": "        if resized.width != size[0]:",
                                "type": "context"
                            },
                            {
                                "content": "            x = int((size[0] - resized.width) * max(0, min(centering[0], 1)))",
                                "type": "deleted"
                            },
                            {
                                "content": "            x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))",
                                "type": "added"
                            },
                            {
                                "content": "            out.paste(resized, (x, 0))",
                                "type": "context"
                            },
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            y = int((size[1] - resized.height) * max(0, min(centering[1], 1)))",
                                "type": "deleted"
                            },
                            {
                                "content": "            y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))",
                                "type": "added"
                            },
                            {
                                "content": "            out.paste(resized, (0, y))",
                                "type": "context"
                            },
                            {
                                "content": "    return out",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/ImageOps.py",
                            "type": "function",
                            "name": "pad",
                            "content": "def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a resized and padded version of the image, expanded to fill the\n    requested aspect ratio and size.\n\n    :param image: The image to resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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\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    resized = contain(image, size, method)\n    if resized.size == size:\n        out = resized\n    else:\n        out = Image.new(image.mode, size, color)\n        if resized.width != size[0]:\n            x = int((size[0] - resized.width) * max(0, min(centering[0], 1)))\n            out.paste(resized, (x, 0))\n        else:\n            y = int((size[1] - resized.height) * max(0, min(centering[1], 1)))\n            out.paste(resized, (0, y))\n    return out",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 268,
                            "end_lineno": 300,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "f98fde7dad773cc913ec05a3b8db5eacfa888300^",
    "new_commit_hash": "f98fde7dad773cc913ec05a3b8db5eacfa888300",
    "commit_message": "Merge pull request #6522 from bibinhashley/ImageOps.contain-function-issue-in-finding-new-size",
    "commit_date": "2022-09-21T12:58:09+03:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "f98fde7dad773cc913ec05a3b8db5eacfa888300",
    "test_file_codes": [
        "import pytest\n\nfrom PIL import Image, ImageDraw, ImageOps, ImageStat, features\n\nfrom .helper import (\n    assert_image_equal,\n    assert_image_similar,\n    assert_image_similar_tofile,\n    assert_tuple_approx_equal,\n    hopper,\n)\n\n\nclass Deformer:\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\ndeformer = Deformer()\n\n\ndef test_sanity():\n\n    ImageOps.autocontrast(hopper(\"L\"))\n    ImageOps.autocontrast(hopper(\"RGB\"))\n\n    ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n    ImageOps.autocontrast(hopper(\"L\"), cutoff=(2, 10))\n    ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n    ImageOps.autocontrast(hopper(\"L\"), mask=hopper(\"L\"))\n    ImageOps.autocontrast(hopper(\"L\"), preserve_tone=True)\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.contain(hopper(\"L\"), (128, 128))\n    ImageOps.contain(hopper(\"RGB\"), (128, 128))\n\n    ImageOps.crop(hopper(\"L\"), 1)\n    ImageOps.crop(hopper(\"RGB\"), 1)\n\n    ImageOps.deform(hopper(\"L\"), deformer)\n    ImageOps.deform(hopper(\"RGB\"), 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(\"1\"))\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\ndef test_1pxfit():\n    # Division by zero in equalize if image is 1 pixel high\n    newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n    assert newimg.size == (35, 35)\n\n    newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n    assert newimg.size == (35, 35)\n\n    newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n    assert newimg.size == (35, 35)\n\n\ndef test_fit_same_ratio():\n    # The ratio for this image is 1000.0 / 755 = 1.3245033112582782\n    # If the ratios are not acknowledged to be the same,\n    # and Pillow attempts to adjust the width to\n    # 1.3245033112582782 * 755 = 1000.0000000000001\n    # then centering this greater width causes a negative x offset when cropping\n    with Image.new(\"RGB\", (1000, 755)) as im:\n        new_im = ImageOps.fit(im, (1000, 755))\n        assert new_im.size == (1000, 755)\n\n\n@pytest.mark.parametrize(\"new_size\", ((256, 256), (512, 256), (256, 512)))\ndef test_contain(new_size):\n    im = hopper()\n    new_im = ImageOps.contain(im, new_size)\n    assert new_im.size == (256, 256)\n\n\ndef test_contain_round():\n    im = Image.new(\"1\", (43, 63), 1)\n    new_im = ImageOps.contain(im, (5, 7))\n    assert new_im.width == 5\n\n    im = Image.new(\"1\", (63, 43), 1)\n    new_im = ImageOps.contain(im, (7, 5))\n    assert new_im.height == 5\n\n\ndef test_pad():\n    # Same ratio\n    im = hopper()\n    new_size = (im.width * 2, im.height * 2)\n    new_im = ImageOps.pad(im, new_size)\n    assert 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, color=color, centering=centering)\n            assert new_im.size == new_size\n\n            assert_image_similar_tofile(\n                new_im, \"Tests/images/imageops_pad_\" + label + \"_\" + str(i) + \".jpg\", 6\n            )\n\n\ndef test_pad_round():\n    im = Image.new(\"1\", (1, 1), 1)\n    new_im = ImageOps.pad(im, (4, 1))\n    assert new_im.load()[2, 0] == 1\n\n    new_im = ImageOps.pad(im, (1, 4))\n    assert new_im.load()[0, 2] == 1\n\n\ndef test_pil163():\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\ndef test_scale():\n    # Test the scaling function\n    i = hopper(\"L\").resize((50, 50))\n\n    with pytest.raises(ValueError):\n        ImageOps.scale(i, -1)\n\n    newimg = ImageOps.scale(i, 1)\n    assert newimg.size == (50, 50)\n\n    newimg = ImageOps.scale(i, 2)\n    assert newimg.size == (100, 100)\n\n    newimg = ImageOps.scale(i, 0.5)\n    assert newimg.size == (25, 25)\n\n\n@pytest.mark.parametrize(\"border\", (10, (1, 2, 3, 4)))\ndef test_expand_palette(border):\n    with Image.open(\"Tests/images/p_16.tga\") as im:\n        im_expanded = ImageOps.expand(im, border, (255, 0, 0))\n\n        if isinstance(border, int):\n            left = top = right = bottom = border\n        else:\n            left, top, right, bottom = border\n        px = im_expanded.convert(\"RGB\").load()\n        for x in range(im_expanded.width):\n            for b in range(top):\n                assert px[x, b] == (255, 0, 0)\n            for b in range(bottom):\n                assert px[x, im_expanded.height - 1 - b] == (255, 0, 0)\n        for y in range(im_expanded.height):\n            for b in range(left):\n                assert px[b, y] == (255, 0, 0)\n            for b in range(right):\n                assert px[im_expanded.width - 1 - b, y] == (255, 0, 0)\n\n        im_cropped = im_expanded.crop(\n            (left, top, im_expanded.width - right, im_expanded.height - bottom)\n        )\n        assert_image_equal(im_cropped, im)\n\n\ndef test_colorize_2color():\n    # Test the colorizing function with 2-color functionality\n\n    # Open test image (256px by 10px, black to white)\n    with Image.open(\"Tests/images/bw_gradient.png\") as im:\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    assert_tuple_approx_equal(\n        im_test.getpixel(left),\n        (255, 0, 0),\n        threshold=1,\n        msg=\"black test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(middle),\n        (127, 63, 0),\n        threshold=1,\n        msg=\"mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right),\n        (0, 127, 0),\n        threshold=1,\n        msg=\"white test pixel incorrect\",\n    )\n\n\ndef test_colorize_2color_offset():\n    # Test the colorizing function with 2-color functionality and offset\n\n    # Open test image (256px by 10px, black to white)\n    with Image.open(\"Tests/images/bw_gradient.png\") as im:\n        im = im.convert(\"L\")\n\n    # Create image with original 2-color functionality with offsets\n    im_test = ImageOps.colorize(\n        im, black=\"red\", white=\"green\", blackpoint=50, whitepoint=100\n    )\n\n    # Test output image (2-color) with offsets\n    left = (25, 1)\n    middle = (75, 1)\n    right = (125, 1)\n    assert_tuple_approx_equal(\n        im_test.getpixel(left),\n        (255, 0, 0),\n        threshold=1,\n        msg=\"black test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(middle),\n        (127, 63, 0),\n        threshold=1,\n        msg=\"mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right),\n        (0, 127, 0),\n        threshold=1,\n        msg=\"white test pixel incorrect\",\n    )\n\n\ndef test_colorize_3color_offset():\n    # Test the colorizing function with 3-color functionality and offset\n\n    # Open test image (256px by 10px, black to white)\n    with Image.open(\"Tests/images/bw_gradient.png\") as im:\n        im = im.convert(\"L\")\n\n    # Create image with new three color functionality with offsets\n    im_test = ImageOps.colorize(\n        im,\n        black=\"red\",\n        white=\"green\",\n        mid=\"blue\",\n        blackpoint=50,\n        whitepoint=200,\n        midpoint=100,\n    )\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    assert_tuple_approx_equal(\n        im_test.getpixel(left),\n        (255, 0, 0),\n        threshold=1,\n        msg=\"black test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(left_middle),\n        (127, 0, 127),\n        threshold=1,\n        msg=\"low-mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(middle), (0, 0, 255), threshold=1, msg=\"mid incorrect\"\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right_middle),\n        (0, 63, 127),\n        threshold=1,\n        msg=\"high-mid test pixel incorrect\",\n    )\n    assert_tuple_approx_equal(\n        im_test.getpixel(right),\n        (0, 127, 0),\n        threshold=1,\n        msg=\"white test pixel incorrect\",\n    )\n\n\ndef test_exif_transpose():\n    exts = [\".jpg\"]\n    if features.check(\"webp\") and features.check(\"webp_anim\"):\n        exts.append(\".webp\")\n    for ext in exts:\n        with Image.open(\"Tests/images/hopper\" + ext) as base_im:\n\n            def check(orientation_im):\n                for im in [\n                    orientation_im,\n                    orientation_im.copy(),\n                ]:  # ImageFile  # Image\n                    if orientation_im is base_im:\n                        assert \"exif\" not in im.info\n                    else:\n                        original_exif = im.info[\"exif\"]\n                    transposed_im = ImageOps.exif_transpose(im)\n                    assert_image_similar(base_im, transposed_im, 17)\n                    if orientation_im is base_im:\n                        assert \"exif\" not in im.info\n                    else:\n                        assert transposed_im.info[\"exif\"] != original_exif\n\n                        assert 0x0112 in im.getexif()\n                        assert 0x0112 not in transposed_im.getexif()\n\n                    # Repeat the operation to test that it does not keep transposing\n                    transposed_im2 = ImageOps.exif_transpose(transposed_im)\n                    assert_image_equal(transposed_im2, transposed_im)\n\n            check(base_im)\n            for i in range(2, 9):\n                with Image.open(\n                    \"Tests/images/hopper_orientation_\" + str(i) + ext\n                ) as orientation_im:\n                    check(orientation_im)\n\n    # Orientation from \"XML:com.adobe.xmp\" info key\n    for suffix in (\"\", \"_exiftool\"):\n        with Image.open(\"Tests/images/xmp_tags_orientation\" + suffix + \".png\") as im:\n            assert im.getexif()[0x0112] == 3\n\n            transposed_im = ImageOps.exif_transpose(im)\n            assert 0x0112 not in transposed_im.getexif()\n\n            transposed_im._reload_exif()\n            assert 0x0112 not in transposed_im.getexif()\n\n    # Orientation from \"Raw profile type exif\" info key\n    # This test image has been manually hexedited from exif_imagemagick.png\n    # to have a different orientation\n    with Image.open(\"Tests/images/exif_imagemagick_orientation.png\") as im:\n        assert im.getexif()[0x0112] == 3\n\n        transposed_im = ImageOps.exif_transpose(im)\n        assert 0x0112 not in transposed_im.getexif()\n\n    # Orientation set directly on Image.Exif\n    im = hopper()\n    im.getexif()[0x0112] = 3\n    transposed_im = ImageOps.exif_transpose(im)\n    assert 0x0112 not in transposed_im.getexif()\n\n\ndef test_autocontrast_cutoff():\n    # Test the cutoff argument of autocontrast\n    with Image.open(\"Tests/images/bw_gradient.png\") as img:\n\n        def autocontrast(cutoff):\n            return ImageOps.autocontrast(img, cutoff).histogram()\n\n        assert autocontrast(10) == autocontrast((10, 10))\n        assert autocontrast(10) != autocontrast((1, 10))\n\n\ndef test_autocontrast_mask_toy_input():\n    # Test the mask argument of autocontrast\n    with Image.open(\"Tests/images/bw_gradient.png\") as img:\n\n        rect_mask = Image.new(\"L\", img.size, 0)\n        draw = ImageDraw.Draw(rect_mask)\n        x0 = img.size[0] // 4\n        y0 = img.size[1] // 4\n        x1 = 3 * img.size[0] // 4\n        y1 = 3 * img.size[1] // 4\n        draw.rectangle((x0, y0, x1, y1), fill=255)\n\n        result = ImageOps.autocontrast(img, mask=rect_mask)\n        result_nomask = ImageOps.autocontrast(img)\n\n        assert result != result_nomask\n        assert ImageStat.Stat(result, mask=rect_mask).median == [127]\n        assert ImageStat.Stat(result_nomask).median == [128]\n\n\ndef test_autocontrast_mask_real_input():\n    # Test the autocontrast with a rectangular mask\n    with Image.open(\"Tests/images/iptc.jpg\") as img:\n\n        rect_mask = Image.new(\"L\", img.size, 0)\n        draw = ImageDraw.Draw(rect_mask)\n        x0, y0 = img.size[0] // 2, img.size[1] // 2\n        x1, y1 = img.size[0] - 40, img.size[1]\n        draw.rectangle((x0, y0, x1, y1), fill=255)\n\n        result = ImageOps.autocontrast(img, mask=rect_mask)\n        result_nomask = ImageOps.autocontrast(img)\n\n        assert result_nomask != result\n        assert_tuple_approx_equal(\n            ImageStat.Stat(result, mask=rect_mask).median,\n            [195, 202, 184],\n            threshold=2,\n            msg=\"autocontrast with mask pixel incorrect\",\n        )\n        assert_tuple_approx_equal(\n            ImageStat.Stat(result_nomask).median,\n            [119, 106, 79],\n            threshold=2,\n            msg=\"autocontrast without mask pixel incorrect\",\n        )\n\n\ndef test_autocontrast_preserve_tone():\n    def autocontrast(mode, preserve_tone):\n        im = hopper(mode)\n        return ImageOps.autocontrast(im, preserve_tone=preserve_tone).histogram()\n\n    assert autocontrast(\"RGB\", True) != autocontrast(\"RGB\", False)\n    assert autocontrast(\"L\", True) == autocontrast(\"L\", False)\n\n\ndef test_autocontrast_preserve_gradient():\n    gradient = Image.linear_gradient(\"L\")\n\n    # test with a grayscale gradient that extends to 0,255.\n    # Should be a noop.\n    out = ImageOps.autocontrast(gradient, cutoff=0, preserve_tone=True)\n\n    assert_image_equal(gradient, out)\n\n    # cutoff the top and bottom\n    # autocontrast should make the first and last histogram entries equal\n    # and, with rounding, should be 10% of the image pixels\n    out = ImageOps.autocontrast(gradient, cutoff=10, preserve_tone=True)\n    hist = out.histogram()\n    assert hist[0] == hist[-1]\n    assert hist[-1] == 256 * round(256 * 0.10)\n\n    # in rgb\n    img = gradient.convert(\"RGB\")\n    out = ImageOps.autocontrast(img, cutoff=0, preserve_tone=True)\n    assert_image_equal(img, out)\n\n\n@pytest.mark.parametrize(\n    \"color\", ((255, 255, 255), (127, 255, 0), (127, 127, 127), (0, 0, 0))\n)\ndef test_autocontrast_preserve_one_color(color):\n    img = Image.new(\"RGB\", (10, 10), color)\n\n    # single color images shouldn't change\n    out = ImageOps.autocontrast(img, cutoff=0, preserve_tone=True)\n    assert_image_equal(img, out)  # single color, no cutoff\n\n    # even if there is a cutoff\n    out = ImageOps.autocontrast(\n        img, cutoff=10, preserve_tone=True\n    )  # single color 10 cutoff\n    assert_image_equal(img, out)\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 17ms\nInstalled 12 packages in 119ms\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 858ms\nPrepared 1 package in 36.18s\nInstalled 1 package in 1ms\n + pillow==9.3.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_f98fde7dad773cc913ec05a3b8db5eacfa888300)\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "\u001b[1m============================= test session starts ==============================\u001b[0m\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_f98fde7dad773cc913ec05a3b8db5eacfa888300\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 26 items\n\nr2e_tests/test_1.py \u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m                           [100%]\u001b[0m\n\n==================================== PASSES ====================================\n\u001b[36m\u001b[1m=========================== short test summary info ============================\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_sanity\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_1pxfit\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_fit_same_ratio\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_contain[new_size0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_contain[new_size1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_contain[new_size2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_contain_round\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_pad\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_pad_round\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_pil163\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_scale\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_expand_palette[10]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_expand_palette[border1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_colorize_2color\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_colorize_2color_offset\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_colorize_3color_offset\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_exif_transpose\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_cutoff\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_mask_toy_input\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_mask_real_input\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_tone\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_gradient\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_one_color[color0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_one_color[color1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_one_color[color2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_one_color[color3]\u001b[0m\n\u001b[32m============================== \u001b[32m\u001b[1m26 passed\u001b[0m\u001b[32m in 0.32s\u001b[0m\u001b[32m ==============================\u001b[0m\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "\u001b[1m============================= test session starts ==============================\u001b[0m\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_f98fde7dad773cc913ec05a3b8db5eacfa888300\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 26 items\n\nr2e_tests/test_1.py \u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[31mF\u001b[0m\u001b[32m.\u001b[0m\u001b[31mF\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[31m                           [100%]\u001b[0m\n\n=================================== FAILURES ===================================\n\u001b[31m\u001b[1m______________________________ test_contain_round ______________________________\u001b[0m\n\n    def test_contain_round():\n        im = Image.new(\"1\", (43, 63), 1)\n        new_im = ImageOps.contain(im, (5, 7))\n>       assert new_im.width == 5\n\u001b[1m\u001b[31mE       assert 4 == 5\u001b[0m\n\u001b[1m\u001b[31mE        +  where 4 = <PIL.Image.Image image mode=1 size=4x7 at 0x7FED46FA96D0>.width\u001b[0m\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:116: AssertionError\n\u001b[31m\u001b[1m________________________________ test_pad_round ________________________________\u001b[0m\n\n    def test_pad_round():\n        im = Image.new(\"1\", (1, 1), 1)\n        new_im = ImageOps.pad(im, (4, 1))\n>       assert new_im.load()[2, 0] == 1\n\u001b[1m\u001b[31mE       assert 0 == 1\u001b[0m\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:146: AssertionError\n==================================== PASSES ====================================\n\u001b[36m\u001b[1m=========================== short test summary info ============================\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_sanity\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_1pxfit\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_fit_same_ratio\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_contain[new_size0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_contain[new_size1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_contain[new_size2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_pad\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_pil163\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_scale\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_expand_palette[10]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_expand_palette[border1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_colorize_2color\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_colorize_2color_offset\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_colorize_3color_offset\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_exif_transpose\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_cutoff\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_mask_toy_input\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_mask_real_input\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_tone\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_gradient\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_one_color[color0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_one_color[color1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_one_color[color2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_autocontrast_preserve_one_color[color3]\u001b[0m\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_contain_round\u001b[0m - assert 4 == 5\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_pad_round\u001b[0m - assert 0 == 1\n\u001b[31m========================= \u001b[31m\u001b[1m2 failed\u001b[0m, \u001b[32m24 passed\u001b[0m\u001b[31m in 0.22s\u001b[0m\u001b[31m =========================\u001b[0m\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:** ImageOps.contain and ImageOps.pad produce incorrect image dimensions and padding positions

**Description:**

When using the `ImageOps.contain` and `ImageOps.pad` functions to resize or pad images, the resulting image dimensions and padding positions are incorrectly calculated in certain scenarios.

**Example Buggy Code:**

```python
from PIL import Image, ImageOps

def resize_image():
    im = Image.new("1", (43, 63), 1)
    new_im = ImageOps.contain(im, (5, 7))
    print(new_im.width)  # Expected: 5, but got: 4

def pad_image():
    im = Image.new("1", (1, 1), 1)
    new_im = ImageOps.pad(im, (4, 1))
    pixels = new_im.load()
    print(pixels[2, 0])  # Expected: 1, but got: 0
```

**Expected Behavior:**

- **`ImageOps.contain`:** The resized image should have the exact dimensions specified (e.g., width of 5 and height of 7).
- **`ImageOps.pad`:** The padding should be correctly applied, ensuring that the specified pixel positions retain the expected values (e.g., pixel at position (2, 0) should be 1).

**Actual Behavior:**

- **`ImageOps.contain`:** The resized image has an incorrect width of 4 instead of the expected 5.
- **`ImageOps.pad`:** The padding results in unexpected pixel values, with the pixel at position (2, 0) being 0 instead of the expected 1.

[/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.
#

import functools
import operator
import re

from . import Image

#
# 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 isinstance(color, str):
        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 OSError("not supported for this image mode")


#
# actions


def autocontrast(image, cutoff=0, ignore=None, mask=None, preserve_tone=False):
    """
    Maximize (normalize) image contrast. This function calculates a
    histogram of the input image (or mask region), 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: The percent to cut off from the histogram on the low and
                   high ends. Either a tuple of (low, high), or a single
                   number for both.
    :param ignore: The background pixel value (use None for no background).
    :param mask: Histogram used in contrast operation is computed using pixels
                 within the mask. If no mask is given the entire image is used
                 for histogram computation.
    :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.

                          .. versionadded:: 8.2.0

    :return: An image.
    """
    if preserve_tone:
        histogram = image.convert("L").histogram(mask)
    else:
        histogram = image.histogram(mask)

    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
            if not isinstance(cutoff, tuple):
                cutoff = (cutoff, cutoff)
            # 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[0] // 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 high end
            cut = n * cutoff[1] // 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 contain(image, size, method=Image.Resampling.BICUBIC):
    """
    Returns a resized version of the image, set to the maximum width and height
    within the requested size, while maintaining the original aspect ratio.

    :param image: The image to resize and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: Resampling method to use. Default is
                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
    :return: An image.
    """

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

    if im_ratio != dest_ratio:
        if im_ratio > dest_ratio:
            new_height = int(image.height / image.width * size[0])
            if new_height != size[1]:
                size = (size[0], new_height)
        else:
            new_width = int(image.width / image.height * size[1])
            if new_width != size[0]:
                size = (new_width, size[1])
    return image.resize(size, resample=method)


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

    :param image: The image to resize and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: Resampling method to use. Default is
                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
    :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.
    """

    resized = contain(image, size, method)
    if resized.size == size:
        out = resized
    else:
        out = Image.new(image.mode, size, color)
        if resized.width != size[0]:
            x = int((size[0] - resized.width) * max(0, min(centering[0], 1)))
            out.paste(resized, (x, 0))
        else:
            y = int((size[1] - resized.height) * max(0, min(centering[1], 1)))
            out.paste(resized, (0, y))
    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.Resampling.BICUBIC):
    """
    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: Resampling method to use. Default is
                     :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
    :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 = (round(factor * image.width), round(factor * image.height))
        return image.resize(size, resample)


def deform(image, deformer, resample=Image.Resampling.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.Transform.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
    color = _color(fill, image.mode)
    if image.mode == "P" and image.palette:
        image.load()
        palette = image.palette.copy()
        if isinstance(color, tuple):
            color = palette.getcolor(color)
    else:
        palette = None
    out = Image.new(image.mode, (width, height), color)
    if palette:
        out.putpalette(palette.palette)
    out.paste(image, (left, top))
    return out


def fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5, 0.5)):
    """
    Returns a resized 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 resize and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: Resampling method to use. Default is
                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
    :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
    # https://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 = live_size[0] / live_size[1]

    # calculate the aspect ratio of the output image
    output_ratio = 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 already the needed ratio
        crop_width = live_size[0]
        crop_height = live_size[1]
    elif 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.Transpose.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 image.point(lut) if image.mode == "1" else _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.Transpose.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, other than 1, return a new image
    that is transposed accordingly. The new image will have the orientation
    data removed.

    Otherwise, return a copy of the image.

    :param image: The image to transpose.
    :return: An image.
    """
    exif = image.getexif()
    orientation = exif.get(0x0112)
    method = {
        2: Image.Transpose.FLIP_LEFT_RIGHT,
        3: Image.Transpose.ROTATE_180,
        4: Image.Transpose.FLIP_TOP_BOTTOM,
        5: Image.Transpose.TRANSPOSE,
        6: Image.Transpose.ROTATE_270,
        7: Image.Transpose.TRANSVERSE,
        8: Image.Transpose.ROTATE_90,
    }.get(orientation)
    if method is not None:
        transposed_image = image.transpose(method)
        transposed_exif = transposed_image.getexif()
        if 0x0112 in transposed_exif:
            del transposed_exif[0x0112]
            if "exif" in transposed_image.info:
                transposed_image.info["exif"] = transposed_exif.tobytes()
            elif "Raw profile type exif" in transposed_image.info:
                transposed_image.info[
                    "Raw profile type exif"
                ] = transposed_exif.tobytes().hex()
            elif "XML:com.adobe.xmp" in transposed_image.info:
                for pattern in (
                    r'tiff:Orientation="([0-9])"',
                    r"<tiff:Orientation>([0-9])</tiff:Orientation>",
                ):
                    transposed_image.info["XML:com.adobe.xmp"] = re.sub(
                        pattern, "", transposed_image.info["XML:com.adobe.xmp"]
                    )
        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:** ImageOps.contain and ImageOps.pad produce incorrect image dimensions and padding positions

**Description:**

When using the `ImageOps.contain` and `ImageOps.pad` functions to resize or pad images, the resulting image dimensions and padding positions are incorrectly calculated in certain scenarios.

**Example Buggy Code:**

```python
from PIL import Image, ImageOps

def resize_image():
    im = Image.new("1", (43, 63), 1)
    new_im = ImageOps.contain(im, (5, 7))
    print(new_im.width)  # Expected: 5, but got: 4

def pad_image():
    im = Image.new("1", (1, 1), 1)
    new_im = ImageOps.pad(im, (4, 1))
    pixels = new_im.load()
    print(pixels[2, 0])  # Expected: 1, but got: 0
```

**Expected Behavior:**

- **`ImageOps.contain`:** The resized image should have the exact dimensions specified (e.g., width of 5 and height of 7).
- **`ImageOps.pad`:** The padding should be correctly applied, ensuring that the specified pixel positions retain the expected values (e.g., pixel at position (2, 0) should be 1).

**Actual Behavior:**

- **`ImageOps.contain`:** The resized image has an incorrect width of 4 instead of the expected 5.
- **`ImageOps.pad`:** The padding results in unexpected pixel values, with the pixel at position (2, 0) being 0 instead of the expected 1.

[/ISSUE]
{
    "\u001b[1mtest_sanity\u001b[0m": "PASSED",
    "\u001b[1mtest_1pxfit\u001b[0m": "PASSED",
    "\u001b[1mtest_fit_same_ratio\u001b[0m": "PASSED",
    "\u001b[1mtest_contain[new_size0]\u001b[0m": "PASSED",
    "\u001b[1mtest_contain[new_size1]\u001b[0m": "PASSED",
    "\u001b[1mtest_contain[new_size2]\u001b[0m": "PASSED",
    "\u001b[1mtest_contain_round\u001b[0m": "PASSED",
    "\u001b[1mtest_pad\u001b[0m": "PASSED",
    "\u001b[1mtest_pad_round\u001b[0m": "PASSED",
    "\u001b[1mtest_pil163\u001b[0m": "PASSED",
    "\u001b[1mtest_scale\u001b[0m": "PASSED",
    "\u001b[1mtest_expand_palette[10]\u001b[0m": "PASSED",
    "\u001b[1mtest_expand_palette[border1]\u001b[0m": "PASSED",
    "\u001b[1mtest_colorize_2color\u001b[0m": "PASSED",
    "\u001b[1mtest_colorize_2color_offset\u001b[0m": "PASSED",
    "\u001b[1mtest_colorize_3color_offset\u001b[0m": "PASSED",
    "\u001b[1mtest_exif_transpose\u001b[0m": "PASSED",
    "\u001b[1mtest_autocontrast_cutoff\u001b[0m": "PASSED",
    "\u001b[1mtest_autocontrast_mask_toy_input\u001b[0m": "PASSED",
    "\u001b[1mtest_autocontrast_mask_real_input\u001b[0m": "PASSED",
    "\u001b[1mtest_autocontrast_preserve_tone\u001b[0m": "PASSED",
    "\u001b[1mtest_autocontrast_preserve_gradient\u001b[0m": "PASSED",
    "\u001b[1mtest_autocontrast_preserve_one_color[color0]\u001b[0m": "PASSED",
    "\u001b[1mtest_autocontrast_preserve_one_color[color1]\u001b[0m": "PASSED",
    "\u001b[1mtest_autocontrast_preserve_one_color[color2]\u001b[0m": "PASSED",
    "\u001b[1mtest_autocontrast_preserve_one_color[color3]\u001b[0m": "PASSED"
}
diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py
index 0c3f900ca..ae43fc3bd 100644
--- a/src/PIL/ImageOps.py
+++ b/src/PIL/ImageOps.py
@@ -255,11 +255,11 @@ def contain(image, size, method=Image.Resampling.BICUBIC):
 
     if im_ratio != dest_ratio:
         if im_ratio > dest_ratio:
-            new_height = int(image.height / image.width * size[0])
+            new_height = round(image.height / image.width * size[0])
             if new_height != size[1]:
                 size = (size[0], new_height)
         else:
-            new_width = int(image.width / image.height * size[1])
+            new_width = round(image.width / image.height * size[1])
             if new_width != size[0]:
                 size = (new_width, size[1])
     return image.resize(size, resample=method)
@@ -292,10 +292,10 @@ def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5
     else:
         out = Image.new(image.mode, size, color)
         if resized.width != size[0]:
-            x = int((size[0] - resized.width) * max(0, min(centering[0], 1)))
+            x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
             out.paste(resized, (x, 0))
         else:
-            y = int((size[1] - resized.height) * max(0, min(centering[1], 1)))
+            y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
             out.paste(resized, (0, y))
     return out
 
 

{"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\nimport functools\nimport operator\nimport re\n\nfrom . import Image\n\n#\n# helpers\n\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 isinstance(color, str):\n        from . import ImageColor\n\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 OSError(\"not supported for this image mode\")\n\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None, mask=None, preserve_tone=False):\n    \"\"\"\n    Maximize (normalize) image contrast. This function calculates a\n    histogram of the input image (or mask region), 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: The percent to cut off from the histogram on the low and\n                   high ends. Either a tuple of (low, high), or a single\n                   number for both.\n    :param ignore: The background pixel value (use None for no background).\n    :param mask: Histogram used in contrast operation is computed using pixels\n                 within the mask. If no mask is given the entire image is used\n                 for histogram computation.\n    :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.\n\n                          .. versionadded:: 8.2.0\n\n    :return: An image.\n    \"\"\"\n    if preserve_tone:\n        histogram = image.convert(\"L\").histogram(mask)\n    else:\n        histogram = image.histogram(mask)\n\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            if not isinstance(cutoff, tuple):\n                cutoff = (cutoff, cutoff)\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[0] // 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 high end\n            cut = n * cutoff[1] // 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, 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 contain(image, size, method=Image.Resampling.BICUBIC):\n    \"\"\"\n    Returns a resized version of the image, set to the maximum width and height\n    within the requested size, while maintaining the original aspect ratio.\n\n    :param image: The image to resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\n    :return: An image.\n    \"\"\"\n\n    im_ratio = image.width / image.height\n    dest_ratio = size[0] / size[1]\n\n    if im_ratio != dest_ratio:\n        if im_ratio > dest_ratio:\n            new_height = int(image.height / image.width * size[0])\n            if new_height != size[1]:\n                size = (size[0], new_height)\n        else:\n            new_width = int(image.width / image.height * size[1])\n            if new_width != size[0]:\n                size = (new_width, size[1])\n    return image.resize(size, resample=method)\n\n\ndef pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a resized and padded version of the image, expanded to fill the\n    requested aspect ratio and size.\n\n    :param image: The image to resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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\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    resized = contain(image, size, method)\n    if resized.size == size:\n        out = resized\n    else:\n        out = Image.new(image.mode, size, color)\n        if resized.width != size[0]:\n            x = int((size[0] - resized.width) * max(0, min(centering[0], 1)))\n            out.paste(resized, (x, 0))\n        else:\n            y = int((size[1] - resized.height) * max(0, min(centering[1], 1)))\n            out.paste(resized, (0, y))\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((left, top, image.size[0] - right, image.size[1] - bottom))\n\n\ndef scale(image, factor, resample=Image.Resampling.BICUBIC):\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: Resampling method to use. Default is\n                     :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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 = (round(factor * image.width), round(factor * image.height))\n        return image.resize(size, resample)\n\n\ndef deform(image, deformer, resample=Image.Resampling.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.Transform.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    color = _color(fill, image.mode)\n    if image.mode == \"P\" and image.palette:\n        image.load()\n        palette = image.palette.copy()\n        if isinstance(color, tuple):\n            color = palette.getcolor(color)\n    else:\n        palette = None\n    out = Image.new(image.mode, (width, height), color)\n    if palette:\n        out.putpalette(palette.palette)\n    out.paste(image, (left, top))\n    return out\n\n\ndef fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a resized 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 resize and crop.\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: Resampling method to use. Default is\n                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.\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    # https://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 = (\n        image.size[0] - bleed_pixels[0] * 2,\n        image.size[1] - bleed_pixels[1] * 2,\n    )\n\n    # calculate the aspect ratio of the live_size\n    live_size_ratio = live_size[0] / live_size[1]\n\n    # calculate the aspect ratio of the output image\n    output_ratio = 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 already the needed ratio\n        crop_width = live_size[0]\n        crop_height = live_size[1]\n    elif 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 = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)\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.Transpose.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 image.point(lut) if image.mode == \"1\" else _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.Transpose.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, other than 1, return a new image\n    that is transposed accordingly. The new image will have the orientation\n    data removed.\n\n    Otherwise, return a copy of the image.\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    exif = image.getexif()\n    orientation = exif.get(0x0112)\n    method = {\n        2: Image.Transpose.FLIP_LEFT_RIGHT,\n        3: Image.Transpose.ROTATE_180,\n        4: Image.Transpose.FLIP_TOP_BOTTOM,\n        5: Image.Transpose.TRANSPOSE,\n        6: Image.Transpose.ROTATE_270,\n        7: Image.Transpose.TRANSVERSE,\n        8: Image.Transpose.ROTATE_90,\n    }.get(orientation)\n    if method is not None:\n        transposed_image = image.transpose(method)\n        transposed_exif = transposed_image.getexif()\n        if 0x0112 in transposed_exif:\n            del transposed_exif[0x0112]\n            if \"exif\" in transposed_image.info:\n                transposed_image.info[\"exif\"] = transposed_exif.tobytes()\n            elif \"Raw profile type exif\" in transposed_image.info:\n                transposed_image.info[\n                    \"Raw profile type exif\"\n                ] = transposed_exif.tobytes().hex()\n            elif \"XML:com.adobe.xmp\" in transposed_image.info:\n                for pattern in (\n                    r'tiff:Orientation=\"([0-9])\"',\n                    r\"<tiff:Orientation>([0-9])</tiff:Orientation>\",\n                ):\n                    transposed_image.info[\"XML:com.adobe.xmp\"] = re.sub(\n                        pattern, \"\", transposed_image.info[\"XML:com.adobe.xmp\"]\n                    )\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:** ImageOps.contain and ImageOps.pad produce incorrect image dimensions and padding positions

**Description:**

When using the `ImageOps.contain` and `ImageOps.pad` functions to resize or pad images, the resulting image dimensions and padding positions are incorrectly calculated in certain scenarios.

**Example Buggy Code:**

```python
from PIL import Image, ImageOps

def resize_image():
    im = Image.new("1", (43, 63), 1)
    new_im = ImageOps.contain(im, (5, 7))
    print(new_im.width)  # Expected: 5, but got: 4

def pad_image():
    im = Image.new("1", (1, 1), 1)
    new_im = ImageOps.pad(im, (4, 1))
    pixels = new_im.load()
    print(pixels[2, 0])  # Expected: 1, but got: 0
```

**Expected Behavior:**

- **`ImageOps.contain`:** The resized image should have the exact dimensions specified (e.g., width of 5 and height of 7).
- **`ImageOps.pad`:** The padding should be correctly applied, ensuring that the specified pixel positions retain the expected values (e.g., pixel at position (2, 0) should be 1).

**Actual Behavior:**

- **`ImageOps.contain`:** The resized image has an incorrect width of 4 instead of the expected 5.
- **`ImageOps.pad`:** The padding results in unexpected pixel values, with the pixel at position (2, 0) being 0 instead of the expected 1.

[/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.
#

import functools
import operator
import re

from . import Image

#
# 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 isinstance(color, str):
        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 OSError("not supported for this image mode")


#
# actions


def autocontrast(image, cutoff=0, ignore=None, mask=None, preserve_tone=False):
    """
    Maximize (normalize) image contrast. This function calculates a
    histogram of the input image (or mask region), 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: The percent to cut off from the histogram on the low and
                   high ends. Either a tuple of (low, high), or a single
                   number for both.
    :param ignore: The background pixel value (use None for no background).
    :param mask: Histogram used in contrast operation is computed using pixels
                 within the mask. If no mask is given the entire image is used
                 for histogram computation.
    :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.

                          .. versionadded:: 8.2.0

    :return: An image.
    """
    if preserve_tone:
        histogram = image.convert("L").histogram(mask)
    else:
        histogram = image.histogram(mask)

    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
            if not isinstance(cutoff, tuple):
                cutoff = (cutoff, cutoff)
            # 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[0] // 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 high end
            cut = n * cutoff[1] // 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 contain(image, size, method=Image.Resampling.BICUBIC):
    """
    Returns a resized version of the image, set to the maximum width and height
    within the requested size, while maintaining the original aspect ratio.

    :param image: The image to resize and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: Resampling method to use. Default is
                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
    :return: An image.
    """

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

    if im_ratio != dest_ratio:
        if im_ratio > dest_ratio:
            new_height = int(image.height / image.width * size[0])
            if new_height != size[1]:
                size = (size[0], new_height)
        else:
            new_width = int(image.width / image.height * size[1])
            if new_width != size[0]:
                size = (new_width, size[1])
    return image.resize(size, resample=method)


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

    :param image: The image to resize and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: Resampling method to use. Default is
                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
    :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.
    """

    resized = contain(image, size, method)
    if resized.size == size:
        out = resized
    else:
        out = Image.new(image.mode, size, color)
        if resized.width != size[0]:
            x = int((size[0] - resized.width) * max(0, min(centering[0], 1)))
            out.paste(resized, (x, 0))
        else:
            y = int((size[1] - resized.height) * max(0, min(centering[1], 1)))
            out.paste(resized, (0, y))
    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.Resampling.BICUBIC):
    """
    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: Resampling method to use. Default is
                     :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
    :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 = (round(factor * image.width), round(factor * image.height))
        return image.resize(size, resample)


def deform(image, deformer, resample=Image.Resampling.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.Transform.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
    color = _color(fill, image.mode)
    if image.mode == "P" and image.palette:
        image.load()
        palette = image.palette.copy()
        if isinstance(color, tuple):
            color = palette.getcolor(color)
    else:
        palette = None
    out = Image.new(image.mode, (width, height), color)
    if palette:
        out.putpalette(palette.palette)
    out.paste(image, (left, top))
    return out


def fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5, 0.5)):
    """
    Returns a resized 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 resize and crop.
    :param size: The requested output size in pixels, given as a
                 (width, height) tuple.
    :param method: Resampling method to use. Default is
                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
    :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
    # https://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 = live_size[0] / live_size[1]

    # calculate the aspect ratio of the output image
    output_ratio = 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 already the needed ratio
        crop_width = live_size[0]
        crop_height = live_size[1]
    elif 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.Transpose.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 image.point(lut) if image.mode == "1" else _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.Transpose.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, other than 1, return a new image
    that is transposed accordingly. The new image will have the orientation
    data removed.

    Otherwise, return a copy of the image.

    :param image: The image to transpose.
    :return: An image.
    """
    exif = image.getexif()
    orientation = exif.get(0x0112)
    method = {
        2: Image.Transpose.FLIP_LEFT_RIGHT,
        3: Image.Transpose.ROTATE_180,
        4: Image.Transpose.FLIP_TOP_BOTTOM,
        5: Image.Transpose.TRANSPOSE,
        6: Image.Transpose.ROTATE_270,
        7: Image.Transpose.TRANSVERSE,
        8: Image.Transpose.ROTATE_90,
    }.get(orientation)
    if method is not None:
        transposed_image = image.transpose(method)
        transposed_exif = transposed_image.getexif()
        if 0x0112 in transposed_exif:
            del transposed_exif[0x0112]
            if "exif" in transposed_image.info:
                transposed_image.info["exif"] = transposed_exif.tobytes()
            elif "Raw profile type exif" in transposed_image.info:
                transposed_image.info[
                    "Raw profile type exif"
                ] = transposed_exif.tobytes().hex()
            elif "XML:com.adobe.xmp" in transposed_image.info:
                for pattern in (
                    r'tiff:Orientation="([0-9])"',
                    r"<tiff:Orientation>([0-9])</tiff:Orientation>",
                ):
                    transposed_image.info["XML:com.adobe.xmp"] = re.sub(
                        pattern, "", transposed_image.info["XML:com.adobe.xmp"]
                    )
        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