在Python中移除图片的边框 [英] Removing borders from an image in 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 ## <-- This is the maximum length of the set
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)
在这里,我发现具有相同元素的列以及所有具有黑色边框的视频.但是,即使我将函数checkEqual()
中的最大长度从1增加到20或40,整个黑条也不会被删除.
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 image after running the program:
任何人都可以提出更好的解决方案的建议吗? 谢谢!
Could anyone give suggestion for a better solution to this problem ? Thanks!
推荐答案
此问题已在此答案中解决.
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()
我用枕头代替PIL:
pip install pillow
结果:
这篇关于在Python中移除图片的边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文