Python remove picture solid color border (qbit)

Posted Jun 15, 20202 min read

Foreword

  • This article mainly refers to Trim whitespace using PIL

  • test environment

    Windows 10 2004
    Python 3.8.3
    Pillow 7.1.2
    ImageMagick 7.0.10

  • In addition to Pillow , qbit also tried skimage and opencv-python , the effect is not better than Pillow, and the usage is much more complicated

Pillow

  • Pillow documentation: https://pillow.readthedocs.io/

    encoding:utf-8

    author:qbit

    date:2020-06-15

    summary:Remove the solid border of the picture

    import shutil
    from PIL import Image, ImageChops
    def TrimImgEdge(inImgPath, outImgPath):

      r"""
      Remove picture border
      inImgPath:Enter the image path
      outImgPath:output image path
      """
      print(f'TrimImgEdge {inImgPath} ...')
      imgIn = Image.open(inImgPath)
      # Create a border color picture
      bg = Image.new(imgIn.mode, imgIn.size, imgIn.getpixel((0, 0)))
      diff = ImageChops.difference(imgIn, bg)
      bbox = diff.getbbox() # Returns the coordinates of the upper left and lower right corners(left, upper, right, lower)
      if bbox:
          imgIn.crop(bbox).save(outImgPath, quality=95)
      else:
          shutil.copyfile(inImgPath, outImgPath)

    if name == "main":

      TrimImgEdge('csharp.jpg','csharp_pillow.jpg')
  • Adjust the size

    LANCZOS before Pillow 2.7 was called ANTIALIAS

    img.resize((width, height), Image.LANCZOS)

  • Sample input picture(Click the picture to view the border)

csharp.jpg

  • Sample output picture(Click the picture to see the border)

csharp_pillow.jpg

ImageMagick

  • Use ImageMagick to achieve a similar purpose

    magick convert csharp.jpg -fuzz 7%-trim csharp_magick.jpg

This article is from qbit snap