[Python] python自动裁剪图像 →→→→→进入此内容的聊天室

来自 , 2020-08-21, 写在 Python, 查看 109 次.
URL http://www.code666.cn/view/23716803
  1. import Image, ImageChops
  2.  
  3. def autoCrop(image,backgroundColor=None):
  4.     '''Intelligent automatic image cropping.
  5.       This functions removes the usless "white" space around an image.
  6.      
  7.       If the image has an alpha (tranparency) channel, it will be used
  8.       to choose what to crop.
  9.      
  10.       Otherwise, this function will try to find the most popular color
  11.       on the edges of the image and consider this color "whitespace".
  12.       (You can override this color with the backgroundColor parameter)  
  13.  
  14.       Input:
  15.            image (a PIL Image object): The image to crop.
  16.            backgroundColor (3 integers tuple): eg. (0,0,255)
  17.                 The color to consider "background to crop".
  18.                 If the image is transparent, this parameters will be ignored.
  19.                 If the image is not transparent and this parameter is not
  20.                 provided, it will be automatically calculated.
  21.  
  22.       Output:
  23.            a PIL Image object : The cropped image.
  24.    '''
  25.    
  26.     def mostPopularEdgeColor(image):
  27.         ''' Compute who's the most popular color on the edges of an image.
  28.            (left,right,top,bottom)
  29.            
  30.            Input:
  31.                image: a PIL Image object
  32.            
  33.            Ouput:
  34.                The most popular color (A tuple of integers (R,G,B))
  35.        '''
  36.         im = image
  37.         if im.mode != 'RGB':
  38.             im = image.convert("RGB")
  39.        
  40.         # Get pixels from the edges of the image:
  41.         width,height = im.size
  42.         left   = im.crop((0,1,1,height-1))
  43.         right  = im.crop((width-1,1,width,height-1))
  44.         top    = im.crop((0,0,width,1))
  45.         bottom = im.crop((0,height-1,width,height))
  46.         pixels = left.tostring() + right.tostring() + top.tostring() + bottom.tostring()
  47.  
  48.         # Compute who's the most popular RGB triplet
  49.         counts = {}
  50.         for i in range(0,len(pixels),3):
  51.             RGB = pixels[i]+pixels[i+1]+pixels[i+2]
  52.             if RGB in counts:
  53.                 counts[RGB] += 1
  54.             else:
  55.                 counts[RGB] = 1    
  56.        
  57.         # Get the colour which is the most popular:        
  58.         mostPopularColor = sorted([(count,rgba) for (rgba,count) in counts.items()],reverse=True)[0][1]
  59.         return ord(mostPopularColor[0]),ord(mostPopularColor[1]),ord(mostPopularColor[2])
  60.    
  61.     bbox = None
  62.    
  63.     # If the image has an alpha (tranparency) layer, we use it to crop the image.
  64.     # Otherwise, we look at the pixels around the image (top, left, bottom and right)
  65.     # and use the most used color as the color to crop.
  66.    
  67.     # --- For transparent images -----------------------------------------------
  68.     if 'A' in image.getbands(): # If the image has a transparency layer, use it.
  69.         # This works for all modes which have transparency layer
  70.         bbox = image.split()[list(image.getbands()).index('A')].getbbox()
  71.     # --- For non-transparent images -------------------------------------------
  72.     elif image.mode=='RGB':
  73.         if not backgroundColor:
  74.             backgroundColor = mostPopularEdgeColor(image)
  75.         # Crop a non-transparent image.
  76.         # .getbbox() always crops the black color.
  77.         # So we need to substract the "background" color from our image.
  78.         bg = Image.new("RGB", image.size, backgroundColor)
  79.         diff = ImageChops.difference(image, bg)  # Substract background color from image
  80.         bbox = diff.getbbox()  # Try to find the real bounding box of the image.
  81.     else:
  82.         raise NotImplementedError, "Sorry, this function is not implemented yet for images in mode '%s'." % image.mode
  83.        
  84.     if bbox:
  85.         image = image.crop(bbox)
  86.        
  87.     return image
  88.  
  89.  
  90.  
  91. #范例:裁剪透明图片:
  92. im = Image.open('myTransparentImage.png')
  93. cropped = autoCrop(im)
  94. cropped.show()
  95.  
  96. #范例:裁剪非透明图片
  97. im = Image.open('myImage.png')
  98. cropped = autoCrop(im)
  99. cropped.show()
  100. #//python/1870

回复 "python自动裁剪图像"

这儿你可以回复上面这条便签

captcha