有些视频的框架有黑色条状边框。我必须从框架中删除它们。我提出了一个粗略的解决方案:
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,也不会删除整个黑条。
这是原始图片:
这是运行程序后的图像:
有人可以建议更好地解决这个问题吗? 谢谢!
答案 0 :(得分:9)
此问题已在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()
我使用Pillow代替PIL:
pip install pillow
结果:
答案 1 :(得分:0)
为什么不计算框架并使用PIL
from PIL import Image
img = Image.open('myImage.jpeg')
box = (50, 50, 100, 100)
area = img.crop(box)
答案 2 :(得分:0)
我认为如果你在图像的另一边工作,你会发现问题消失了,因为你正在检查第一列(col [0] - 它是黑色的,所以你删除它和黑色col [1] ]变成col [0]然后你检查col [1] - 跳过新的col [0] ....
如果你从最大值开始它会起作用,或者如果你删除了它,你会留在任何给定的col。或者,您可以列出要删除的内容,将其反转,然后执行删除。
答案 3 :(得分:0)
使用opencv和numpy,就像你在尝试这样的事情:
im = cv2.imread(filename)
h,w,d = im.shape
#left limit
for i in range(w):
if np.sum(im[:,i,:]) > 0:
break
#right limit
for j in xrange(w-1,0,-1):
if np.sum(im[:,j,:]) > 0:
break
cropped = im[:,i:j+1,:].copy() # deep copy to get byte-aligned array needed for opencv