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: