python自动裁剪图像代码分享
本代码可以帮你自动剪切掉图片的边缘空白区域,如果你的图片有大片空白区域(只要是同一颜色形成一定的面积就认为是空白区域),下面的python代码可以帮你自动切除,如果是透明图像,会自动剪切大片的透明部分。
本代码需要PIL模块
pil相关介绍
PIL:PythonImagingLibrary,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。
由于PIL仅支持到Python2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow。
importImage,ImageChops defautoCrop(image,backgroundColor=None): '''Intelligentautomaticimagecropping. Thisfunctionsremovestheusless"white"spacearoundanimage. Iftheimagehasanalpha(tranparency)channel,itwillbeused tochoosewhattocrop. Otherwise,thisfunctionwilltrytofindthemostpopularcolor ontheedgesoftheimageandconsiderthiscolor"whitespace". (YoucanoverridethiscolorwiththebackgroundColorparameter) Input: image(aPILImageobject):Theimagetocrop. backgroundColor(3integerstuple):eg.(0,0,255) Thecolortoconsider"backgroundtocrop". Iftheimageistransparent,thisparameterswillbeignored. Iftheimageisnottransparentandthisparameterisnot provided,itwillbeautomaticallycalculated. Output: aPILImageobject:Thecroppedimage. ''' defmostPopularEdgeColor(image): '''Computewho'sthemostpopularcolorontheedgesofanimage. (left,right,top,bottom) Input: image:aPILImageobject Ouput: Themostpopularcolor(Atupleofintegers(R,G,B)) ''' im=image ifim.mode!='RGB': im=image.convert("RGB") #Getpixelsfromtheedgesoftheimage: 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() #Computewho'sthemostpopularRGBtriplet counts={} foriinrange(0,len(pixels),3): RGB=pixels[i]+pixels[i+1]+pixels[i+2] ifRGBincounts: counts[RGB]+=1 else: counts[RGB]=1 #Getthecolourwhichisthemostpopular: mostPopularColor=sorted([(count,rgba)for(rgba,count)incounts.items()],reverse=True)[0][1] returnord(mostPopularColor[0]),ord(mostPopularColor[1]),ord(mostPopularColor[2]) bbox=None #Iftheimagehasanalpha(tranparency)layer,weuseittocroptheimage. #Otherwise,welookatthepixelsaroundtheimage(top,left,bottomandright) #andusethemostusedcolorasthecolortocrop. #---Fortransparentimages----------------------------------------------- if'A'inimage.getbands():#Iftheimagehasatransparencylayer,useit. #Thisworksforallmodeswhichhavetransparencylayer bbox=image.split()[list(image.getbands()).index('A')].getbbox() #---Fornon-transparentimages------------------------------------------- elifimage.mode=='RGB': ifnotbackgroundColor: backgroundColor=mostPopularEdgeColor(image) #Cropanon-transparentimage. #.getbbox()alwayscropstheblackcolor. #Soweneedtosubstractthe"background"colorfromourimage. bg=Image.new("RGB",image.size,backgroundColor) diff=ImageChops.difference(image,bg)#Substractbackgroundcolorfromimage bbox=diff.getbbox()#Trytofindtherealboundingboxoftheimage. else: raiseNotImplementedError,"Sorry,thisfunctionisnotimplementedyetforimagesinmode'%s'."%image.mode ifbbox: image=image.crop(bbox) returnimage #范例:裁剪透明图片: im=Image.open('myTransparentImage.png') cropped=autoCrop(im) cropped.show() #范例:裁剪非透明图片 im=Image.open('myImage.png') cropped=autoCrop(im) cropped.show()
总结
以上就是本文关于python自动裁剪图像代码分享的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感兴趣的朋友可以继续参阅本站:
python图像常规操作
python好玩的项目—色情图片识别代码分享
Python生成数字图片代码分享