{
    "file_diffs": [
        {
            "old_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# standard image operations\n#\n# History:\n# 2001-10-20 fl   Created\n# 2001-10-23 fl   Added autocontrast operator\n# 2001-12-18 fl   Added Kevin's fit operator\n# 2004-03-14 fl   Fixed potential division by zero in equalize\n# 2005-05-05 fl   Fixed equalize for low number of values\n#\n# Copyright (c) 2001-2004 by Secret Labs AB\n# Copyright (c) 2001-2004 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom PIL import Image\nfrom PIL._util import isStringType\nimport operator\nimport functools\n\n\n#\n# helpers\n\ndef _border(border):\n    if isinstance(border, tuple):\n        if len(border) == 2:\n            left, top = right, bottom = border\n        elif len(border) == 4:\n            left, top, right, bottom = border\n    else:\n        left = top = right = bottom = border\n    return left, top, right, bottom\n\n\ndef _color(color, mode):\n    if isStringType(color):\n        from PIL import ImageColor\n        color = ImageColor.getcolor(color, mode)\n    return color\n\n\ndef _lut(image, lut):\n    if image.mode == \"P\":\n        # FIXME: apply to lookup table, not image data\n        raise NotImplementedError(\"mode P support coming soon\")\n    elif image.mode in (\"L\", \"RGB\"):\n        if image.mode == \"RGB\" and len(lut) == 256:\n            lut = lut + lut + lut\n        return image.point(lut)\n    else:\n        raise IOError(\"not supported for this image mode\")\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None):\n    \"\"\"\n    Maximize (normalize) image contrast. This function calculates a\n    histogram of the input image, removes **cutoff** percent of the\n    lightest and darkest pixels from the histogram, and remaps the image\n    so that the darkest pixel becomes black (0), and the lightest\n    becomes white (255).\n\n    :param image: The image to process.\n    :param cutoff: How many percent to cut off from the histogram.\n    :param ignore: The background pixel value (use None for no background).\n    :return: An image.\n    \"\"\"\n    histogram = image.histogram()\n    lut = []\n    for layer in range(0, len(histogram), 256):\n        h = histogram[layer:layer+256]\n        if ignore is not None:\n            # get rid of outliers\n            try:\n                h[ignore] = 0\n            except TypeError:\n                # assume sequence\n                for ix in ignore:\n                    h[ix] = 0\n        if cutoff:\n            # cut off pixels from both ends of the histogram\n            # get number of pixels\n            n = 0\n            for ix in range(256):\n                n = n + h[ix]\n            # remove cutoff% pixels from the low end\n            cut = n * cutoff // 100\n            for lo in range(256):\n                if cut > h[lo]:\n                    cut = cut - h[lo]\n                    h[lo] = 0\n                else:\n                    h[lo] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n            # remove cutoff% samples from the hi end\n            cut = n * cutoff // 100\n            for hi in range(255, -1, -1):\n                if cut > h[hi]:\n                    cut = cut - h[hi]\n                    h[hi] = 0\n                else:\n                    h[hi] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n        # find lowest/highest samples after preprocessing\n        for lo in range(256):\n            if h[lo]:\n                break\n        for hi in range(255, -1, -1):\n            if h[hi]:\n                break\n        if hi <= lo:\n            # don't bother\n            lut.extend(list(range(256)))\n        else:\n            scale = 255.0 / (hi - lo)\n            offset = -lo * scale\n            for ix in range(256):\n                ix = int(ix * scale + offset)\n                if ix < 0:\n                    ix = 0\n                elif ix > 255:\n                    ix = 255\n                lut.append(ix)\n    return _lut(image, lut)\n\n\ndef colorize(image, black, white):\n    \"\"\"\n    Colorize grayscale image.  The **black** and **white**\n    arguments should be RGB tuples; this function calculates a color\n    wedge mapping all black pixels in the source image to the first\n    color, and all white pixels to the second color.\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    :return: An image.\n    \"\"\"\n    assert image.mode == \"L\"\n    black = _color(black, \"RGB\")\n    white = _color(white, \"RGB\")\n    red = []\n    green = []\n    blue = []\n    for i in range(256):\n        red.append(black[0]+i*(white[0]-black[0])//255)\n        green.append(black[1]+i*(white[1]-black[1])//255)\n        blue.append(black[2]+i*(white[2]-black[2])//255)\n    image = image.convert(\"RGB\")\n    return _lut(image, red + green + blue)\n\n\ndef crop(image, border=0):\n    \"\"\"\n    Remove border from image.  The same amount of pixels are removed\n    from all four sides.  This function works on all image modes.\n\n    .. seealso:: :py:meth:`~PIL.Image.Image.crop`\n\n    :param image: The image to crop.\n    :param border: The number of pixels to remove.\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    return image.crop(\n        (left, top, image.size[0]-right, image.size[1]-bottom)\n        )\n\n\ndef deform(image, deformer, resample=Image.BILINEAR):\n    \"\"\"\n    Deform the image.\n\n    :param image: The image to deform.\n    :param deformer: A deformer object.  Any object that implements a\n                    **getmesh** method can be used.\n    :param resample: What resampling filter to use.\n    :return: An image.\n    \"\"\"\n    return image.transform(\n        image.size, Image.MESH, deformer.getmesh(image), resample\n        )\n\n\ndef equalize(image, mask=None):\n    \"\"\"\n    Equalize the image histogram. This function applies a non-linear\n    mapping to the input image, in order to create a uniform\n    distribution of grayscale values in the output image.\n\n    :param image: The image to equalize.\n    :param mask: An optional mask.  If given, only the pixels selected by\n                 the mask are included in the analysis.\n    :return: An image.\n    \"\"\"\n    if image.mode == \"P\":\n        image = image.convert(\"RGB\")\n    h = image.histogram(mask)\n    lut = []\n    for b in range(0, len(h), 256):\n        histo = [_f for _f in h[b:b+256] if _f]\n        if len(histo) <= 1:\n            lut.extend(list(range(256)))\n        else:\n            step = (functools.reduce(operator.add, histo) - histo[-1]) // 255\n            if not step:\n                lut.extend(list(range(256)))\n            else:\n                n = step // 2\n                for i in range(256):\n                    lut.append(n // step)\n                    n = n + h[i+b]\n    return _lut(image, lut)\n\n\ndef expand(image, border=0, fill=0):\n    \"\"\"\n    Add border to the image\n\n    :param image: The image to expand.\n    :param border: Border width, in pixels.\n    :param fill: Pixel fill value (a color value).  Default is 0 (black).\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    width = left + image.size[0] + right\n    height = top + image.size[1] + bottom\n    out = Image.new(image.mode, (width, height), _color(fill, image.mode))\n    out.paste(image, (left, top))\n    return out\n\n\ndef fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a sized and cropped version of the image, cropped to the\n    requested aspect ratio and size.\n\n    This function was contributed by Kevin Cazabon.\n\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: What resampling method to use. Default is\n                   :py:attr:`PIL.Image.NEAREST`.\n    :param bleed: Remove a border around the outside of the image (from all\n                  four edges. The value is a decimal percentage (use 0.01 for\n                  one percent). The default value is 0 (no border).\n    :param centering: Control the cropping position.  Use (0.5, 0.5) for\n                      center cropping (e.g. if cropping the width, take 50% off\n                      of the left side, and therefore 50% off the right side).\n                      (0.0, 0.0) will crop from the top left corner (i.e. if\n                      cropping the width, take all of the crop off of the right\n                      side, and if cropping the height, take all of it off the\n                      bottom).  (1.0, 0.0) will crop from the bottom left\n                      corner, etc. (i.e. if cropping the width, take all of the\n                      crop off the left side, and if cropping the height take\n                      none from the top, and therefore all off the bottom).\n    :return: An image.\n    \"\"\"\n\n    # by Kevin Cazabon, Feb 17/2000\n    # kevin@cazabon.com\n    # http://www.cazabon.com\n\n    # ensure inputs are valid\n    if not isinstance(centering, list):\n        centering = [centering[0], centering[1]]\n\n    if centering[0] > 1.0 or centering[0] < 0.0:\n        centering[0] = 0.50\n    if centering[1] > 1.0 or centering[1] < 0.0:\n        centering[1] = 0.50\n\n    if bleed > 0.49999 or bleed < 0.0:\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    bleedPixels = (\n        int((float(bleed) * float(image.size[0])) + 0.5),\n        int((float(bleed) * float(image.size[1])) + 0.5)\n        )\n\n    liveArea = (0, 0, image.size[0], image.size[1])\n    if bleed > 0.0:\n        liveArea = (\n            bleedPixels[0], bleedPixels[1], image.size[0] - bleedPixels[0] - 1,\n            image.size[1] - bleedPixels[1] - 1\n            )\n\n    liveSize = (liveArea[2] - liveArea[0], liveArea[3] - liveArea[1])\n\n    # calculate the aspect ratio of the liveArea\n    liveAreaAspectRatio = float(liveSize[0])/float(liveSize[1])\n\n    # calculate the aspect ratio of the output image\n    aspectRatio = float(size[0]) / float(size[1])\n\n    # figure out if the sides or top/bottom will be cropped off\n    if liveAreaAspectRatio >= aspectRatio:\n        # liveArea is wider than what's needed, crop the sides\n        cropWidth = int((aspectRatio * float(liveSize[1])) + 0.5)\n        cropHeight = liveSize[1]\n    else:\n        # liveArea is taller than what's needed, crop the top and bottom\n        cropWidth = liveSize[0]\n        cropHeight = int((float(liveSize[0])/aspectRatio) + 0.5)\n\n    # make the crop\n    leftSide = int(liveArea[0] + (float(liveSize[0]-cropWidth) * centering[0]))\n    if leftSide < 0:\n        leftSide = 0\n    topSide = int(liveArea[1] + (float(liveSize[1]-cropHeight) * centering[1]))\n    if topSide < 0:\n        topSide = 0\n\n    out = image.crop(\n        (leftSide, topSide, leftSide + cropWidth, topSide + cropHeight)\n        )\n\n    # resize the image and return it\n    return out.resize(size, method)\n\n\ndef flip(image):\n    \"\"\"\n    Flip the image vertically (top to bottom).\n\n    :param image: The image to flip.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_TOP_BOTTOM)\n\n\ndef grayscale(image):\n    \"\"\"\n    Convert the image to grayscale.\n\n    :param image: The image to convert.\n    :return: An image.\n    \"\"\"\n    return image.convert(\"L\")\n\n\ndef invert(image):\n    \"\"\"\n    Invert (negate) the image.\n\n    :param image: The image to invert.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        lut.append(255-i)\n    return _lut(image, lut)\n\n\ndef mirror(image):\n    \"\"\"\n    Flip image horizontally (left to right).\n\n    :param image: The image to mirror.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_LEFT_RIGHT)\n\n\ndef posterize(image, bits):\n    \"\"\"\n    Reduce the number of bits for each color channel.\n\n    :param image: The image to posterize.\n    :param bits: The number of bits to keep for each channel (1-8).\n    :return: An image.\n    \"\"\"\n    lut = []\n    mask = ~(2**(8-bits)-1)\n    for i in range(256):\n        lut.append(i & mask)\n    return _lut(image, lut)\n\n\ndef solarize(image, threshold=128):\n    \"\"\"\n    Invert all pixel values above a threshold.\n\n    :param image: The image to solarize.\n    :param threshold: All pixels above this greyscale level are inverted.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        if i < threshold:\n            lut.append(i)\n        else:\n            lut.append(255-i)\n    return _lut(image, lut)\n\n\n# --------------------------------------------------------------------\n# PIL USM components, from Kevin Cazabon.\n\ndef gaussian_blur(im, radius=None):\n    \"\"\" PIL_usm.gblur(im, [radius])\"\"\"\n\n    if radius is None:\n        radius = 5.0\n\n    im.load()\n\n    return im.im.gaussian_blur(radius)\n\ngblur = gaussian_blur\n\n\ndef unsharp_mask(im, radius=None, percent=None, threshold=None):\n    \"\"\" PIL_usm.usm(im, [radius, percent, threshold])\"\"\"\n\n    if radius is None:\n        radius = 5.0\n    if percent is None:\n        percent = 150\n    if threshold is None:\n        threshold = 3\n\n    im.load()\n\n    return im.im.unsharp_mask(radius, percent, threshold)\n\nusm = unsharp_mask\n\n\ndef box_blur(image, radius):\n    \"\"\"\n    Blur the image by setting each pixel to the average value of the pixels\n    in a square box extending radius pixels in each direction.\n    Supports float radius of arbitrary size. Uses an optimized implementation\n    which runs in linear time relative to the size of the image\n    for any radius value.\n\n    :param image: The image to blur.\n    :param radius: Size of the box in one direction. Radius 0 does not blur,\n                   returns an identical image. Radius 1 takes 1 pixel\n                   in each direction, i.e. 9 pixels in total.\n    :return: An image.\n    \"\"\"\n    image.load()\n\n    return image._new(image.im.box_blur(radius))\n",
            "new_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# standard image operations\n#\n# History:\n# 2001-10-20 fl   Created\n# 2001-10-23 fl   Added autocontrast operator\n# 2001-12-18 fl   Added Kevin's fit operator\n# 2004-03-14 fl   Fixed potential division by zero in equalize\n# 2005-05-05 fl   Fixed equalize for low number of values\n#\n# Copyright (c) 2001-2004 by Secret Labs AB\n# Copyright (c) 2001-2004 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom PIL import Image\nfrom PIL._util import isStringType\nimport operator\nimport functools\n\n\n#\n# helpers\n\ndef _border(border):\n    if isinstance(border, tuple):\n        if len(border) == 2:\n            left, top = right, bottom = border\n        elif len(border) == 4:\n            left, top, right, bottom = border\n    else:\n        left = top = right = bottom = border\n    return left, top, right, bottom\n\n\ndef _color(color, mode):\n    if isStringType(color):\n        from PIL import ImageColor\n        color = ImageColor.getcolor(color, mode)\n    return color\n\n\ndef _lut(image, lut):\n    if image.mode == \"P\":\n        # FIXME: apply to lookup table, not image data\n        raise NotImplementedError(\"mode P support coming soon\")\n    elif image.mode in (\"L\", \"RGB\"):\n        if image.mode == \"RGB\" and len(lut) == 256:\n            lut = lut + lut + lut\n        return image.point(lut)\n    else:\n        raise IOError(\"not supported for this image mode\")\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None):\n    \"\"\"\n    Maximize (normalize) image contrast. This function calculates a\n    histogram of the input image, removes **cutoff** percent of the\n    lightest and darkest pixels from the histogram, and remaps the image\n    so that the darkest pixel becomes black (0), and the lightest\n    becomes white (255).\n\n    :param image: The image to process.\n    :param cutoff: How many percent to cut off from the histogram.\n    :param ignore: The background pixel value (use None for no background).\n    :return: An image.\n    \"\"\"\n    histogram = image.histogram()\n    lut = []\n    for layer in range(0, len(histogram), 256):\n        h = histogram[layer:layer+256]\n        if ignore is not None:\n            # get rid of outliers\n            try:\n                h[ignore] = 0\n            except TypeError:\n                # assume sequence\n                for ix in ignore:\n                    h[ix] = 0\n        if cutoff:\n            # cut off pixels from both ends of the histogram\n            # get number of pixels\n            n = 0\n            for ix in range(256):\n                n = n + h[ix]\n            # remove cutoff% pixels from the low end\n            cut = n * cutoff // 100\n            for lo in range(256):\n                if cut > h[lo]:\n                    cut = cut - h[lo]\n                    h[lo] = 0\n                else:\n                    h[lo] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n            # remove cutoff% samples from the hi end\n            cut = n * cutoff // 100\n            for hi in range(255, -1, -1):\n                if cut > h[hi]:\n                    cut = cut - h[hi]\n                    h[hi] = 0\n                else:\n                    h[hi] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n        # find lowest/highest samples after preprocessing\n        for lo in range(256):\n            if h[lo]:\n                break\n        for hi in range(255, -1, -1):\n            if h[hi]:\n                break\n        if hi <= lo:\n            # don't bother\n            lut.extend(list(range(256)))\n        else:\n            scale = 255.0 / (hi - lo)\n            offset = -lo * scale\n            for ix in range(256):\n                ix = int(ix * scale + offset)\n                if ix < 0:\n                    ix = 0\n                elif ix > 255:\n                    ix = 255\n                lut.append(ix)\n    return _lut(image, lut)\n\n\ndef colorize(image, black, white):\n    \"\"\"\n    Colorize grayscale image.  The **black** and **white**\n    arguments should be RGB tuples; this function calculates a color\n    wedge mapping all black pixels in the source image to the first\n    color, and all white pixels to the second color.\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    :return: An image.\n    \"\"\"\n    assert image.mode == \"L\"\n    black = _color(black, \"RGB\")\n    white = _color(white, \"RGB\")\n    red = []\n    green = []\n    blue = []\n    for i in range(256):\n        red.append(black[0]+i*(white[0]-black[0])//255)\n        green.append(black[1]+i*(white[1]-black[1])//255)\n        blue.append(black[2]+i*(white[2]-black[2])//255)\n    image = image.convert(\"RGB\")\n    return _lut(image, red + green + blue)\n\n\ndef crop(image, border=0):\n    \"\"\"\n    Remove border from image.  The same amount of pixels are removed\n    from all four sides.  This function works on all image modes.\n\n    .. seealso:: :py:meth:`~PIL.Image.Image.crop`\n\n    :param image: The image to crop.\n    :param border: The number of pixels to remove.\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    return image.crop(\n        (left, top, image.size[0]-right, image.size[1]-bottom)\n        )\n\n\ndef scale(image, factor, resample=Image.NEAREST):\n    \"\"\"\n    Returns a rescaled image by a specific factor given in parameter.\n    A factor greater than 1 expands the image, between 0 and 1 contracts the\n    image.\n\n    :param factor: The expansion factor, as a float.\n    :param resample: An optional resampling filter. Same values possible as\n       in the PIL.Image.resize function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n    if factor == 1:\n        return image.copy()\n    elif factor <= 0:\n        raise ValueError(\"the factor must be greater than 0\")\n    else:\n        size = (int(round(factor * image.width)),\n                int(round(factor * image.height)))\n        return image.resize(size, resample)\n\n\ndef deform(image, deformer, resample=Image.BILINEAR):\n    \"\"\"\n    Deform the image.\n\n    :param image: The image to deform.\n    :param deformer: A deformer object.  Any object that implements a\n                    **getmesh** method can be used.\n    :param resample: What resampling filter to use.\n    :return: An image.\n    \"\"\"\n    return image.transform(\n        image.size, Image.MESH, deformer.getmesh(image), resample\n        )\n\n\ndef equalize(image, mask=None):\n    \"\"\"\n    Equalize the image histogram. This function applies a non-linear\n    mapping to the input image, in order to create a uniform\n    distribution of grayscale values in the output image.\n\n    :param image: The image to equalize.\n    :param mask: An optional mask.  If given, only the pixels selected by\n                 the mask are included in the analysis.\n    :return: An image.\n    \"\"\"\n    if image.mode == \"P\":\n        image = image.convert(\"RGB\")\n    h = image.histogram(mask)\n    lut = []\n    for b in range(0, len(h), 256):\n        histo = [_f for _f in h[b:b+256] if _f]\n        if len(histo) <= 1:\n            lut.extend(list(range(256)))\n        else:\n            step = (functools.reduce(operator.add, histo) - histo[-1]) // 255\n            if not step:\n                lut.extend(list(range(256)))\n            else:\n                n = step // 2\n                for i in range(256):\n                    lut.append(n // step)\n                    n = n + h[i+b]\n    return _lut(image, lut)\n\n\ndef expand(image, border=0, fill=0):\n    \"\"\"\n    Add border to the image\n\n    :param image: The image to expand.\n    :param border: Border width, in pixels.\n    :param fill: Pixel fill value (a color value).  Default is 0 (black).\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    width = left + image.size[0] + right\n    height = top + image.size[1] + bottom\n    out = Image.new(image.mode, (width, height), _color(fill, image.mode))\n    out.paste(image, (left, top))\n    return out\n\n\ndef fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a sized and cropped version of the image, cropped to the\n    requested aspect ratio and size.\n\n    This function was contributed by Kevin Cazabon.\n\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: What resampling method to use. Default is\n                   :py:attr:`PIL.Image.NEAREST`.\n    :param bleed: Remove a border around the outside of the image (from all\n                  four edges. The value is a decimal percentage (use 0.01 for\n                  one percent). The default value is 0 (no border).\n    :param centering: Control the cropping position.  Use (0.5, 0.5) for\n                      center cropping (e.g. if cropping the width, take 50% off\n                      of the left side, and therefore 50% off the right side).\n                      (0.0, 0.0) will crop from the top left corner (i.e. if\n                      cropping the width, take all of the crop off of the right\n                      side, and if cropping the height, take all of it off the\n                      bottom).  (1.0, 0.0) will crop from the bottom left\n                      corner, etc. (i.e. if cropping the width, take all of the\n                      crop off the left side, and if cropping the height take\n                      none from the top, and therefore all off the bottom).\n    :return: An image.\n    \"\"\"\n\n    # by Kevin Cazabon, Feb 17/2000\n    # kevin@cazabon.com\n    # http://www.cazabon.com\n\n    # ensure inputs are valid\n    if not isinstance(centering, list):\n        centering = [centering[0], centering[1]]\n\n    if centering[0] > 1.0 or centering[0] < 0.0:\n        centering[0] = 0.50\n    if centering[1] > 1.0 or centering[1] < 0.0:\n        centering[1] = 0.50\n\n    if bleed > 0.49999 or bleed < 0.0:\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    bleedPixels = (\n        int((float(bleed) * float(image.size[0])) + 0.5),\n        int((float(bleed) * float(image.size[1])) + 0.5)\n        )\n\n    liveArea = (0, 0, image.size[0], image.size[1])\n    if bleed > 0.0:\n        liveArea = (\n            bleedPixels[0], bleedPixels[1], image.size[0] - bleedPixels[0] - 1,\n            image.size[1] - bleedPixels[1] - 1\n            )\n\n    liveSize = (liveArea[2] - liveArea[0], liveArea[3] - liveArea[1])\n\n    # calculate the aspect ratio of the liveArea\n    liveAreaAspectRatio = float(liveSize[0])/float(liveSize[1])\n\n    # calculate the aspect ratio of the output image\n    aspectRatio = float(size[0]) / float(size[1])\n\n    # figure out if the sides or top/bottom will be cropped off\n    if liveAreaAspectRatio >= aspectRatio:\n        # liveArea is wider than what's needed, crop the sides\n        cropWidth = int((aspectRatio * float(liveSize[1])) + 0.5)\n        cropHeight = liveSize[1]\n    else:\n        # liveArea is taller than what's needed, crop the top and bottom\n        cropWidth = liveSize[0]\n        cropHeight = int((float(liveSize[0])/aspectRatio) + 0.5)\n\n    # make the crop\n    leftSide = int(liveArea[0] + (float(liveSize[0]-cropWidth) * centering[0]))\n    if leftSide < 0:\n        leftSide = 0\n    topSide = int(liveArea[1] + (float(liveSize[1]-cropHeight) * centering[1]))\n    if topSide < 0:\n        topSide = 0\n\n    out = image.crop(\n        (leftSide, topSide, leftSide + cropWidth, topSide + cropHeight)\n        )\n\n    # resize the image and return it\n    return out.resize(size, method)\n\n\ndef flip(image):\n    \"\"\"\n    Flip the image vertically (top to bottom).\n\n    :param image: The image to flip.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_TOP_BOTTOM)\n\n\ndef grayscale(image):\n    \"\"\"\n    Convert the image to grayscale.\n\n    :param image: The image to convert.\n    :return: An image.\n    \"\"\"\n    return image.convert(\"L\")\n\n\ndef invert(image):\n    \"\"\"\n    Invert (negate) the image.\n\n    :param image: The image to invert.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        lut.append(255-i)\n    return _lut(image, lut)\n\n\ndef mirror(image):\n    \"\"\"\n    Flip image horizontally (left to right).\n\n    :param image: The image to mirror.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_LEFT_RIGHT)\n\n\ndef posterize(image, bits):\n    \"\"\"\n    Reduce the number of bits for each color channel.\n\n    :param image: The image to posterize.\n    :param bits: The number of bits to keep for each channel (1-8).\n    :return: An image.\n    \"\"\"\n    lut = []\n    mask = ~(2**(8-bits)-1)\n    for i in range(256):\n        lut.append(i & mask)\n    return _lut(image, lut)\n\n\ndef solarize(image, threshold=128):\n    \"\"\"\n    Invert all pixel values above a threshold.\n\n    :param image: The image to solarize.\n    :param threshold: All pixels above this greyscale level are inverted.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        if i < threshold:\n            lut.append(i)\n        else:\n            lut.append(255-i)\n    return _lut(image, lut)\n\n\n# --------------------------------------------------------------------\n# PIL USM components, from Kevin Cazabon.\n\ndef gaussian_blur(im, radius=None):\n    \"\"\" PIL_usm.gblur(im, [radius])\"\"\"\n\n    if radius is None:\n        radius = 5.0\n\n    im.load()\n\n    return im.im.gaussian_blur(radius)\n\ngblur = gaussian_blur\n\n\ndef unsharp_mask(im, radius=None, percent=None, threshold=None):\n    \"\"\" PIL_usm.usm(im, [radius, percent, threshold])\"\"\"\n\n    if radius is None:\n        radius = 5.0\n    if percent is None:\n        percent = 150\n    if threshold is None:\n        threshold = 3\n\n    im.load()\n\n    return im.im.unsharp_mask(radius, percent, threshold)\n\nusm = unsharp_mask\n\n\ndef box_blur(image, radius):\n    \"\"\"\n    Blur the image by setting each pixel to the average value of the pixels\n    in a square box extending radius pixels in each direction.\n    Supports float radius of arbitrary size. Uses an optimized implementation\n    which runs in linear time relative to the size of the image\n    for any radius value.\n\n    :param image: The image to blur.\n    :param radius: Size of the box in one direction. Radius 0 does not blur,\n                   returns an identical image. Radius 1 takes 1 pixel\n                   in each direction, i.e. 9 pixels in total.\n    :return: An image.\n    \"\"\"\n    image.load()\n\n    return image._new(image.im.box_blur(radius))\n",
            "header": {
                "file": {
                    "path": "PIL/ImageOps.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "f317645b2",
                "new_commit_hash": "8580ec5fb",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/PIL/ImageOps.py"
            },
            "plus_file": {
                "path": "b/PIL/ImageOps.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 178,
                            "length": 6
                        },
                        "new_range": {
                            "start": 178,
                            "length": 27
                        },
                        "section": "def crop(image, border=0):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        )",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def scale(image, factor, resample=Image.NEAREST):",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "    Returns a rescaled image by a specific factor given in parameter.",
                                "type": "added"
                            },
                            {
                                "content": "    A factor greater than 1 expands the image, between 0 and 1 contracts the",
                                "type": "added"
                            },
                            {
                                "content": "    image.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    :param factor: The expansion factor, as a float.",
                                "type": "added"
                            },
                            {
                                "content": "    :param resample: An optional resampling filter. Same values possible as",
                                "type": "added"
                            },
                            {
                                "content": "       in the PIL.Image.resize function.",
                                "type": "added"
                            },
                            {
                                "content": "    :returns: An :py:class:`~PIL.Image.Image` object.",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "    if factor == 1:",
                                "type": "added"
                            },
                            {
                                "content": "        return image.copy()",
                                "type": "added"
                            },
                            {
                                "content": "    elif factor <= 0:",
                                "type": "added"
                            },
                            {
                                "content": "        raise ValueError(\"the factor must be greater than 0\")",
                                "type": "added"
                            },
                            {
                                "content": "    else:",
                                "type": "added"
                            },
                            {
                                "content": "        size = (int(round(factor * image.width)),",
                                "type": "added"
                            },
                            {
                                "content": "                int(round(factor * image.height)))",
                                "type": "added"
                            },
                            {
                                "content": "        return image.resize(size, resample)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "def deform(image, deformer, resample=Image.BILINEAR):",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    Deform the image.",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "PIL/ImageOps.py",
                            "type": "function",
                            "name": "scale",
                            "content": "def scale(image, factor, resample=Image.NEAREST):\n    \"\"\"\n    Returns a rescaled image by a specific factor given in parameter.\n    A factor greater than 1 expands the image, between 0 and 1 contracts the\n    image.\n\n    :param factor: The expansion factor, as a float.\n    :param resample: An optional resampling filter. Same values possible as\n       in the PIL.Image.resize function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n    if factor == 1:\n        return image.copy()\n    elif factor <= 0:\n        raise ValueError(\"the factor must be greater than 0\")\n    else:\n        size = (int(round(factor * image.width)),\n                int(round(factor * image.height)))\n        return image.resize(size, resample)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 181,
                            "end_lineno": 199,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from helper import unittest, PillowTestCase, hopper\n\nfrom PIL import ImageOps\n\n\nclass TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "new_file_content": "from helper import unittest, PillowTestCase, hopper\n\nfrom PIL import ImageOps\n\n\nclass TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n        \n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Tests/test_imageops.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "18f077c65",
                "new_commit_hash": "3675e7b71",
                "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": 78,
                            "length": 6
                        },
                        "new_range": {
                            "start": 78,
                            "length": 22
                        },
                        "section": "class TestImageOps(PillowTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        ImageOps.equalize(i.convert(\"P\"))",
                                "type": "context"
                            },
                            {
                                "content": "        ImageOps.equalize(i.convert(\"RGB\"))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_scale(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # Test the scaling function",
                                "type": "added"
                            },
                            {
                                "content": "        i = hopper(\"L\").resize((50, 50))",
                                "type": "added"
                            },
                            {
                                "content": "        ",
                                "type": "added"
                            },
                            {
                                "content": "        with self.assertRaises(ValueError):",
                                "type": "added"
                            },
                            {
                                "content": "            ImageOps.scale(i, -1)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        newimg = ImageOps.scale(i, 1)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(newimg.size, (50, 50))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        newimg = ImageOps.scale(i, 2)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(newimg.size, (100, 100))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        newimg = ImageOps.scale(i, 0.5)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(newimg.size, (25, 25))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "if __name__ == '__main__':",
                                "type": "context"
                            },
                            {
                                "content": "    unittest.main()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_imageops.py",
                            "type": "class",
                            "name": "TestImageOps",
                            "content": "class TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n        \n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 6,
                            "end_lineno": 95,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Tests/test_imageops.py",
                            "type": "method",
                            "name": "TestImageOps.test_scale",
                            "content": "class TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n        \n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 81,
                            "end_lineno": 95,
                            "parent": {
                                "file_name": "Tests/test_imageops.py",
                                "type": "class",
                                "name": "TestImageOps",
                                "content": "class TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n        \n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 6,
                                "end_lineno": 95,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "ffa18c8efd38a40ed4aa49f0f8748c96b64527ad^",
    "new_commit_hash": "ffa18c8efd38a40ed4aa49f0f8748c96b64527ad",
    "commit_message": "Merge pull request #2011 from vlmath/master\n\nAdd ImageOps.scale to expand or contract a PIL image by a factor",
    "commit_date": "2016-08-06T22:19:50+01:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "ffa18c8efd38a40ed4aa49f0f8748c96b64527ad",
    "test_file_codes": [
        "from helper import unittest, PillowTestCase, hopper\n\nfrom PIL import ImageOps\n\n\nclass TestImageOps(PillowTestCase):\n\n    class Deformer(object):\n        def getmesh(self, im):\n            x, y = im.size\n            return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]\n\n    deformer = Deformer()\n\n    def test_sanity(self):\n\n        ImageOps.autocontrast(hopper(\"L\"))\n        ImageOps.autocontrast(hopper(\"RGB\"))\n\n        ImageOps.autocontrast(hopper(\"L\"), cutoff=10)\n        ImageOps.autocontrast(hopper(\"L\"), ignore=[0, 255])\n\n        ImageOps.colorize(hopper(\"L\"), (0, 0, 0), (255, 255, 255))\n        ImageOps.colorize(hopper(\"L\"), \"black\", \"white\")\n\n        ImageOps.crop(hopper(\"L\"), 1)\n        ImageOps.crop(hopper(\"RGB\"), 1)\n\n        ImageOps.deform(hopper(\"L\"), self.deformer)\n        ImageOps.deform(hopper(\"RGB\"), self.deformer)\n\n        ImageOps.equalize(hopper(\"L\"))\n        ImageOps.equalize(hopper(\"RGB\"))\n\n        ImageOps.expand(hopper(\"L\"), 1)\n        ImageOps.expand(hopper(\"RGB\"), 1)\n        ImageOps.expand(hopper(\"L\"), 2, \"blue\")\n        ImageOps.expand(hopper(\"RGB\"), 2, \"blue\")\n\n        ImageOps.fit(hopper(\"L\"), (128, 128))\n        ImageOps.fit(hopper(\"RGB\"), (128, 128))\n\n        ImageOps.flip(hopper(\"L\"))\n        ImageOps.flip(hopper(\"RGB\"))\n\n        ImageOps.grayscale(hopper(\"L\"))\n        ImageOps.grayscale(hopper(\"RGB\"))\n\n        ImageOps.invert(hopper(\"L\"))\n        ImageOps.invert(hopper(\"RGB\"))\n\n        ImageOps.mirror(hopper(\"L\"))\n        ImageOps.mirror(hopper(\"RGB\"))\n\n        ImageOps.posterize(hopper(\"L\"), 4)\n        ImageOps.posterize(hopper(\"RGB\"), 4)\n\n        ImageOps.solarize(hopper(\"L\"))\n        ImageOps.solarize(hopper(\"RGB\"))\n\n    def test_1pxfit(self):\n        # Division by zero in equalize if image is 1 pixel high\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((1, 100)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n        newimg = ImageOps.fit(hopper(\"RGB\").resize((100, 1)), (35, 35))\n        self.assertEqual(newimg.size, (35, 35))\n\n    def test_pil163(self):\n        # Division by zero in equalize if < 255 pixels in image (@PIL163)\n\n        i = hopper(\"RGB\").resize((15, 16))\n\n        ImageOps.equalize(i.convert(\"L\"))\n        ImageOps.equalize(i.convert(\"P\"))\n        ImageOps.equalize(i.convert(\"RGB\"))\n\n    def test_scale(self):\n        # Test the scaling function\n        i = hopper(\"L\").resize((50, 50))\n        \n        with self.assertRaises(ValueError):\n            ImageOps.scale(i, -1)\n\n        newimg = ImageOps.scale(i, 1)\n        self.assertEqual(newimg.size, (50, 50))\n\n        newimg = ImageOps.scale(i, 2)\n        self.assertEqual(newimg.size, (100, 100))\n\n        newimg = ImageOps.scale(i, 0.5)\n        self.assertEqual(newimg.size, (25, 25))\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\"r2e_tests\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "unittest_custom_runner.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 10ms\nInstalled 12 packages in 32ms\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 401ms\nPrepared 1 package in 6.28s\nInstalled 1 package in 1ms\n + pillow==3.4.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_ffa18c8efd38a40ed4aa49f0f8748c96b64527ad)\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_ffa18c8efd38a40ed4aa49f0f8748c96b64527ad\n....\ncollected 4 items\n\n==================== short test summary info ====================\nPASSED test_1::TestImageOps::test_1pxfit\nPASSED test_1::TestImageOps::test_pil163\nPASSED test_1::TestImageOps::test_sanity\nPASSED test_1::TestImageOps::test_scale\n=================== 4 passed in 0.04s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_ffa18c8efd38a40ed4aa49f0f8748c96b64527ad\n....\ncollected 4 items\n\n=================================== ERRORS =====================================\n__________ TestImageOps.test_scale __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_ffa18c8efd38a40ed4aa49f0f8748c96b64527ad/r2e_tests/test_1.py\", line 86, in test_scale\n    ImageOps.scale(i, -1)\nAttributeError: module 'PIL.ImageOps' has no attribute 'scale'\n\n==================== short test summary info ====================\nPASSED test_1::TestImageOps::test_1pxfit\nPASSED test_1::TestImageOps::test_pil163\nPASSED test_1::TestImageOps::test_sanity\nERROR test_1::TestImageOps::test_scale\n=================== 1 error, 3 passed in 0.01s ===================\n",
    "old_commit_res_stderr": ""
}
PIL/ImageOps.py Tests/test_imageops.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Missing `ImageOps.scale` Function Causes AttributeError When Scaling Images

**Description:**
Attempting to scale an image using the `ImageOps.scale` function results in an `AttributeError` because the `scale` attribute does not exist in the `ImageOps` module.

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

image = Image.open("example.jpg").resize((50, 50))

# Attempting to scale the image by a factor of -1, which should raise a ValueError
ImageOps.scale(image, -1)
```

**Expected Behavior:**
The `ImageOps.scale` function should be available and correctly scale the image by the specified factor. If the scaling factor is less than or equal to 0, the function should raise a `ValueError` indicating that the factor must be greater than 0.

**Actual Behavior:**
Executing the code above results in the following error:
```
AttributeError: module 'PIL.ImageOps' has no attribute 'scale'
```
This prevents any image scaling operations using the `ImageOps.scale` function.
[/ISSUE]
--- END ISSUE ---

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

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

from PIL import Image
from PIL._util import isStringType
import operator
import functools


#
# helpers

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


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


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

#
# actions


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

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


def colorize(image, black, white):
    """
    Colorize grayscale image.  The **black** and **white**
    arguments should be RGB tuples; this function calculates a color
    wedge mapping all black pixels in the source image to the first
    color, and all white pixels to the second color.

    :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.
    :return: An image.
    """
    assert image.mode == "L"
    black = _color(black, "RGB")
    white = _color(white, "RGB")
    red = []
    green = []
    blue = []
    for i in range(256):
        red.append(black[0]+i*(white[0]-black[0])//255)
        green.append(black[1]+i*(white[1]-black[1])//255)
        blue.append(black[2]+i*(white[2]-black[2])//255)
    image = image.convert("RGB")
    return _lut(image, red + green + blue)


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 deform(image, deformer, resample=Image.BILINEAR):
    """
    Deform the image.

    :param image: The image to deform.
    :param deformer: A deformer object.  Any object that implements a
                    **getmesh** method can be used.
    :param resample: What resampling filter to use.
    :return: An image.
    """
    return image.transform(
        image.size, Image.MESH, deformer.getmesh(image), resample
        )


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

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


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

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


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

    This function was contributed by Kevin Cazabon.

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

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

    # ensure inputs are valid
    if not isinstance(centering, list):
        centering = [centering[0], centering[1]]

    if centering[0] > 1.0 or centering[0] < 0.0:
        centering[0] = 0.50
    if centering[1] > 1.0 or centering[1] < 0.0:
        centering[1] = 0.50

    if bleed > 0.49999 or bleed < 0.0:
        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
    bleedPixels = (
        int((float(bleed) * float(image.size[0])) + 0.5),
        int((float(bleed) * float(image.size[1])) + 0.5)
        )

    liveArea = (0, 0, image.size[0], image.size[1])
    if bleed > 0.0:
        liveArea = (
            bleedPixels[0], bleedPixels[1], image.size[0] - bleedPixels[0] - 1,
            image.size[1] - bleedPixels[1] - 1
            )

    liveSize = (liveArea[2] - liveArea[0], liveArea[3] - liveArea[1])

    # calculate the aspect ratio of the liveArea
    liveAreaAspectRatio = float(liveSize[0])/float(liveSize[1])

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

    # figure out if the sides or top/bottom will be cropped off
    if liveAreaAspectRatio >= aspectRatio:
        # liveArea is wider than what's needed, crop the sides
        cropWidth = int((aspectRatio * float(liveSize[1])) + 0.5)
        cropHeight = liveSize[1]
    else:
        # liveArea is taller than what's needed, crop the top and bottom
        cropWidth = liveSize[0]
        cropHeight = int((float(liveSize[0])/aspectRatio) + 0.5)

    # make the crop
    leftSide = int(liveArea[0] + (float(liveSize[0]-cropWidth) * centering[0]))
    if leftSide < 0:
        leftSide = 0
    topSide = int(liveArea[1] + (float(liveSize[1]-cropHeight) * centering[1]))
    if topSide < 0:
        topSide = 0

    out = image.crop(
        (leftSide, topSide, leftSide + cropWidth, topSide + cropHeight)
        )

    # resize the image and return it
    return out.resize(size, method)


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

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


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

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


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

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


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

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


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

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


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

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


# --------------------------------------------------------------------
# PIL USM components, from Kevin Cazabon.

def gaussian_blur(im, radius=None):
    """ PIL_usm.gblur(im, [radius])"""

    if radius is None:
        radius = 5.0

    im.load()

    return im.im.gaussian_blur(radius)

gblur = gaussian_blur


def unsharp_mask(im, radius=None, percent=None, threshold=None):
    """ PIL_usm.usm(im, [radius, percent, threshold])"""

    if radius is None:
        radius = 5.0
    if percent is None:
        percent = 150
    if threshold is None:
        threshold = 3

    im.load()

    return im.im.unsharp_mask(radius, percent, threshold)

usm = unsharp_mask


def box_blur(image, radius):
    """
    Blur the image by setting each pixel to the average value of the pixels
    in a square box extending radius pixels in each direction.
    Supports float radius of arbitrary size. Uses an optimized implementation
    which runs in linear time relative to the size of the image
    for any radius value.

    :param image: The image to blur.
    :param radius: Size of the box in one direction. Radius 0 does not blur,
                   returns an identical image. Radius 1 takes 1 pixel
                   in each direction, i.e. 9 pixels in total.
    :return: An image.
    """
    image.load()

    return image._new(image.im.box_blur(radius))

```
--- 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:** Missing `ImageOps.scale` Function Causes AttributeError When Scaling Images

**Description:**
Attempting to scale an image using the `ImageOps.scale` function results in an `AttributeError` because the `scale` attribute does not exist in the `ImageOps` module.

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

image = Image.open("example.jpg").resize((50, 50))

# Attempting to scale the image by a factor of -1, which should raise a ValueError
ImageOps.scale(image, -1)
```

**Expected Behavior:**
The `ImageOps.scale` function should be available and correctly scale the image by the specified factor. If the scaling factor is less than or equal to 0, the function should raise a `ValueError` indicating that the factor must be greater than 0.

**Actual Behavior:**
Executing the code above results in the following error:
```
AttributeError: module 'PIL.ImageOps' has no attribute 'scale'
```
This prevents any image scaling operations using the `ImageOps.scale` function.
[/ISSUE]
{
    "TestImageOps.test_1pxfit": "PASSED",
    "TestImageOps.test_pil163": "PASSED",
    "TestImageOps.test_sanity": "PASSED",
    "TestImageOps.test_scale": "PASSED"
}
diff --git a/PIL/ImageOps.py b/PIL/ImageOps.py
index f317645b2..8580ec5fb 100644
--- a/PIL/ImageOps.py
+++ b/PIL/ImageOps.py
@@ -178,6 +178,27 @@ def crop(image, border=0):
         )
 
 
+def scale(image, factor, resample=Image.NEAREST):
+    """
+    Returns a rescaled image by a specific factor given in parameter.
+    A factor greater than 1 expands the image, between 0 and 1 contracts the
+    image.
+
+    :param factor: The expansion factor, as a float.
+    :param resample: An optional resampling filter. Same values possible as
+       in the PIL.Image.resize function.
+    :returns: An :py:class:`~PIL.Image.Image` object.
+    """
+    if factor == 1:
+        return image.copy()
+    elif factor <= 0:
+        raise ValueError("the factor must be greater than 0")
+    else:
+        size = (int(round(factor * image.width)),
+                int(round(factor * image.height)))
+        return image.resize(size, resample)
+
+
 def deform(image, deformer, resample=Image.BILINEAR):
     """
     Deform the image.

{"PIL/ImageOps.py": "#\n# The Python Imaging Library.\n# $Id$\n#\n# standard image operations\n#\n# History:\n# 2001-10-20 fl   Created\n# 2001-10-23 fl   Added autocontrast operator\n# 2001-12-18 fl   Added Kevin's fit operator\n# 2004-03-14 fl   Fixed potential division by zero in equalize\n# 2005-05-05 fl   Fixed equalize for low number of values\n#\n# Copyright (c) 2001-2004 by Secret Labs AB\n# Copyright (c) 2001-2004 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom PIL import Image\nfrom PIL._util import isStringType\nimport operator\nimport functools\n\n\n#\n# helpers\n\ndef _border(border):\n    if isinstance(border, tuple):\n        if len(border) == 2:\n            left, top = right, bottom = border\n        elif len(border) == 4:\n            left, top, right, bottom = border\n    else:\n        left = top = right = bottom = border\n    return left, top, right, bottom\n\n\ndef _color(color, mode):\n    if isStringType(color):\n        from PIL import ImageColor\n        color = ImageColor.getcolor(color, mode)\n    return color\n\n\ndef _lut(image, lut):\n    if image.mode == \"P\":\n        # FIXME: apply to lookup table, not image data\n        raise NotImplementedError(\"mode P support coming soon\")\n    elif image.mode in (\"L\", \"RGB\"):\n        if image.mode == \"RGB\" and len(lut) == 256:\n            lut = lut + lut + lut\n        return image.point(lut)\n    else:\n        raise IOError(\"not supported for this image mode\")\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None):\n    \"\"\"\n    Maximize (normalize) image contrast. This function calculates a\n    histogram of the input image, removes **cutoff** percent of the\n    lightest and darkest pixels from the histogram, and remaps the image\n    so that the darkest pixel becomes black (0), and the lightest\n    becomes white (255).\n\n    :param image: The image to process.\n    :param cutoff: How many percent to cut off from the histogram.\n    :param ignore: The background pixel value (use None for no background).\n    :return: An image.\n    \"\"\"\n    histogram = image.histogram()\n    lut = []\n    for layer in range(0, len(histogram), 256):\n        h = histogram[layer:layer+256]\n        if ignore is not None:\n            # get rid of outliers\n            try:\n                h[ignore] = 0\n            except TypeError:\n                # assume sequence\n                for ix in ignore:\n                    h[ix] = 0\n        if cutoff:\n            # cut off pixels from both ends of the histogram\n            # get number of pixels\n            n = 0\n            for ix in range(256):\n                n = n + h[ix]\n            # remove cutoff% pixels from the low end\n            cut = n * cutoff // 100\n            for lo in range(256):\n                if cut > h[lo]:\n                    cut = cut - h[lo]\n                    h[lo] = 0\n                else:\n                    h[lo] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n            # remove cutoff% samples from the hi end\n            cut = n * cutoff // 100\n            for hi in range(255, -1, -1):\n                if cut > h[hi]:\n                    cut = cut - h[hi]\n                    h[hi] = 0\n                else:\n                    h[hi] -= cut\n                    cut = 0\n                if cut <= 0:\n                    break\n        # find lowest/highest samples after preprocessing\n        for lo in range(256):\n            if h[lo]:\n                break\n        for hi in range(255, -1, -1):\n            if h[hi]:\n                break\n        if hi <= lo:\n            # don't bother\n            lut.extend(list(range(256)))\n        else:\n            scale = 255.0 / (hi - lo)\n            offset = -lo * scale\n            for ix in range(256):\n                ix = int(ix * scale + offset)\n                if ix < 0:\n                    ix = 0\n                elif ix > 255:\n                    ix = 255\n                lut.append(ix)\n    return _lut(image, lut)\n\n\ndef colorize(image, black, white):\n    \"\"\"\n    Colorize grayscale image.  The **black** and **white**\n    arguments should be RGB tuples; this function calculates a color\n    wedge mapping all black pixels in the source image to the first\n    color, and all white pixels to the second color.\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    :return: An image.\n    \"\"\"\n    assert image.mode == \"L\"\n    black = _color(black, \"RGB\")\n    white = _color(white, \"RGB\")\n    red = []\n    green = []\n    blue = []\n    for i in range(256):\n        red.append(black[0]+i*(white[0]-black[0])//255)\n        green.append(black[1]+i*(white[1]-black[1])//255)\n        blue.append(black[2]+i*(white[2]-black[2])//255)\n    image = image.convert(\"RGB\")\n    return _lut(image, red + green + blue)\n\n\ndef crop(image, border=0):\n    \"\"\"\n    Remove border from image.  The same amount of pixels are removed\n    from all four sides.  This function works on all image modes.\n\n    .. seealso:: :py:meth:`~PIL.Image.Image.crop`\n\n    :param image: The image to crop.\n    :param border: The number of pixels to remove.\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    return image.crop(\n        (left, top, image.size[0]-right, image.size[1]-bottom)\n        )\n\n\ndef deform(image, deformer, resample=Image.BILINEAR):\n    \"\"\"\n    Deform the image.\n\n    :param image: The image to deform.\n    :param deformer: A deformer object.  Any object that implements a\n                    **getmesh** method can be used.\n    :param resample: What resampling filter to use.\n    :return: An image.\n    \"\"\"\n    return image.transform(\n        image.size, Image.MESH, deformer.getmesh(image), resample\n        )\n\n\ndef equalize(image, mask=None):\n    \"\"\"\n    Equalize the image histogram. This function applies a non-linear\n    mapping to the input image, in order to create a uniform\n    distribution of grayscale values in the output image.\n\n    :param image: The image to equalize.\n    :param mask: An optional mask.  If given, only the pixels selected by\n                 the mask are included in the analysis.\n    :return: An image.\n    \"\"\"\n    if image.mode == \"P\":\n        image = image.convert(\"RGB\")\n    h = image.histogram(mask)\n    lut = []\n    for b in range(0, len(h), 256):\n        histo = [_f for _f in h[b:b+256] if _f]\n        if len(histo) <= 1:\n            lut.extend(list(range(256)))\n        else:\n            step = (functools.reduce(operator.add, histo) - histo[-1]) // 255\n            if not step:\n                lut.extend(list(range(256)))\n            else:\n                n = step // 2\n                for i in range(256):\n                    lut.append(n // step)\n                    n = n + h[i+b]\n    return _lut(image, lut)\n\n\ndef expand(image, border=0, fill=0):\n    \"\"\"\n    Add border to the image\n\n    :param image: The image to expand.\n    :param border: Border width, in pixels.\n    :param fill: Pixel fill value (a color value).  Default is 0 (black).\n    :return: An image.\n    \"\"\"\n    left, top, right, bottom = _border(border)\n    width = left + image.size[0] + right\n    height = top + image.size[1] + bottom\n    out = Image.new(image.mode, (width, height), _color(fill, image.mode))\n    out.paste(image, (left, top))\n    return out\n\n\ndef fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):\n    \"\"\"\n    Returns a sized and cropped version of the image, cropped to the\n    requested aspect ratio and size.\n\n    This function was contributed by Kevin Cazabon.\n\n    :param size: The requested output size in pixels, given as a\n                 (width, height) tuple.\n    :param method: What resampling method to use. Default is\n                   :py:attr:`PIL.Image.NEAREST`.\n    :param bleed: Remove a border around the outside of the image (from all\n                  four edges. The value is a decimal percentage (use 0.01 for\n                  one percent). The default value is 0 (no border).\n    :param centering: Control the cropping position.  Use (0.5, 0.5) for\n                      center cropping (e.g. if cropping the width, take 50% off\n                      of the left side, and therefore 50% off the right side).\n                      (0.0, 0.0) will crop from the top left corner (i.e. if\n                      cropping the width, take all of the crop off of the right\n                      side, and if cropping the height, take all of it off the\n                      bottom).  (1.0, 0.0) will crop from the bottom left\n                      corner, etc. (i.e. if cropping the width, take all of the\n                      crop off the left side, and if cropping the height take\n                      none from the top, and therefore all off the bottom).\n    :return: An image.\n    \"\"\"\n\n    # by Kevin Cazabon, Feb 17/2000\n    # kevin@cazabon.com\n    # http://www.cazabon.com\n\n    # ensure inputs are valid\n    if not isinstance(centering, list):\n        centering = [centering[0], centering[1]]\n\n    if centering[0] > 1.0 or centering[0] < 0.0:\n        centering[0] = 0.50\n    if centering[1] > 1.0 or centering[1] < 0.0:\n        centering[1] = 0.50\n\n    if bleed > 0.49999 or bleed < 0.0:\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    bleedPixels = (\n        int((float(bleed) * float(image.size[0])) + 0.5),\n        int((float(bleed) * float(image.size[1])) + 0.5)\n        )\n\n    liveArea = (0, 0, image.size[0], image.size[1])\n    if bleed > 0.0:\n        liveArea = (\n            bleedPixels[0], bleedPixels[1], image.size[0] - bleedPixels[0] - 1,\n            image.size[1] - bleedPixels[1] - 1\n            )\n\n    liveSize = (liveArea[2] - liveArea[0], liveArea[3] - liveArea[1])\n\n    # calculate the aspect ratio of the liveArea\n    liveAreaAspectRatio = float(liveSize[0])/float(liveSize[1])\n\n    # calculate the aspect ratio of the output image\n    aspectRatio = float(size[0]) / float(size[1])\n\n    # figure out if the sides or top/bottom will be cropped off\n    if liveAreaAspectRatio >= aspectRatio:\n        # liveArea is wider than what's needed, crop the sides\n        cropWidth = int((aspectRatio * float(liveSize[1])) + 0.5)\n        cropHeight = liveSize[1]\n    else:\n        # liveArea is taller than what's needed, crop the top and bottom\n        cropWidth = liveSize[0]\n        cropHeight = int((float(liveSize[0])/aspectRatio) + 0.5)\n\n    # make the crop\n    leftSide = int(liveArea[0] + (float(liveSize[0]-cropWidth) * centering[0]))\n    if leftSide < 0:\n        leftSide = 0\n    topSide = int(liveArea[1] + (float(liveSize[1]-cropHeight) * centering[1]))\n    if topSide < 0:\n        topSide = 0\n\n    out = image.crop(\n        (leftSide, topSide, leftSide + cropWidth, topSide + cropHeight)\n        )\n\n    # resize the image and return it\n    return out.resize(size, method)\n\n\ndef flip(image):\n    \"\"\"\n    Flip the image vertically (top to bottom).\n\n    :param image: The image to flip.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_TOP_BOTTOM)\n\n\ndef grayscale(image):\n    \"\"\"\n    Convert the image to grayscale.\n\n    :param image: The image to convert.\n    :return: An image.\n    \"\"\"\n    return image.convert(\"L\")\n\n\ndef invert(image):\n    \"\"\"\n    Invert (negate) the image.\n\n    :param image: The image to invert.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        lut.append(255-i)\n    return _lut(image, lut)\n\n\ndef mirror(image):\n    \"\"\"\n    Flip image horizontally (left to right).\n\n    :param image: The image to mirror.\n    :return: An image.\n    \"\"\"\n    return image.transpose(Image.FLIP_LEFT_RIGHT)\n\n\ndef posterize(image, bits):\n    \"\"\"\n    Reduce the number of bits for each color channel.\n\n    :param image: The image to posterize.\n    :param bits: The number of bits to keep for each channel (1-8).\n    :return: An image.\n    \"\"\"\n    lut = []\n    mask = ~(2**(8-bits)-1)\n    for i in range(256):\n        lut.append(i & mask)\n    return _lut(image, lut)\n\n\ndef solarize(image, threshold=128):\n    \"\"\"\n    Invert all pixel values above a threshold.\n\n    :param image: The image to solarize.\n    :param threshold: All pixels above this greyscale level are inverted.\n    :return: An image.\n    \"\"\"\n    lut = []\n    for i in range(256):\n        if i < threshold:\n            lut.append(i)\n        else:\n            lut.append(255-i)\n    return _lut(image, lut)\n\n\n# --------------------------------------------------------------------\n# PIL USM components, from Kevin Cazabon.\n\ndef gaussian_blur(im, radius=None):\n    \"\"\" PIL_usm.gblur(im, [radius])\"\"\"\n\n    if radius is None:\n        radius = 5.0\n\n    im.load()\n\n    return im.im.gaussian_blur(radius)\n\ngblur = gaussian_blur\n\n\ndef unsharp_mask(im, radius=None, percent=None, threshold=None):\n    \"\"\" PIL_usm.usm(im, [radius, percent, threshold])\"\"\"\n\n    if radius is None:\n        radius = 5.0\n    if percent is None:\n        percent = 150\n    if threshold is None:\n        threshold = 3\n\n    im.load()\n\n    return im.im.unsharp_mask(radius, percent, threshold)\n\nusm = unsharp_mask\n\n\ndef box_blur(image, radius):\n    \"\"\"\n    Blur the image by setting each pixel to the average value of the pixels\n    in a square box extending radius pixels in each direction.\n    Supports float radius of arbitrary size. Uses an optimized implementation\n    which runs in linear time relative to the size of the image\n    for any radius value.\n\n    :param image: The image to blur.\n    :param radius: Size of the box in one direction. Radius 0 does not blur,\n                   returns an identical image. Radius 1 takes 1 pixel\n                   in each direction, i.e. 9 pixels in total.\n    :return: An image.\n    \"\"\"\n    image.load()\n\n    return image._new(image.im.box_blur(radius))\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:** Missing `ImageOps.scale` Function Causes AttributeError When Scaling Images

**Description:**
Attempting to scale an image using the `ImageOps.scale` function results in an `AttributeError` because the `scale` attribute does not exist in the `ImageOps` module.

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

image = Image.open("example.jpg").resize((50, 50))

# Attempting to scale the image by a factor of -1, which should raise a ValueError
ImageOps.scale(image, -1)
```

**Expected Behavior:**
The `ImageOps.scale` function should be available and correctly scale the image by the specified factor. If the scaling factor is less than or equal to 0, the function should raise a `ValueError` indicating that the factor must be greater than 0.

**Actual Behavior:**
Executing the code above results in the following error:
```
AttributeError: module 'PIL.ImageOps' has no attribute 'scale'
```
This prevents any image scaling operations using the `ImageOps.scale` function.
[/ISSUE]
--- END ISSUE ---

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

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

from PIL import Image
from PIL._util import isStringType
import operator
import functools


#
# helpers

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


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


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

#
# actions


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

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


def colorize(image, black, white):
    """
    Colorize grayscale image.  The **black** and **white**
    arguments should be RGB tuples; this function calculates a color
    wedge mapping all black pixels in the source image to the first
    color, and all white pixels to the second color.

    :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.
    :return: An image.
    """
    assert image.mode == "L"
    black = _color(black, "RGB")
    white = _color(white, "RGB")
    red = []
    green = []
    blue = []
    for i in range(256):
        red.append(black[0]+i*(white[0]-black[0])//255)
        green.append(black[1]+i*(white[1]-black[1])//255)
        blue.append(black[2]+i*(white[2]-black[2])//255)
    image = image.convert("RGB")
    return _lut(image, red + green + blue)


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 deform(image, deformer, resample=Image.BILINEAR):
    """
    Deform the image.

    :param image: The image to deform.
    :param deformer: A deformer object.  Any object that implements a
                    **getmesh** method can be used.
    :param resample: What resampling filter to use.
    :return: An image.
    """
    return image.transform(
        image.size, Image.MESH, deformer.getmesh(image), resample
        )


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

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


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

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


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

    This function was contributed by Kevin Cazabon.

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

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

    # ensure inputs are valid
    if not isinstance(centering, list):
        centering = [centering[0], centering[1]]

    if centering[0] > 1.0 or centering[0] < 0.0:
        centering[0] = 0.50
    if centering[1] > 1.0 or centering[1] < 0.0:
        centering[1] = 0.50

    if bleed > 0.49999 or bleed < 0.0:
        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
    bleedPixels = (
        int((float(bleed) * float(image.size[0])) + 0.5),
        int((float(bleed) * float(image.size[1])) + 0.5)
        )

    liveArea = (0, 0, image.size[0], image.size[1])
    if bleed > 0.0:
        liveArea = (
            bleedPixels[0], bleedPixels[1], image.size[0] - bleedPixels[0] - 1,
            image.size[1] - bleedPixels[1] - 1
            )

    liveSize = (liveArea[2] - liveArea[0], liveArea[3] - liveArea[1])

    # calculate the aspect ratio of the liveArea
    liveAreaAspectRatio = float(liveSize[0])/float(liveSize[1])

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

    # figure out if the sides or top/bottom will be cropped off
    if liveAreaAspectRatio >= aspectRatio:
        # liveArea is wider than what's needed, crop the sides
        cropWidth = int((aspectRatio * float(liveSize[1])) + 0.5)
        cropHeight = liveSize[1]
    else:
        # liveArea is taller than what's needed, crop the top and bottom
        cropWidth = liveSize[0]
        cropHeight = int((float(liveSize[0])/aspectRatio) + 0.5)

    # make the crop
    leftSide = int(liveArea[0] + (float(liveSize[0]-cropWidth) * centering[0]))
    if leftSide < 0:
        leftSide = 0
    topSide = int(liveArea[1] + (float(liveSize[1]-cropHeight) * centering[1]))
    if topSide < 0:
        topSide = 0

    out = image.crop(
        (leftSide, topSide, leftSide + cropWidth, topSide + cropHeight)
        )

    # resize the image and return it
    return out.resize(size, method)


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

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


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

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


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

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


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

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


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

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


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

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


# --------------------------------------------------------------------
# PIL USM components, from Kevin Cazabon.

def gaussian_blur(im, radius=None):
    """ PIL_usm.gblur(im, [radius])"""

    if radius is None:
        radius = 5.0

    im.load()

    return im.im.gaussian_blur(radius)

gblur = gaussian_blur


def unsharp_mask(im, radius=None, percent=None, threshold=None):
    """ PIL_usm.usm(im, [radius, percent, threshold])"""

    if radius is None:
        radius = 5.0
    if percent is None:
        percent = 150
    if threshold is None:
        threshold = 3

    im.load()

    return im.im.unsharp_mask(radius, percent, threshold)

usm = unsharp_mask


def box_blur(image, radius):
    """
    Blur the image by setting each pixel to the average value of the pixels
    in a square box extending radius pixels in each direction.
    Supports float radius of arbitrary size. Uses an optimized implementation
    which runs in linear time relative to the size of the image
    for any radius value.

    :param image: The image to blur.
    :param radius: Size of the box in one direction. Radius 0 does not blur,
                   returns an identical image. Radius 1 takes 1 pixel
                   in each direction, i.e. 9 pixels in total.
    :return: An image.
    """
    image.load()

    return image._new(image.im.box_blur(radius))

```
--- 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