好的,我自己拍的照片,在这里:
zY28f_64.png,zY28f_80.png,zY28f_96.png
以代码结束:
from PIL import Image,ImageOps
import os
path= 'images'
x = 0
for dirname,dirs,files in os.walk(path):
for filename in files:
x+=1
path = dirname + "/" + filename
print(path)
im = Image.open(path)
im.show()
fill_color = (255,255,255)
im = im.convert("RGBA")
if im.mode in ('RGBA','LA'):
background = Image.new(im.mode[:-1],im.size,fill_color)
# background.paste(im,im.split()[-1])
background.paste(im)
im = background
im_inv = ImageOps.invert(im) ### make white background black
imResize = ImageOps.fit(im.crop(im_inv.getbbox()),(96,96),Image.BOX,(0.5,0.5)) # im.crop crop on box got from image with black background,Image.getbbox works only with black bacground returning biggest box containing non zero(non black ) pixels
imResize.show()
# imResize.save("dataset/images/" + str(x) + '.png','PNG')
输出:
zY28f_64.png2.png,zY28f_80.png1.png,zY28f_96.png3.png
这里的主要变化:
使白底变黑
im_inv = ImageOps.invert(im)
从黑色背景图像获得的框上的 im.crop 裁剪,Image.getbbox 仅适用于黑色背景,返回包含非零(非黑色)像素的最大框
imResize = ImageOps.fit(im.crop(im_inv.getbbox()),0.5))
由于 ImageOps.fit(...)
行返回切碎的图像,不确定它是如何工作的,为了保留整个数字,我使用 PIL Image.resize() not resizing the picture 中的代码获取:
from PIL import Image,ImageOps
import os
import math
path= 'images'
x = 0
for dirname,files in os.walk(path):
for filename in files:
x+=1
path = dirname + "/" + filename
print(path)
im = Image.open(path)
fill_color = (255,im.split()[-1])
background.paste(im)
im = background
im_inv = ImageOps.invert(im)
imResize = im.crop(im_inv.getbbox())
width,height = imResize.size
print(width,height)
if height > width:
ratio = math.floor(height / width)
newheight = ratio * 96
print(imResize,ratio,newheight)
imResize = imResize.resize((96,newheight))
else:
ratio = math.floor(width /height )
newwidth = ratio * 96
print(imResize,newwidth)
imResize = imResize.resize((newwidth,96))
imResize.show()
print(imResize.size)
imResize.save(path + str(x) + '.png','PNG')
输出:
zY28f_64.png2.png,zY28f_96.png3.png
本文链接:https://www.f2er.com/733.html