国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python自動(dòng)裁剪圖像代碼分享

2020-01-04 16:15:15
字體:
供稿:網(wǎng)友

本代碼可以幫你自動(dòng)剪切掉圖片的邊緣空白區(qū)域,如果你的圖片有大片空白區(qū)域(只要是同一顏色形成一定的面積就認(rèn)為是空白區(qū)域),下面的python/271941.html">python/267544.html">python代碼可以幫你自動(dòng)切除,如果是透明圖像,會(huì)自動(dòng)剪切大片的透明部分。

本代碼需要PIL模塊

pil相關(guān)介紹

PIL:Python Imaging Library,已經(jīng)是Python平臺(tái)事實(shí)上的圖像處理標(biāo)準(zhǔn)庫了。PIL功能非常強(qiáng)大,但API卻非常簡單易用。

由于PIL僅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基礎(chǔ)上創(chuàng)建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了許多新特性,因此,我們可以直接安裝使用Pillow。

import Image, ImageChops def autoCrop(image,backgroundColor=None):  '''Intelligent automatic image cropping.    This functions removes the usless "white" space around an image.        If the image has an alpha (tranparency) channel, it will be used    to choose what to crop.        Otherwise, this function will try to find the most popular color    on the edges of the image and consider this color "whitespace".    (You can override this color with the backgroundColor parameter)      Input:      image (a PIL Image object): The image to crop.      backgroundColor (3 integers tuple): eg. (0,0,255)         The color to consider "background to crop".         If the image is transparent, this parameters will be ignored.         If the image is not transparent and this parameter is not         provided, it will be automatically calculated.     Output:      a PIL Image object : The cropped image.  '''     def mostPopularEdgeColor(image):    ''' Compute who's the most popular color on the edges of an image.      (left,right,top,bottom)             Input:        image: a PIL Image object             Ouput:        The most popular color (A tuple of integers (R,G,B))    '''    im = image    if im.mode != 'RGB':      im = image.convert("RGB")         # Get pixels from the edges of the image:    width,height = im.size    left  = im.crop((0,1,1,height-1))    right = im.crop((width-1,1,width,height-1))    top  = im.crop((0,0,width,1))    bottom = im.crop((0,height-1,width,height))    pixels = left.tostring() + right.tostring() + top.tostring() + bottom.tostring()     # Compute who's the most popular RGB triplet    counts = {}    for i in range(0,len(pixels),3):      RGB = pixels[i]+pixels[i+1]+pixels[i+2]      if RGB in counts:        counts[RGB] += 1      else:        counts[RGB] = 1           # Get the colour which is the most popular:        mostPopularColor = sorted([(count,rgba) for (rgba,count) in counts.items()],reverse=True)[0][1]    return ord(mostPopularColor[0]),ord(mostPopularColor[1]),ord(mostPopularColor[2])     bbox = None     # If the image has an alpha (tranparency) layer, we use it to crop the image.  # Otherwise, we look at the pixels around the image (top, left, bottom and right)  # and use the most used color as the color to crop.     # --- For transparent images -----------------------------------------------  if 'A' in image.getbands(): # If the image has a transparency layer, use it.    # This works for all modes which have transparency layer    bbox = image.split()[list(image.getbands()).index('A')].getbbox()  # --- For non-transparent images -------------------------------------------  elif image.mode=='RGB':    if not backgroundColor:      backgroundColor = mostPopularEdgeColor(image)    # Crop a non-transparent image.    # .getbbox() always crops the black color.    # So we need to substract the "background" color from our image.    bg = Image.new("RGB", image.size, backgroundColor)    diff = ImageChops.difference(image, bg) # Substract background color from image    bbox = diff.getbbox() # Try to find the real bounding box of the image.  else:    raise NotImplementedError, "Sorry, this function is not implemented yet for images in mode '%s'." % image.mode       if bbox:    image = image.crop(bbox)       return image   #范例:裁剪透明圖片:im = Image.open('myTransparentImage.png')cropped = autoCrop(im)cropped.show() #范例:裁剪非透明圖片im = Image.open('myImage.png')cropped = autoCrop(im)cropped.show()

 總結(jié)

以上就是本文關(guān)于python自動(dòng)裁剪圖像代碼分享的全部內(nèi)容,希望對大家有所幫助。如有不足之處,歡迎留言指出。


注:相關(guān)教程知識(shí)閱讀請移步到python教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 霸州市| 南部县| 乳山市| 通化市| 平江县| 竹山县| 太湖县| 营山县| 麟游县| 佳木斯市| 洛隆县| 隆化县| 玉龙| 扎鲁特旗| 白银市| 扎赉特旗| 新巴尔虎左旗| 平罗县| 剑河县| 谢通门县| 故城县| 廊坊市| 阳新县| 高雄市| 色达县| 白城市| 平陆县| 内黄县| 纳雍县| 泽普县| 合山市| 麻江县| 耒阳市| 庆云县| 五华县| 绍兴县| 英吉沙县| 丰县| 定结县| 县级市| 屏东县|