Python PIL.ImageFilter.SHARPEN Examples

The following are 10 code examples of PIL.ImageFilter.SHARPEN(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PIL.ImageFilter , or try the search function .
Example #1
Source File: test_image_filter.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_sanity(self):

        def filter(filter):
            for mode in ["L", "RGB", "CMYK"]:
                im = hopper(mode)
                out = im.filter(filter)
                self.assertEqual(out.mode, im.mode)
                self.assertEqual(out.size, im.size)

        filter(ImageFilter.BLUR)
        filter(ImageFilter.CONTOUR)
        filter(ImageFilter.DETAIL)
        filter(ImageFilter.EDGE_ENHANCE)
        filter(ImageFilter.EDGE_ENHANCE_MORE)
        filter(ImageFilter.EMBOSS)
        filter(ImageFilter.FIND_EDGES)
        filter(ImageFilter.SMOOTH)
        filter(ImageFilter.SMOOTH_MORE)
        filter(ImageFilter.SHARPEN)
        filter(ImageFilter.MaxFilter)
        filter(ImageFilter.MedianFilter)
        filter(ImageFilter.MinFilter)
        filter(ImageFilter.ModeFilter)
        filter(ImageFilter.GaussianBlur)
        filter(ImageFilter.GaussianBlur(5))
        filter(ImageFilter.BoxBlur(5))
        filter(ImageFilter.UnsharpMask)
        filter(ImageFilter.UnsharpMask(10))

        self.assertRaises(TypeError, filter, "hello") 
Example #2
Source File: pilutil.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def imfilter(arr, ftype):
    """
    Simple filtering of an image.

    Parameters
    ----------
    arr : ndarray
        The array of Image in which the filter is to be applied.
    ftype : str
        The filter that has to be applied. Legal values are:
        'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more',
        'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'.

    Returns
    -------
    imfilter : ndarray
        The array with filter applied.

    Raises
    ------
    ValueError
        *Unknown filter type.*  If the filter you are trying
        to apply is unsupported.

    """
    _tdict = {'blur': ImageFilter.BLUR,
              'contour': ImageFilter.CONTOUR,
              'detail': ImageFilter.DETAIL,
              'edge_enhance': ImageFilter.EDGE_ENHANCE,
              'edge_enhance_more': ImageFilter.EDGE_ENHANCE_MORE,
              'emboss': ImageFilter.EMBOSS,
              'find_edges': ImageFilter.FIND_EDGES,
              'smooth': ImageFilter.SMOOTH,
              'smooth_more': ImageFilter.SMOOTH_MORE,
              'sharpen': ImageFilter.SHARPEN
              }

    im = toimage(arr)
    if ftype not in _tdict:
        raise ValueError("Unknown filter type.")
    return fromimage(im.filter(_tdict[ftype])) 
Example #3
Source File: picmaker.py    From pds-tools with Academic Free License v3.0 6 votes vote down vote up
def FilterImage(image, filter_name):
    """Applies an arbitrary filtering to a PIL image. Note that this does not
    work for two-byte images.

    Input:
        image               a PIL image as 8-bit RGB or grayscale.
        filter_name         name of the filter to be applied. Choices are
                            "NONE", "BLUR", "CONTOUR", "DETAIL" ,"EDGE_ENHANCE",
                            "EDGE_ENHANCE_MORE", "EMBOSS", "FIND_EDGES",
                            "SMOOTH", "SMOOTH_MORE", "SHARPEN", "MEDIAN_3",
                            "MEDIAN_5", "MEDIAN_7", "MINIMUM_3", "MINIMUM_5",
                            "MINIMUM_7" ,"MAXIMUM_3", "MAXIMUM_5", and
                            "MAXIMUM_7".

    Return:                 a pointer to the filtered image.
    """

    if type(image) == list:
        raise ValueError("filtering of 2-byte images is not supported")

    # Look up filter method
    if filter:
        filter_method = FILTER_DICT[filter_name.upper()]
    else:
        filter_method = None

    # Apply filter if necessary
    if filter_method: image = image.filter(filter_method)

    return image

################################################################################
# Re-size a PIL image
################################################################################ 
Example #4
Source File: pilutil.py    From lambda-packs with MIT License 5 votes vote down vote up
def imfilter(arr, ftype):
    """
    Simple filtering of an image.

    This function is only available if Python Imaging Library (PIL) is installed.

    .. warning::

        This function uses `bytescale` under the hood to rescale images to use
        the full (0, 255) range if ``mode`` is one of ``None, 'L', 'P', 'l'``.
        It will also cast data for 2-D images to ``uint32`` for ``mode=None``
        (which is the default).

    Parameters
    ----------
    arr : ndarray
        The array of Image in which the filter is to be applied.
    ftype : str
        The filter that has to be applied. Legal values are:
        'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more',
        'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'.

    Returns
    -------
    imfilter : ndarray
        The array with filter applied.

    Raises
    ------
    ValueError
        *Unknown filter type.*  If the filter you are trying
        to apply is unsupported.

    """
    _tdict = {'blur': ImageFilter.BLUR,
              'contour': ImageFilter.CONTOUR,
              'detail': ImageFilter.DETAIL,
              'edge_enhance': ImageFilter.EDGE_ENHANCE,
              'edge_enhance_more': ImageFilter.EDGE_ENHANCE_MORE,
              'emboss': ImageFilter.EMBOSS,
              'find_edges': ImageFilter.FIND_EDGES,
              'smooth': ImageFilter.SMOOTH,
              'smooth_more': ImageFilter.SMOOTH_MORE,
              'sharpen': ImageFilter.SHARPEN
              }

    im = toimage(arr)
    if ftype not in _tdict:
        raise ValueError("Unknown filter type.")
    return fromimage(im.filter(_tdict[ftype])) 
Example #5
Source File: pilutil.py    From Computable with MIT License 5 votes vote down vote up
def imfilter(arr,ftype):
    """
    Simple filtering of an image.

    Parameters
    ----------
    arr : ndarray
        The array of Image in which the filter is to be applied.
    ftype : str
        The filter that has to be applied. Legal values are:
        'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more',
        'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'.

    Returns
    -------
    imfilter : ndarray
        The array with filter applied.

    Raises
    ------
    ValueError
        *Unknown filter type.*  If the filter you are trying
        to apply is unsupported.

    """
    _tdict = {'blur':ImageFilter.BLUR,
              'contour':ImageFilter.CONTOUR,
              'detail':ImageFilter.DETAIL,
              'edge_enhance':ImageFilter.EDGE_ENHANCE,
              'edge_enhance_more':ImageFilter.EDGE_ENHANCE_MORE,
              'emboss':ImageFilter.EMBOSS,
              'find_edges':ImageFilter.FIND_EDGES,
              'smooth':ImageFilter.SMOOTH,
              'smooth_more':ImageFilter.SMOOTH_MORE,
              'sharpen':ImageFilter.SHARPEN
              }

    im = toimage(arr)
    if ftype not in _tdict:
        raise ValueError("Unknown filter type.")
    return fromimage(im.filter(_tdict[ftype])) 
Example #6
Source File: inputs.py    From NGU-scripts with GNU Lesser General Public License v3.0 4 votes vote down vote up
def ocr(
         x_start :int,
         y_start :int,
         x_end :int,
         y_end :int,
         debug :bool =False,
         bmp :image =None,
         cropb :bool =False,
         filter :bool =True,
         binf :int =0,
         sliced :bool =False
     ) -> str:
        """Perform an OCR of the supplied area, returns a string of the result.
        
        Keyword arguments
        debug  -- Saves an image of what is sent to the OCR (default False)
        bmp    -- A bitmap from the get_bitmap() function, use this if you're
                  performing multiple different OCR-readings in succession from
                  the same page. This is to avoid to needlessly get the same
                  bitmap multiple times. If a bitmap is not passed, the function
                  will get the bitmap itself. (default None)
        cropb  -- Whether the bmp provided should be cropped.
        filter -- Whether to filter the image for better OCR.
        binf   -- Threshold value for binarizing filter. Zero means no filtering.
        sliced -- Whether the image has ben sliced so there's very little blank
                  space. Gets better readings from small values for some reason.
        """
        x_start += Window.x
        x_end   += Window.x
        y_start += Window.y
        y_end   += Window.y

        if bmp is None:
            bmp = Inputs.get_cropped_bitmap(x_start, y_start, x_end, y_end)
        
        elif cropb:
            # Bitmaps are created with a 8px border
            bmp = bmp.crop((x_start + 8, y_start + 8, x_end + 8, y_end + 8))
        
        if binf > 0: # Binarizing Filter
            fn = lambda x : 255 if x > binf else 0
            bmp = bmp.convert('L') # To Monochrome
            bmp = bmp.point(fn, mode='1')
            if debug: bmp.save("debug_ocr_whiten.png")
        
        if filter: # Resizing and sharpening
            *_, right, lower = bmp.getbbox()
            bmp = bmp.resize((right * 4, lower * 4), image.BICUBIC)  # Resize image
            bmp = bmp.filter(ImageFilter.SHARPEN)
            if debug: bmp.save("debug_ocr_filter.png")
            
        if sliced: s = pytesseract.image_to_string(bmp, config='--psm 6')
        else:      s = pytesseract.image_to_string(bmp, config='--psm 4')
        
        return s 
Example #7
Source File: pilutil.py    From GraphicDesignPatternByPython with MIT License 4 votes vote down vote up
def imfilter(arr, ftype):
    """
    Simple filtering of an image.

    This function is only available if Python Imaging Library (PIL) is installed.

    .. warning::

        This function uses `bytescale` under the hood to rescale images to use
        the full (0, 255) range if ``mode`` is one of ``None, 'L', 'P', 'l'``.
        It will also cast data for 2-D images to ``uint32`` for ``mode=None``
        (which is the default).

    Parameters
    ----------
    arr : ndarray
        The array of Image in which the filter is to be applied.
    ftype : str
        The filter that has to be applied. Legal values are:
        'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more',
        'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'.

    Returns
    -------
    imfilter : ndarray
        The array with filter applied.

    Raises
    ------
    ValueError
        *Unknown filter type.*  If the filter you are trying
        to apply is unsupported.

    """
    _tdict = {'blur': ImageFilter.BLUR,
              'contour': ImageFilter.CONTOUR,
              'detail': ImageFilter.DETAIL,
              'edge_enhance': ImageFilter.EDGE_ENHANCE,
              'edge_enhance_more': ImageFilter.EDGE_ENHANCE_MORE,
              'emboss': ImageFilter.EMBOSS,
              'find_edges': ImageFilter.FIND_EDGES,
              'smooth': ImageFilter.SMOOTH,
              'smooth_more': ImageFilter.SMOOTH_MORE,
              'sharpen': ImageFilter.SHARPEN
              }

    im = toimage(arr)
    if ftype not in _tdict:
        raise ValueError("Unknown filter type.")
    return fromimage(im.filter(_tdict[ftype])) 
Example #8
Source File: image.py    From Fruit-API with GNU General Public License v3.0 4 votes vote down vote up
def imfilter(arr, ftype):
    """
    Simple filtering of an image.

    This function is only available if Python Imaging Library (PIL) is installed.

    .. warning::

        This function uses `bytescale` under the hood to rescale images to use
        the full (0, 255) range if ``mode`` is one of ``None, 'L', 'P', 'l'``.
        It will also cast data for 2-D images to ``uint32`` for ``mode=None``
        (which is the default).

    Parameters
    ----------
    arr : ndarray
        The array of Image in which the filter is to be applied.
    ftype : str
        The filter that has to be applied. Legal values are:
        'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more',
        'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'.

    Returns
    -------
    imfilter : ndarray
        The array with filter applied.

    Raises
    ------
    ValueError
        *Unknown filter type.*  If the filter you are trying
        to apply is unsupported.

    """
    _tdict = {'blur': ImageFilter.BLUR,
              'contour': ImageFilter.CONTOUR,
              'detail': ImageFilter.DETAIL,
              'edge_enhance': ImageFilter.EDGE_ENHANCE,
              'edge_enhance_more': ImageFilter.EDGE_ENHANCE_MORE,
              'emboss': ImageFilter.EMBOSS,
              'find_edges': ImageFilter.FIND_EDGES,
              'smooth': ImageFilter.SMOOTH,
              'smooth_more': ImageFilter.SMOOTH_MORE,
              'sharpen': ImageFilter.SHARPEN
              }

    im = toimage(arr)
    if ftype not in _tdict:
        raise ValueError("Unknown filter type.")
    return fromimage(im.filter(_tdict[ftype])) 
Example #9
Source File: views.py    From ocr-with-django with MIT License 4 votes vote down vote up
def post(self, request, *args, **kwargs):
        with PyTessBaseAPI() as api:
            with Image.open(request.FILES['image']) as image:
                sharpened_image = image.filter(ImageFilter.SHARPEN)
                api.SetImage(sharpened_image)
                utf8_text = api.GetUTF8Text()

        return JsonResponse({'utf8_text': utf8_text}) 
Example #10
Source File: Binarization.py    From ArknightsAutoHelper with MIT License 4 votes vote down vote up
def binarization_image(image, invert_image=True, threshold=127):
    """
    锐化图片,二值化图像,之后颜色反转,以增加ocr识别精确度
    原因是tesseract在识别黑底白字和白底黑字会有不同表现:
    黑底白字有问题,而白底黑字可以识别
    Arknights中截取的图片大多为黑底白字,所以转变为白底黑字
    :param invert_image: 是否颜色反转图片,绝大部分如理智判断,需要反转图片,但有部分不需要
    :param image: 输入图片
    :param threshold: 临界灰度值,原来是200,现在改为175,有人report问题issue#24; 现在改回PIL默认的127,鬼知道为啥之前的就不行
    :return: 返回二值化图片,但暂时没有用,tesseract的调用方式导致必须有个图片路径,
             变量的方式不知道怎么弄过去,百度OCR倒是可以,但没弄
    """
    # 百度api有的时候需要二值化,有时二值化反而会造成负面影响
    # if save_backup:
    #     # 这里给二值化前的图片留个底,确认二值化异常的原因
    #     try:
    #         copy(image, image + ".DebugBackup.png")
    #     except IOError as e:
    #         print("Unable to copy file. {}".format(e))
    #     except:
    #         print("Unexpected error:", sys.exc_info())
    # picture = Image.open(image)
    # 锐化图片
    sharpen = image.filter(ImageFilter.SHARPEN)
    # 灰度化
    final = sharpen.convert('L')
    # 颜色反转
    if invert_image:
        final = ImageOps.invert(final)
    # 二值化,这里其实可以直接使用inverted_image.convert(1)来完成,但为了保障阈值可控,这里“手动”一下
    # table = []
    # for i in range(256):
    #     if i < threshold:
    #         table.append(0)
    #     else:
    #         table.append(1)
    # 这里该用似乎是更快速的方式
    lut = lambda x: 1 if x > threshold else 0
    bim = final.point(lut, '1')
    # bim.save(image)
    return bim

# def image_threshold(image, threshold=127):
#     """
#     threshold filter on L channel
#     :param threshold: negative value means inverted output
#     """
#     if threshold < 0:
#         lut = lambda x: 0 if x > -threshold else 1
#     else:
#         lut = lambda x: 1 if x > threshold else 0
#     return image.convert('L').point(lut, '1')