python删除图片_在Python中移除图片的边框

Some videos have frames that have black strips like borders. I have to remove them from the frames. I came up with a crude solution:

import sys, cv2, numpy

import Image, scipy

filename = "snap.jpeg"

img = cv2.imread(filename)

def checkEqual(lst):

return len(set(lst)) <= 1 ##

def removeColumns(image):

for col in range(image.shape[1]):

for ch in range(3):

try:

checkEqual(image[:, col, ch].tolist())

except IndexError:

continue

else:

if checkEqual(image[:, col, ch].tolist()):

try:

image = numpy.delete(image, col, 1)

except IndexError:

continue

else:

pass

return image

img2 = removeColumns(img)

print img.shape, img2.shape ## (480, 856, 3) (480, 705, 3)

Here I find the columns that have the same elements and all the videos that I have have black borders. But even if I increase the maximum length in the function checkEqual() from 1 to 20 or 40, the whole black strip is not deleted.

This is the original image:

This is the image after running the program:

Could anyone give suggestion for a better solution to this problem ?

Thanks!

解决方案

This problem was already solved in this answer.

In [1]: from PIL import Image, ImageChops

In [3]: im = Image.open('iI3ZE.jpg')

In [4]: def trim(im):

...: bg = Image.new(im.mode, im.size, im.getpixel((0,0)))

...: diff = ImageChops.difference(im, bg)

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

...: bbox = diff.getbbox()

...: if bbox:

...: return im.crop(bbox)

...:

In [5]: trim(im).show()

I used Pillow instead of PIL:

pip install pillow

Results in:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值