python - 从视频帧中删除边框/边距
问题描述
我正在处理周围有边框(边距)的视频。有些沿所有 4 个侧面都有,有些仅沿左侧和右侧,有些仅沿顶部和底部。这些边距的长度也不是固定的。我正在从这些视频中提取帧,例如,
和
这两个都包含顶部和底部的边框。
谁能建议一些从这些图像中删除这些边框的方法(最好是在 Python 中)。我遇到了一些方法,比如在 Stackoverflow 上,但这处理的是边框完全黑色 (0,0,0) 的理想情况。但就我而言,它们可能不是漆黑的,也可能包含抖动的噪音。任何帮助/建议将不胜感激。
解决方案
这是在 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)
输入:
阈值和清洁图像:
裁剪结果:
推荐阅读
- c# - 无法获取数据视图字段的总和
- python - 为类文件自动生成 __iter__、readline() 和 readlines()?
- asp.net-mvc - 如何按尺寸和数量以及一次上色获得库存价值
- string - 将小数点前6位的字符串转换为Double
- python - JSONDecodeError:期望','分隔符:第1行第220200961列(char 220200960)
- python - 如何调用快速api文件上传路由
- arrays - 在 for 循环中删除重复项会使 Excel 崩溃
- python - 在看板视图中添加阶段 (Odoo 13)
- xml - 如何使用 curl 发送摘要身份验证请求?
- python-3.x - Sqlite3 - 熊猫模块“时间”没有属性“时钟”