python自動裁剪映像代碼分享,python裁剪映像

來源:互聯網
上載者:User

python自動裁剪映像代碼分享,python裁剪映像

本代碼可以幫你自動剪下掉圖片的邊緣空白地區,如果你的圖片有大片空白地區(只要是同一顏色形成一定的面積就認為是空白地區),下面的python代碼可以幫你自動切除,如果是透明映像,會自動剪下大片的透明部分。

本代碼需要PIL模組

pil相關介紹

PIL:Python Imaging Library,已經是Python平台事實上的影像處理標準庫了。PIL功能非常強大,但API卻非常簡單易用。

由於PIL僅支援到Python 2.7,加上年久失修,於是一群志願者在PIL的基礎上建立了相容的版本,名字叫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()

 總結

以上就是本文關於python自動裁剪映像代碼分享的全部內容,希望對大家有所協助。如有不足之處,歡迎留言指出。感興趣的朋友可以繼續參閱本站:

python映像常規操作

python好玩的項目—色情圖片識別代碼分享

Python產生數字圖片代碼分享

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.