python消除图像模块区域_python - 从图像中删除所有空白区域 - SO中文参考 - www.soinside.com...

你可以通过for循环走很长的路

from PIL import Image, ImageChops

def getbox(im, color):

bg = Image.new(im.mode, im.size, color)

diff = ImageChops.difference(im, bg)

diff = ImageChops.add(diff, diff, 2.0, -100)

return diff.getbbox()

def split(im):

retur = []

emptyColor = im.getpixel((0, 0))

box = getbox(im, emptyColor)

width, height = im.size

pixels = im.getdata()

sub_start = 0

sub_width = 0

offset = box[1] * width

for x in range(width):

if pixels[x + offset] == emptyColor:

if sub_width > 0:

retur.append((sub_start, box[1], sub_width, box[3]))

sub_width = 0

sub_start = x + 1

else:

sub_width = x + 1

if sub_width > 0:

retur.append((sub_start, box[1], sub_width, box[3]))

return retur

这样可以轻松地检索图像中的裁剪框,如下所示:

im = Image.open("/home/einfochips/Documents/imagecomparsion/kroger_image_comparison/SnapshotImages/screenshot_Hide.png")

for idx, box in enumerate(split(im)):

im.crop(box).save("trim_{0}.png".format(idx))

如果您已经知道玩具想要提取的图像的大小,您可以使用

def split(im, box):

retur = []

pixels = im.getdata()

emptyColor = pixels[0]

width, height = im.size;

y = 0;

while y < height - box[3]:

x = 0

y_step = 1

while x < width - box[2]:

x_step = 1

if pixels[y*width + x] != emptyColor:

retur.append((x, y, box[2] + x, box[3] + y))

y_step = box[3] + 1

x_step = box[2] + 1

x += x_step

y += y_step

return retur

在呼叫中添加另一个参数

for idx, box in enumerate(split(im, (0, 0, 365, 150))):

im.crop(box).save("trim_{0}.png".format(idx))

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值