首页 > 解决方案 > 从视频帧中删除边框/边距

问题描述

我正在处理周围有边框(边距)的视频。有些沿所有 4 个侧面都有,有些仅沿左侧和右侧,有些仅沿顶部和底部。这些边距的长度也不是固定的。我正在从这些视频中提取帧,例如,

在此处输入图像描述

在此处输入图像描述

这两个都包含顶部和底部的边框。

谁能建议一些从这些图像中删除这些边框的方法(最好是在 Python 中)。我遇到了一些方法,比如在 Stackoverflow 上,但这处理的是边框完全黑色 (0,0,0) 的理想情况。但就我而言,它们可能不是漆黑的,也可能包含抖动的噪音。任何帮助/建议将不胜感激。

标签: pythonimageopencvimage-processingpython-imaging-library

解决方案


这是在 Python/OpenCV 中执行此操作的一种方法。

  • 阅读图片
  • 转换为灰度和反转
  • 临界点
  • 应用形态学去除小的黑色或白色区域,然后再次反转
  • 获取某一区域的轮廓
  • 获取该轮廓的边界框
  • 使用 numpy 切片裁剪图像的该区域以形成结果图像
  • 保存生成的图像


import cv2
import numpy as np

# read image
img = cv2.imread('gymnast.png')

# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# invert gray image
gray = 255 - gray

# gaussian blur
blur = cv2.GaussianBlur(gray, (3,3), 0)

# threshold
thresh = cv2.threshold(blur,236,255,cv2.THRESH_BINARY)[1]

# apply close and open morphology to fill tiny black and white holes
kernel = np.ones((5,5), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)

# invert thresh
thresh = 255 -thresh

# get contours (presumably just one around the nonzero pixels) 
# then crop it to bounding rectangle
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
cntr = contours[0]
x,y,w,h = cv2.boundingRect(cntr)
crop = img[y:y+h, x:x+w]

cv2.imshow("IMAGE", img)
cv2.imshow("THRESH", thresh)
cv2.imshow("CROP", crop)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save cropped image
cv2.imwrite('gymnast_crop.png',crop)
cv2.imwrite('gymnast_crop.png',crop)


输入:

在此处输入图像描述


阈值和清洁图像:

在此处输入图像描述

裁剪结果:

在此处输入图像描述


推荐阅读